Java Code Examples for org.apache.logging.log4j.core.LoggerContext#getLogger()
The following examples show how to use
org.apache.logging.log4j.core.LoggerContext#getLogger() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Log4j2Test.java From sofa-common-tools with Apache License 2.0 | 6 votes |
@Test public void testIndependentSpaceLog4j2() throws URISyntaxException { // LoggerFactory.getLogger(LogbackTest.class).info("xxx"); URL url1 = LogbackTest.class.getResource("/com/alipay/sofa/rpc/log/log4j2/log-conf.xml"); LoggerContext lc1 = new LoggerContext("rest", null, url1.toURI()); lc1.start(); org.apache.logging.log4j.core.Logger logger1 = lc1.getLogger("com.foo.Bar"); logger1.info("log4j2 - 1"); Assert.assertNotNull(logger1); //log4j2 logger2 URL url2 = LogbackTest.class.getResource("/com/alipay/sofa/rpc/log/log4j2/log4j2_b.xml"); LoggerContext lc2 = new LoggerContext("rpc", null, url2.toURI()); lc2.start(); org.apache.logging.log4j.core.Logger logger2 = lc2.getLogger("com.foo.Bar2"); logger2.info("log4j2 - 2"); Assert.assertNotNull(logger2); Assert.assertNotSame(logger1, logger2); }
Example 2
Source File: Log4j2MetricsTest.java From micrometer with Apache License 2.0 | 6 votes |
@Test void noDuplicateLoggingCountWhenMultipleNonAdditiveLoggersShareConfig() { LoggerContext loggerContext = new LoggerContext("test"); LoggerConfig loggerConfig = new LoggerConfig("com.test", Level.INFO, false); Configuration configuration = loggerContext.getConfiguration(); configuration.addLogger("com.test", loggerConfig); loggerContext.setConfiguration(configuration); loggerContext.updateLoggers(); Logger logger1 = loggerContext.getLogger("com.test.log1"); loggerContext.getLogger("com.test.log2"); new Log4j2Metrics(emptyList(), loggerContext).bindTo(registry); assertThat(registry.get("log4j2.events").tags("level", "info").counter().count()).isEqualTo(0); logger1.info("Hello, world!"); assertThat(registry.get("log4j2.events").tags("level", "info").counter().count()).isEqualTo(1); }
Example 3
Source File: CsvJsonParameterLayoutFileAppenderTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
public void testNoNulCharacters(final String message, final String expected) throws IOException { @SuppressWarnings("resource") final LoggerContext loggerContext = loggerContextRule.getLoggerContext(); final Logger logger = loggerContext.getLogger("com.example"); logger.error("log:", message); loggerContext.stop(); final File file = new File(FILE_PATH); final byte[] contents = FileUtils.readFileToByteArray(file); int count0s = 0; final StringBuilder sb = new StringBuilder(); for (int i = 0; i < contents.length; i++) { final byte b = contents[i]; if (b == 0) { sb.append(i); sb.append(", "); count0s++; } } Assert.assertEquals("File contains " + count0s + " 0x00 byte at indices " + sb, 0, count0s); final List<String> readLines = FileUtils.readLines(file, Charset.defaultCharset()); final String actual = readLines.get(0); // Assert.assertTrue(actual, actual.contains(message)); Assert.assertEquals(actual, expected, actual); Assert.assertEquals(1, readLines.size()); }
Example 4
Source File: MissingRootLoggerTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@Test public void testMissingRootLogger() throws Exception { final LoggerContext ctx = context.getLoggerContext(); final Logger logger = ctx.getLogger("sample.Logger1"); assertTrue("Logger should have the INFO level enabled", logger.isInfoEnabled()); assertFalse("Logger should have the DEBUG level disabled", logger.isDebugEnabled()); final Configuration config = ctx.getConfiguration(); assertNotNull("Config not null", config); // final String MISSINGROOT = "MissingRootTest"; // assertTrue("Incorrect Configuration. Expected " + MISSINGROOT + " but found " + config.getName(), // MISSINGROOT.equals(config.getName())); final Map<String, Appender> map = config.getAppenders(); assertNotNull("Appenders not null", map); assertThat("There should only be two appenders", map, hasSize(2)); assertThat(map, hasKey("List")); assertThat(map, hasKey("DefaultConsole-2")); final Map<String, LoggerConfig> loggerMap = config.getLoggers(); assertNotNull("loggerMap not null", loggerMap); assertThat("There should only be one configured logger", loggerMap, hasSize(1)); // only the sample logger, no root logger in loggerMap! assertThat("contains key=sample", loggerMap, hasKey("sample")); final LoggerConfig sample = loggerMap.get("sample"); final Map<String, Appender> sampleAppenders = sample.getAppenders(); assertThat("The sample logger should only have one appender", sampleAppenders, hasSize(1)); // sample only has List appender, not Console! assertThat("The sample appender should be a ListAppender", sampleAppenders, hasKey("List")); assertThat(config, is(instanceOf(AbstractConfiguration.class))); final AbstractConfiguration baseConfig = (AbstractConfiguration) config; final LoggerConfig root = baseConfig.getRootLogger(); final Map<String, Appender> rootAppenders = root.getAppenders(); assertThat("The root logger should only have one appender", rootAppenders, hasSize(1)); // root only has Console appender! assertThat("The root appender should be a ConsoleAppender", rootAppenders, hasKey("DefaultConsole-2")); assertEquals(Level.ERROR, root.getLevel()); }
Example 5
Source File: Log4j2Configuration.java From summerframework with Apache License 2.0 | 5 votes |
@SuppressWarnings("deprecation") @Override public void init() { try { LoggerContext loggerContext = (LoggerContext)LogManager.getContext(false); if (loggerContext == null) return; org.apache.logging.log4j.core.Logger logger = loggerContext.getLogger("org.apache.kafka.clients.producer.ProducerConfig"); if (logger != null) { logger.setLevel(org.apache.logging.log4j.Level.ERROR); } createBizLogger(); Configuration configuration = loggerContext.getConfiguration(); configuration.getPluginPackages().add("org.apache.skywalking.apm.toolkit.log.log4j.v2.x"); Map<String, Appender> appenders = configuration.getAppenders(); for (Appender appender : appenders.values()) { Layout<? extends Serializable> layout = appender.getLayout(); if (layout instanceof PatternLayout) { PatternLayout patternLayOut = (PatternLayout)layout; Serializer serializer = PatternLayout.createSerializer(configuration, null, getLog4jPattern(), getLog4jPattern(), null, true, true); Field field = patternLayOut.getClass().getDeclaredField("eventSerializer"); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); if (!field.isAccessible()) { field.setAccessible(true); } field.set(patternLayOut, serializer); } } loggerContext.updateLoggers(); } catch (Throwable e) { logger.warn(e.getMessage()); } }
Example 6
Source File: LoggerLogic.java From syncope with Apache License 2.0 | 5 votes |
private LoggerTO delete(final String name, final LoggerType expectedType) { Logger syncopeLogger = loggerDAO.find(name); if (syncopeLogger == null) { throw new NotFoundException("Logger " + name); } if (expectedType != syncopeLogger.getType()) { throwInvalidLogger(expectedType); } LoggerTO loggerToDelete = binder.getLoggerTO(syncopeLogger); // remove SyncopeLogger from local storage, so that LoggerLoader won't load this next time loggerDAO.delete(syncopeLogger); // set log level to OFF in order to disable configured logger until next reboot LoggerContext ctx = (LoggerContext) LogManager.getContext(false); String auditLoggerName = AuditLoggerName.getAuditEventLoggerName( AuthContextUtils.getDomain(), syncopeLogger.getKey()); org.apache.logging.log4j.core.Logger logger = SyncopeConstants.ROOT_LOGGER.equals(name) ? ctx.getLogger(LogManager.ROOT_LOGGER_NAME) : LoggerType.AUDIT.equals(syncopeLogger.getType()) ? ctx.getLogger(auditLoggerName) : ctx.getLogger(name); logger.setLevel(Level.OFF); ctx.updateLoggers(); return loggerToDelete; }
Example 7
Source File: ContextDataProviderTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@BeforeClass public static void beforeClass() { ThreadContextDataInjector.contextDataProviders.add(new TestContextDataProvider()); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "target/test-classes/log4j-contextData.xml"); LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); logger = loggerContext.getLogger(ContextDataProviderTest.class.getName()); appender = loggerContext.getConfiguration().getAppender("List"); assertNotNull("No List appender", appender); }
Example 8
Source File: AsyncAppenderShutdownTimeoutTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Test(timeout = 5000) public void shutdownTest() throws Exception { final LoggerContext ctx = (LoggerContext)LogManager.getContext(false); final Logger logger = ctx.getLogger("Logger"); logger.info("This is a test"); ctx.stop(); }
Example 9
Source File: Log4j2LoggerSpaceFactory.java From sofa-common-tools with Apache License 2.0 | 4 votes |
private Logger newLogger(String name, LoggerContext loggerContext) { final String key = Logger.ROOT_LOGGER_NAME.equals(name) ? LogManager.ROOT_LOGGER_NAME : name; return new Log4jLogger(loggerContext.getLogger(key), name); }
Example 10
Source File: CloudStorageLoggerFactory.java From ambari-logsearch with Apache License 2.0 | 4 votes |
public static Logger createLogger(Input input, LoggerContext loggerContext, LogFeederProps logFeederProps) { boolean useJsonFormat = logFeederProps.isCloudStorageUseFilters(); String type = input.getLogType().replace(LogFeederConstants.CLOUD_PREFIX, ""); String uniqueThreadName = input.getThread().getName(); Configuration config = loggerContext.getConfiguration(); String baseDir = logFeederProps.getRolloverConfig().getRolloverArchiveBaseDir(); String destination = logFeederProps.getCloudStorageDestination().getText(); String clusterHostnameBaseDir = Paths.get(baseDir, destination, logFeederProps.getClusterName(), LogFeederUtil.hostName).toFile().getAbsolutePath(); String activeLogDir = Paths.get(clusterHostnameBaseDir, ACTIVE_FOLDER, type).toFile().getAbsolutePath(); String archiveLogDir = Paths.get(clusterHostnameBaseDir, ARCHIVED_FOLDER, type).toFile().getAbsolutePath(); boolean useGzip = logFeederProps.getRolloverConfig().isUseGzip(); final String archiveFilePattern; if (useJsonFormat) { archiveFilePattern = useGzip ? JSON_DATE_PATTERN_SUFFIX_GZ : JSON_DATE_PATTERN_SUFFIX; } else { archiveFilePattern = useGzip ? DATE_PATTERN_SUFFIX_GZ : DATE_PATTERN_SUFFIX; } String logSuffix = useJsonFormat ? ".json" : ".log"; String fileName = String.join(File.separator, activeLogDir, type + logSuffix); String filePattern = String.join(File.separator, archiveLogDir, type + archiveFilePattern); PatternLayout layout = PatternLayout.newBuilder() .withPattern(PatternLayout.DEFAULT_CONVERSION_PATTERN).build(); String rolloverSize = logFeederProps.getRolloverConfig().getRolloverSize().toString() + logFeederProps.getRolloverConfig().getRolloverSizeFormat(); SizeBasedTriggeringPolicy sizeBasedTriggeringPolicy = SizeBasedTriggeringPolicy.createPolicy(rolloverSize); final Integer thresholdMin = logFeederProps.getRolloverConfig().getRolloverThresholdTimeMins(); final Integer thresholdInterval = thresholdMin * 60000; // 1 min = 60000 milliseconds TimeBasedTriggeringPolicy timeBasedTriggeringPolicy = TimeBasedTriggeringPolicy.newBuilder() .withInterval(thresholdInterval) .build(); final CompositeTriggeringPolicy compositeTriggeringPolicy; if (logFeederProps.getRolloverConfig().isRolloverOnStartup()) { OnStartupTriggeringPolicy onStartupTriggeringPolicy = OnStartupTriggeringPolicy.createPolicy(1); compositeTriggeringPolicy = CompositeTriggeringPolicy .createPolicy(sizeBasedTriggeringPolicy, timeBasedTriggeringPolicy, onStartupTriggeringPolicy); } else { compositeTriggeringPolicy = CompositeTriggeringPolicy .createPolicy(sizeBasedTriggeringPolicy, timeBasedTriggeringPolicy); } DefaultRolloverStrategy defaultRolloverStrategy = DefaultRolloverStrategy.newBuilder() .withMax(String.valueOf(logFeederProps.getRolloverConfig().getRolloverMaxBackupFiles())) .build(); boolean immediateFlush = logFeederProps.getRolloverConfig().isImmediateFlush(); RollingFileAppender appender = RollingFileAppender.newBuilder() .withFileName(fileName) .withFilePattern(filePattern) .withLayout(layout) .withName(type) .withPolicy(compositeTriggeringPolicy) .withStrategy(defaultRolloverStrategy) .withImmediateFlush(immediateFlush) .build(); appender.start(); config.addAppender(appender); AppenderRef ref = AppenderRef.createAppenderRef(type, null, null); AppenderRef[] refs = new AppenderRef[] {ref}; LoggerConfig loggerConfig = LoggerConfig .createLogger(false, Level.ALL, input.getThread().getName(), "true", refs, null, config, null); loggerConfig.addAppender(appender, null, null); config.addLogger(uniqueThreadName, loggerConfig); loggerContext.updateLoggers(); return loggerContext.getLogger(uniqueThreadName); }
Example 11
Source File: SmtpAppenderTest.java From logging-log4j2 with Apache License 2.0 | 4 votes |
@Test public void testDelivery() { final String subjectKey = getClass().getName(); final String subjectValue = "SubjectValue1"; ThreadContext.put(subjectKey, subjectValue); final int smtpPort = AvailablePortFinder.getNextAvailable(); final SmtpAppender appender = SmtpAppender.newBuilder() .setName("Test") .setTo("[email protected]") .setCc("[email protected]") .setBcc("[email protected]") .setFrom("[email protected]") .setReplyTo("[email protected]") .setSubject("Subject Pattern %X{" + subjectKey + "}") .setSmtpHost(HOST) .setSmtpPort(smtpPort) .setBufferSize(3) .build(); appender.start(); final LoggerContext context = LoggerContext.getContext(); final Logger root = context.getLogger("SMTPAppenderTest"); root.addAppender(appender); root.setAdditive(false); root.setLevel(Level.DEBUG); final SimpleSmtpServer server = SimpleSmtpServer.start(smtpPort); root.debug("Debug message #1"); root.debug("Debug message #2"); root.debug("Debug message #3"); root.debug("Debug message #4"); root.error("Error with exception", new RuntimeException("Exception message")); root.error("Error message #2"); server.stop(); assertTrue(server.getReceivedEmailSize() == 2); final Iterator<SmtpMessage> messages = server.getReceivedEmail(); final SmtpMessage email = messages.next(); assertEquals("[email protected]", email.getHeaderValue("To")); assertEquals("[email protected]", email.getHeaderValue("Cc")); // assertEquals("[email protected]", email.getHeaderValue("Bcc")); // BCC // can't be tested with Dumpster 1.6 assertEquals("[email protected]", email.getHeaderValue("From")); assertEquals("[email protected]", email.getHeaderValue("Reply-To")); final String headerValue = email.getHeaderValue("Subject"); assertEquals(headerValue, "Subject Pattern " + subjectValue); final String body = email.getBody(); assertFalse(body.contains("Debug message #1")); assertTrue(body.contains("Debug message #2")); assertTrue(body.contains("Debug message #3")); assertTrue(body.contains("Debug message #4")); assertTrue(body.contains("Error with exception")); assertTrue(body.contains("RuntimeException")); assertTrue(body.contains("Exception message")); assertFalse(body.contains("Error message #2")); final SmtpMessage email2 = messages.next(); final String body2 = email2.getBody(); assertFalse(body2.contains("Debug message #4")); assertFalse(body2.contains("Error with exception")); assertTrue(body2.contains("Error message #2")); }
Example 12
Source File: CustomConfigurationTest.java From logging-log4j2 with Apache License 2.0 | 4 votes |
@Test public void testConfig() { // don't bother using "error" since that's the default; try another level final LoggerContext ctx = this.init.getLoggerContext(); ctx.reconfigure(); final Configuration config = ctx.getConfiguration(); assertThat(config, instanceOf(XmlConfiguration.class)); for (final StatusListener listener : StatusLogger.getLogger().getListeners()) { if (listener instanceof StatusConsoleListener) { assertSame(listener.getStatusLevel(), Level.INFO); break; } } final Layout<? extends Serializable> layout = PatternLayout.newBuilder() .setPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN) .setConfiguration(config) .build(); // @formatter:off final FileAppender appender = FileAppender.newBuilder() .setFileName(LOG_FILE) .setAppend(false) .setName("File") .setIgnoreExceptions(false) .setBufferSize(4000) .setBufferedIo(false) .setLayout(layout) .build(); // @formatter:on appender.start(); config.addAppender(appender); final AppenderRef ref = AppenderRef.createAppenderRef("File", null, null); final AppenderRef[] refs = new AppenderRef[] {ref}; final LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "org.apache.logging.log4j", "true", refs, null, config, null ); loggerConfig.addAppender(appender, null, null); config.addLogger("org.apache.logging.log4j", loggerConfig); ctx.updateLoggers(); final Logger logger = ctx.getLogger(CustomConfigurationTest.class.getName()); logger.info("This is a test"); final File file = new File(LOG_FILE); assertThat(file, exists()); assertThat(file, hasLength(greaterThan(0L))); }