Java Code Examples for org.apache.logging.log4j.core.LoggerContext#getContext()
The following examples show how to use
org.apache.logging.log4j.core.LoggerContext#getContext() .
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: JdbcAppenderBenchmark.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@Setup public void setup() throws Exception { connectionHSQLDB = getConnectionHSQLDB(); connectionH2 = getConnectionH2(); createTable(connectionHSQLDB, toCreateTableSqlStringHQLDB("fmLogEntry")); createTable(connectionH2, toCreateTableSqlStringH2("fmLogEntry")); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "log4j2-jdbc-appender.xml"); final LoggerContext context = LoggerContext.getContext(false); if (context.getConfiguration() instanceof DefaultConfiguration) { context.reconfigure(); } StatusLogger.getLogger().reset(); loggerH2 = LogManager.getLogger("H2Logger"); loggerHSQLDB = LogManager.getLogger("HSQLDBLogger"); }
Example 2
Source File: EncodingPatternConverterTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@Test public void testReplacement() { final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName(EncodingPatternConverterTest.class.getName()) // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage("Test \r\n<div class=\"test\">this</div> & <div class='test'>that</div>")) .build(); final StringBuilder sb = new StringBuilder(); final LoggerContext ctx = LoggerContext.getContext(); final String[] options = new String[]{"%msg"}; final EncodingPatternConverter converter = EncodingPatternConverter .newInstance(ctx.getConfiguration(), options); assertNotNull("Error creating converter", converter); converter.format(event, sb); assertEquals( "Test \\r\\n<div class="test">this</div> & <div class='test'>that</div>", sb.toString()); }
Example 3
Source File: AbstractJpaAppenderTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
public void tearDown() throws SQLException { final LoggerContext context = LoggerContext.getContext(false); try { String appenderName = "databaseAppender"; final Appender appender = context.getConfiguration().getAppender(appenderName); assertNotNull("The appender '" + appenderName + "' should not be null.", appender); assertTrue("The appender should be a JpaAppender.", appender instanceof JpaAppender); ((JpaAppender) appender).getManager().close(); } finally { System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); PropertiesUtil.getProperties().reload(); context.reconfigure(); StatusLogger.getLogger().reset(); try (Statement statement = this.connection.createStatement();) { statement.execute("SHUTDOWN"); } this.connection.close(); } }
Example 4
Source File: RollingFileAppenderAccessTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
/** * Not a real test, just make sure we can compile access to the typed manager. * * @throws IOException */ @Test public void testAccessManagerWithBuilder() throws IOException { try (final LoggerContext ctx = LoggerContext.getContext(false)) { final Configuration config = ctx.getConfiguration(); final File file = File.createTempFile("RollingFileAppenderAccessTest", ".tmp"); file.deleteOnExit(); // @formatter:off final RollingFileAppender appender = RollingFileAppender.newBuilder() .setFileName(file.getCanonicalPath()) .setFilePattern("FilePattern") .setName("Name") .setPolicy(OnStartupTriggeringPolicy.createPolicy(1)) .setConfiguration(config) .build(); // @formatter:on final RollingFileManager manager = appender.getManager(); // Since the RolloverStrategy and TriggeringPolicy are immutable, we could also use generics to type their // access. Assert.assertNotNull(manager.getRolloverStrategy()); Assert.assertNotNull(manager.getTriggeringPolicy()); } }
Example 5
Source File: Log4jBridgeHandler.java From logging-log4j2 with Apache License 2.0 | 5 votes |
/** Perform init. of this handler with given configuration (typical use is for constructor). */ protected void init(boolean debugOutput, String suffixToAppend, boolean propagateLevels) { this.doDebugOutput = debugOutput; if (debugOutput) { new Exception("DIAGNOSTIC ONLY (sysout): Log4jBridgeHandler instance created (" + this + ")") .printStackTrace(System.out); // is no error thus no syserr } if (suffixToAppend != null) { suffixToAppend = suffixToAppend.trim(); // remove spaces if (suffixToAppend.isEmpty()) { suffixToAppend = null; } else if (suffixToAppend.charAt(0) != '.') { // always make it a sub-logger suffixToAppend = '.' + suffixToAppend; } } this.julSuffixToAppend = suffixToAppend; //not needed: this.installAsLevelPropagator = propagateLevels; if (propagateLevels) { @SuppressWarnings("resource") // no need to close the AutoCloseable ctx here LoggerContext context = LoggerContext.getContext(false); context.addPropertyChangeListener(this); propagateLogLevels(context.getConfiguration()); // note: java.util.logging.LogManager.addPropertyChangeListener() could also // be set here, but a call of JUL.readConfiguration() will be done on purpose } SLOGGER.debug("Log4jBridgeHandler init. with: suffix='{}', lvlProp={}, instance={}", suffixToAppend, propagateLevels, this); }
Example 6
Source File: EqualsReplacementConverterTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
private void testReplacement(final String expectedValue, final String[] options) { final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName(EqualsReplacementConverterTest.class.getName()) // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage(TEST_MESSAGE)) // .build(); final StringBuilder sb = new StringBuilder(); final LoggerContext ctx = LoggerContext.getContext(); final EqualsReplacementConverter converter = EqualsReplacementConverter.newInstance(ctx.getConfiguration(), options); converter.format(event, sb); assertEquals(expectedValue, sb.toString()); }
Example 7
Source File: VariablesNotEmptyReplacementConverterTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
private void testReplacement(final String tag, final String expectedValue) { final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName(VariablesNotEmptyReplacementConverterTest.class.getName()) // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage("This is a test")) // .build(); final StringBuilder sb = new StringBuilder(); final LoggerContext ctx = LoggerContext.getContext(); final String[] options = new String[] { "[" + tag + "]" }; final VariablesNotEmptyReplacementConverter converter = VariablesNotEmptyReplacementConverter .newInstance(ctx.getConfiguration(), options); converter.format(event, sb); assertEquals(expectedValue, sb.toString()); }
Example 8
Source File: JpaAppenderBenchmark.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Setup public void setup() throws Exception { connectionHSQLDB = getConnectionHSQLDB(); connectionH2 = getConnectionH2(); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "log4j2-jpa-appender.xml"); final LoggerContext context = LoggerContext.getContext(false); if (context.getConfiguration() instanceof DefaultConfiguration) { context.reconfigure(); } StatusLogger.getLogger().reset(); loggerH2 = LogManager.getLogger("H2Logger"); loggerHSQLDB = LogManager.getLogger("HSQLDBLogger"); }
Example 9
Source File: L4jLogProvider.java From studio with GNU General Public License v3.0 | 5 votes |
/** * return a list of active loggers */ @SuppressWarnings("unchecked") public Map<String, Logger> getLoggers() { LoggerContext context = LoggerContext.getContext(false); return context.getLoggers().stream().collect(Collectors.toMap( org.apache.logging.log4j.core.Logger::getName, logger -> new LoggerImpl(org.slf4j.LoggerFactory.getLogger(logger.getName())) )); }
Example 10
Source File: CassandraLog4JManager.java From jesterj with Apache License 2.0 | 5 votes |
protected CassandraLog4JManager(String name) { super(LoggerContext.getContext(), name); System.out.println(">>>> Creating CassandraLog4JManager"); CassandraSupport cassandra = new CassandraSupport(); Callable<Object> makeTables = new Callable<Object>() { @Override public Object call() throws Exception { System.out.println("Table and key space creation thread started"); boolean tryAgain = true; int tryCount = 0; // ugly but effective fix for https://github.com/nsoft/jesterj/issues/1 while(tryAgain) { try { CqlSession session = cassandra.getSession(); session.execute(CREATE_LOG_KEYSPACE); session.execute(CREATE_LOG_TABLE); session.execute(CREATE_FT_TABLE); session.execute(FTI_STATUS_INDEX); session.execute(FTI_SCANNER_INDEX); tryAgain = false; } catch (Exception e) { tryCount++; // complain and die if we can't set up the tables in cassandra. e.printStackTrace(); Thread.sleep(1000); if (tryCount > 10) { die(e); tryAgain = false; } } } return null; } }; this.cassandraReady = cassandra.whenBooted(makeTables); }
Example 11
Source File: Rfc5424LayoutTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@BeforeClass public static void setupClass() { StatusLogger.getLogger().setLevel(Level.OFF); ConfigurationFactory.setConfigurationFactory(cf); final LoggerContext ctx = LoggerContext.getContext(); ctx.reconfigure(); }
Example 12
Source File: RollingAppenderUncompressedTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@AfterClass public static void cleanupClass() { System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); final LoggerContext ctx = LoggerContext.getContext(); ctx.reconfigure(); StatusLogger.getLogger().reset(); }
Example 13
Source File: JavaInstanceRunnable.java From pulsar with Apache License 2.0 | 5 votes |
private void removeLogTopicHandler() { if (logAppender == null) return; LoggerContext context = LoggerContext.getContext(false); Configuration config = context.getConfiguration(); for (final LoggerConfig loggerConfig : config.getLoggers().values()) { loggerConfig.removeAppender(logAppender.getName()); } config.getRootLogger().removeAppender(logAppender.getName()); }
Example 14
Source File: AdvertiserTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Test public void testAdvertisementsRemovedOnConfigStop() { verifyExpectedEntriesAdvertised(InMemoryAdvertiser.getAdvertisedEntries()); final LoggerContext ctx = LoggerContext.getContext(); ctx.stop(); final Map<Object, Map<String, String>> entries = InMemoryAdvertiser.getAdvertisedEntries(); assertTrue("Entries found: " + entries, entries.isEmpty()); //reconfigure for subsequent testing ctx.start(); }
Example 15
Source File: XmlConfigurationPropsTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Test public void testNoProps() { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG); final LoggerContext ctx = LoggerContext.getContext(); ctx.reconfigure(); final Configuration config = ctx.getConfiguration(); assertTrue("Configuration is not an XmlConfiguration", config instanceof XmlConfiguration); }
Example 16
Source File: DynamicThresholdFilterTest.java From logging-log4j2 with Apache License 2.0 | 4 votes |
@After public void cleanup() { final LoggerContext ctx = LoggerContext.getContext(false); ctx.reconfigure(); StatusLogger.getLogger().reset(); }
Example 17
Source File: XmlLayoutTest.java From logging-log4j2 with Apache License 2.0 | 4 votes |
@BeforeClass public static void setupClass() { ConfigurationFactory.setConfigurationFactory(cf); final LoggerContext ctx = LoggerContext.getContext(); ctx.reconfigure(); }
Example 18
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 19
Source File: SmokeTestBase.java From log4j2-elasticsearch with Apache License 2.0 | 4 votes |
public final void createLoggerProgrammatically(Supplier<ElasticsearchAppender.Builder> appenderBuilder, Function<Configuration, AsyncLoggerConfigDelegate> delegateSupplier) { LoggerContext ctx = LoggerContext.getContext(false); final Configuration config = ctx.getConfiguration(); Appender appender = appenderBuilder.get().build(); appender.start(); AppenderRef ref = AppenderRef.createAppenderRef(DEFAULT_APPENDER_NAME, Level.INFO, null); AppenderRef[] refs = new AppenderRef[] {ref}; // set up disruptor forcefully ((LifeCycle)delegateSupplier.apply(config)).start(); AsyncLoggerConfig loggerConfig = (AsyncLoggerConfig) AsyncLoggerConfig.createLogger(false, Level.INFO, DEFAULT_LOGGER_NAME, "false", refs, null, config, null ); loggerConfig.addAppender(appender, Level.INFO, null); config.addAppender(appender); config.addLogger(DEFAULT_LOGGER_NAME, loggerConfig); }
Example 20
Source File: SyslogLayoutTest.java From logging-log4j2 with Apache License 2.0 | 4 votes |
@BeforeClass public static void setupClass() { ConfigurationFactory.setConfigurationFactory(cf); final LoggerContext ctx = LoggerContext.getContext(); ctx.reconfigure(); }