org.apache.logging.log4j.core.LoggerContext Java Examples
The following examples show how to use
org.apache.logging.log4j.core.LoggerContext.
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: ConsoleAppenderAnsiStyleLayoutMain.java From logging-log4j2 with Apache License 2.0 | 7 votes |
public void test(final String[] args) { System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable // System.out.println(System.getProperty("java.class.path")); final String config = args == null || args.length == 0 ? "target/test-classes/log4j2-console-style-ansi.xml" : args[0]; try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config)) { final Logger logger = LogManager.getLogger(ConsoleAppenderAnsiStyleLayoutMain.class); logger.fatal("Fatal message."); logger.error("Error message."); logger.warn("Warning message."); logger.info("Information message."); logger.debug("Debug message."); logger.trace("Trace message."); logger.error("Error message.", new IOException("test")); } }
Example #2
Source File: LoggingInitialization.java From ghidra with Apache License 2.0 | 7 votes |
/** * Use this to override the default application log file, before you * initialize the logging system. * * @param file The file to use as the application log file */ synchronized static void setApplicationLogFile(File file) { if (APPLICATION_LOG_FILE != null && !SystemUtilities.isInTestingMode()) { // don't throw the exception so that we may can continue to work System.err.println("Cannot change the log file once it has been " + "initialized!\nYou must call this method before calling " + "LoggingInitialization.initializeLoggingSystem()"); (new IllegalStateException()).printStackTrace(); } APPLICATION_LOG_FILE = file; // Need to set the system property that the log4j2 configuration reads in // order to determine the log file name. Once that's set, the log // configuration must be 'kicked' to pick up the change. System.setProperty("logFilename", file.getAbsolutePath()); if (INITIALIZED) { ((LoggerContext) LogManager.getContext(false)).reconfigure(); } }
Example #3
Source File: LoggingInitialization.java From ghidra with Apache License 2.0 | 6 votes |
/** * Use this to override the default application log file, before you * initialize the logging system. * * @param file The file to use as the application log file */ synchronized static void setScriptLogFile(File file) { if (SCRIPT_LOG_FILE != null && !SystemUtilities.isInTestingMode()) { // don't throw the exception so that we may can continue to work System.err.println("Cannot change the log file once it has been " + "initialized!\nYou must call this method before calling " + "LoggingInitialization.initializeLoggingSystem()"); (new IllegalStateException()).printStackTrace(); } SCRIPT_LOG_FILE = file; // Need to set the system property that the log4j2 configuration reads in // order to determine the script log file name. Once that's set, the log // configuration must be 'kicked' to pick up the change. System.setProperty("scriptLogFilename", file.getAbsolutePath()); if (INITIALIZED) { ((LoggerContext) LogManager.getContext(false)).reconfigure(); } }
Example #4
Source File: RewriteAppenderTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@Test public void testRewrite() throws Exception { Logger logger = LogManager.getLogger("test"); ThreadContext.put("key1", "This is a test"); ThreadContext.put("hello", "world"); logger.debug("Say hello"); LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false); Configuration configuration = context.getConfiguration(); Map<String, Appender> appenders = configuration.getAppenders(); ListAppender eventAppender = null; for (Map.Entry<String, Appender> entry : appenders.entrySet()) { if (entry.getKey().equals("events")) { eventAppender = (ListAppender) ((AppenderAdapter.Adapter) entry.getValue()).getAppender(); } } assertNotNull("No Event Appender", eventAppender); List<LoggingEvent> events = eventAppender.getEvents(); assertTrue("No events", events != null && events.size() > 0); assertNotNull("No properties in the event", events.get(0).getProperties()); assertTrue("Key was not inserted", events.get(0).getProperties().containsKey("key2")); assertEquals("Key value is incorrect", "Log4j", events.get(0).getProperties().get("key2")); }
Example #5
Source File: Log4j2LoggingHelper.java From herd with Apache License 2.0 | 6 votes |
@Override public StringWriter addLoggingWriterAppender(String appenderName) { // Get the configuration final LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); final Configuration configuration = loggerContext.getConfiguration(); // Create a string writer as part of the appender so logging will be written to it. StringWriter stringWriter = new StringWriter(); // Create and start the appender with the string writer. Appender appender = WriterAppender.createAppender(null, null, stringWriter, appenderName, false, true); appender.start(); // Add the appender to the root logger. configuration.getRootLogger().addAppender(appender, null, null); // Return the string writer. return stringWriter; }
Example #6
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 #7
Source File: Configurator.java From logging-log4j2 with Apache License 2.0 | 6 votes |
/** * Sets the levels of <code>parentLogger</code> and all 'child' loggers to the given <code>level</code>. * @param parentLogger the parent logger * @param level the new level */ public static void setAllLevels(final String parentLogger, final Level level) { // 1) get logger config // 2) if exact match, use it, if not, create it. // 3) set level on logger config // 4) update child logger configs with level // 5) update loggers final LoggerContext loggerContext = LoggerContext.getContext(false); final Configuration config = loggerContext.getConfiguration(); boolean set = setLevel(parentLogger, level, config); for (final Map.Entry<String, LoggerConfig> entry : config.getLoggers().entrySet()) { if (entry.getKey().startsWith(parentLogger)) { set |= setLevel(entry.getValue(), level); } } if (set) { loggerContext.updateLoggers(); } }
Example #8
Source File: Log4J2Logger.java From ignite with Apache License 2.0 | 6 votes |
/** {@inheritDoc} */ @Override public void setNodeId(UUID nodeId) { A.notNull(nodeId, "nodeId"); this.nodeId = nodeId; // Set nodeId as system variable to be used at configuration. System.setProperty(NODE_ID, U.id8(nodeId)); if (inited) { final LoggerContext ctx = impl.getContext(); synchronized (mux) { inited = false; } addConsoleAppenderIfNeeded(new C1<Boolean, Logger>() { @Override public Logger apply(Boolean init) { if (init) ctx.reconfigure(); return (Logger)LogManager.getRootLogger(); } }); } }
Example #9
Source File: TestLogLevelAnnotations.java From lucene-solr with Apache License 2.0 | 6 votes |
/** * Directly test the methods in the {@link LogLevel} annotation class */ @LogLevel("org.apache.solr.bogus_logger.MethodLogLevel=TRACE") public void testWhiteBoxMethods() { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); final Map<String,Level> oldLevels = LogLevel.Configurer.setLevels(bogus_logger_prefix + "=TRACE"); // assertEquals(oldLevels.toString(), 1, oldLevels.size()); assertNull(oldLevels.get(bogus_logger_prefix)); // assertEquals(Level.TRACE, config.getLoggerConfig(bogus_logger_prefix).getLevel()); assertEquals(Level.TRACE, LogManager.getLogger(bogus_logger_prefix).getLevel()); // restore (to 'unset' values)... LogLevel.Configurer.restoreLogLevels(oldLevels); assertEquals(bogus_logger_prefix + " should have had it's config unset; should now return the 'root' LoggerConfig", config.getRootLogger(), config.getLoggerConfig(bogus_logger_prefix)); assertEquals(DEFAULT_LOG_LEVEL, LogManager.getLogger(bogus_logger_prefix).getLevel()); }
Example #10
Source File: Log4j2Configuration.java From summerframework with Apache License 2.0 | 6 votes |
private void createBizLogger() { if (env.containsProperty(MonitorConfigSpringApplicationRunListener.LOG_KAFKA_BOOTSTRAPSERVERS)) { String appenderName = "AdvancedKafkaAppender"; LoggerContext loggerContext = (LoggerContext)LogManager.getContext(false); Configuration configuration = loggerContext.getConfiguration(); AdvancedKafkaAppender kafkaAppender = AdvancedKafkaAppender.createAppender(CustomJsonLayout.createDefaultLayout(), null, configuration, appenderName, getKafkaTopic(), getBootstrapservers()); kafkaAppender.start(); AppenderRef ref = AppenderRef.createAppenderRef(appenderName, null, null); AppenderRef[] refs = new AppenderRef[] {ref}; LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "BizLogger", null, refs, null, configuration, null); loggerConfig.addAppender(kafkaAppender, null, null); configuration.addLogger("BizLogger", loggerConfig); } }
Example #11
Source File: LoggingConfigurator.java From TweetwallFX with MIT License | 6 votes |
/** * Configures Logging in case it has not been configured via this method * before. */ public static void configure() { if (ALREADY_CONFIGURED.compareAndSet(false, true)) { final File log4jFile = new File("log4j2.xml"); if (log4jFile.isFile()) { LoggerContext context = (LoggerContext) LogManager.getContext(false); context.setConfigLocation(log4jFile.toURI()); } else { final Logger logger = LogManager.getLogger(LoggingConfigurator.class); logger.info("log4j configuration file ('" + log4jFile.getAbsolutePath() + "') not found."); } } }
Example #12
Source File: DynamicThresholdFilterTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@Test public void testConfig() { try (final LoggerContext ctx = Configurator.initialize("Test1", "target/test-classes/log4j2-dynamicfilter.xml")) { final Configuration config = ctx.getConfiguration(); final Filter filter = config.getFilter(); assertNotNull("No DynamicThresholdFilter", filter); assertTrue("Not a DynamicThresholdFilter", filter instanceof DynamicThresholdFilter); final DynamicThresholdFilter dynamic = (DynamicThresholdFilter) filter; final String key = dynamic.getKey(); assertNotNull("Key is null", key); assertEquals("Incorrect key value", "loginId", key); final Map<String, Level> map = dynamic.getLevelMap(); assertNotNull("Map is null", map); assertEquals("Incorrect number of map elements", 1, map.size()); } }
Example #13
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 testAccessManagerWithStrings() 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 #14
Source File: ClassLoaderContextSelector.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@Override public void shutdown(final String fqcn, final ClassLoader loader, final boolean currentContext, final boolean allContexts) { LoggerContext ctx = null; if (currentContext) { ctx = ContextAnchor.THREAD_CONTEXT.get(); } else if (loader != null) { ctx = findContext(loader); } else { final Class<?> clazz = StackLocatorUtil.getCallerClass(fqcn); if (clazz != null) { ctx = findContext(clazz.getClassLoader()); } if (ctx == null) { ctx = ContextAnchor.THREAD_CONTEXT.get(); } } if (ctx != null) { ctx.stop(DEFAULT_STOP_TIMEOUT, TimeUnit.MILLISECONDS); } }
Example #15
Source File: LoggingMixin.java From picocli with Apache License 2.0 | 5 votes |
private void configureAppender(LoggerContext loggerContext, Level level) { final LoggerConfig rootConfig = loggerContext.getConfiguration().getRootLogger(); for (Appender appender : rootConfig.getAppenders().values()) { if (appender instanceof ConsoleAppender) { rootConfig.removeAppender(appender.getName()); rootConfig.addAppender(appender, level, null); } } if (rootConfig.getLevel().isMoreSpecificThan(level)) { rootConfig.setLevel(level); } loggerContext.updateLoggers(); }
Example #16
Source File: JiraLog4j2_2134Test.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Test public void testRefreshMinimalCodeStart() { Logger log = LogManager.getLogger(this.getClass()); final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); ctx.start(config); log.error("Info message"); }
Example #17
Source File: LoggerPanelAppender.java From jmeter-debugger with Apache License 2.0 | 5 votes |
public LoggerPanelAppender(String name, LoggerPanelWrapping panelWrapping) { super(name, null, PatternLayout.newBuilder().withPattern(DEFAULT_PATTERN).build()); start(); Configuration configuration = ((LoggerContext) LogManager.getContext(false)).getConfiguration(); configuration.getRootLogger().addAppender(this, Level.INFO, null); this.panelWrapping = panelWrapping; initializeProcessLogEventMethod(); initializeLogEventObjectConstructor(); }
Example #18
Source File: Configurator.java From logging-log4j2 with Apache License 2.0 | 5 votes |
/** * Initializes the Logging Context. * @param name The Context name. * @param loader The ClassLoader for the Context (or null). * @param configLocation The configuration for the logging context (or null). * @param externalContext The external context to be attached to the LoggerContext * @return The LoggerContext. */ public static LoggerContext initialize(final String name, final ClassLoader loader, final URI configLocation, final Object externalContext) { try { final Log4jContextFactory factory = getFactory(); return factory == null ? null : factory.getContext(FQCN, loader, externalContext, false, configLocation, name); } catch (final Exception ex) { LOGGER.error("There was a problem initializing the LoggerContext [{}] using configuration at [{}].", name, configLocation, ex); } return null; }
Example #19
Source File: RetentionExpirationExporterApp.java From herd with Apache License 2.0 | 5 votes |
/** * The main method of the application. * * @param args the command line arguments passed to the program. * * @throws java.io.FileNotFoundException if the logging file couldn't be found. */ @SuppressWarnings("PMD.DoNotCallSystemExit") // Using System.exit is allowed for an actual application to exit. public static void main(String[] args) throws FileNotFoundException { ToolsCommonConstants.ReturnValue returnValue; try { // Initialize Log4J with the resource. The configuration itself can use "monitorInterval" to have it refresh if it came from a file. LoggerContext loggerContext = Configurator.initialize(null, ToolsCommonConstants.LOG4J_CONFIG_LOCATION); // For some initialization errors, a null context will be returned. if (loggerContext == null) { // We shouldn't get here since we already checked if the location existed previously. throw new IllegalArgumentException("Invalid configuration found at resource location: \"" + ToolsCommonConstants.LOG4J_CONFIG_LOCATION + "\"."); } RetentionExpirationExporterApp retentionExpirationExporterApp = new RetentionExpirationExporterApp(); returnValue = retentionExpirationExporterApp.go(args); } catch (Exception e) { LOGGER.error("Error running herd retention expiration exporter application. {}", e.toString(), e); returnValue = ToolsCommonConstants.ReturnValue.FAILURE; } // Exit with the return code. System.exit(returnValue.getReturnCode()); }
Example #20
Source File: AuditLogConfiguration.java From audit-log-plugin with MIT License | 5 votes |
private void reloadLogger() { if(this.logDestination != null && !this.logDestination.equals("")){ System.setProperty("auditFileName", this.logDestination); } else { System.clearProperty("auditFileName"); } if(this.appenderType != null){ System.setProperty("appenderType", this.appenderType); } else { System.clearProperty("appenderType"); } if(this.syslogHost != null && !this.syslogHost.equals("")){ System.setProperty("syslogHost", this.syslogHost); } else { System.clearProperty("syslogHost"); } if(this.syslogPort != 0){ System.setProperty("syslogPort", String.valueOf(this.syslogPort)); } else { System.clearProperty("syslogPort"); } if(this.enterpriseNumber != 0){ System.setProperty("enterpriseNumber", String.valueOf(this.enterpriseNumber)); } else { System.clearProperty("enterpriseNumber"); } LoggerContext.getContext(false).reconfigure(); }
Example #21
Source File: LoggerContextAdmin.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Override public void propertyChange(final PropertyChangeEvent evt) { if (!LoggerContext.PROPERTY_CONFIG.equals(evt.getPropertyName())) { return; } final Notification notif = new Notification(NOTIF_TYPE_RECONFIGURED, getObjectName(), nextSeqNo(), now(), null); sendNotification(notif); }
Example #22
Source File: LogUtil.java From fix-orchestra with Apache License 2.0 | 5 votes |
public static Logger initializeDefaultLogger(Level level, Class<?> clazz) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); final ConsoleAppender appender = ConsoleAppender.newBuilder().setName("Console").build(); config.addAppender(appender); final AppenderRef ref = AppenderRef.createAppenderRef("Console", level, null); final AppenderRef[] refs = new AppenderRef[] {ref}; final LoggerConfig loggerConfig = LoggerConfig.createLogger(true, level, clazz.getName(), null, refs, null, config, null); config.addLogger(clazz.getName(), loggerConfig); ctx.updateLoggers(); return LogManager.getLogger(clazz); }
Example #23
Source File: ConsoleAppenderAnsiMessagesMain.java From logging-log4j2 with Apache License 2.0 | 5 votes |
public static void main(final String[] args) { System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), "target/test-classes/log4j2-console.xml")) { LOG.fatal("\u001b[1;35mFatal message.\u001b[0m"); LOG.error("\u001b[1;31mError message.\u001b[0m"); LOG.warn("\u001b[0;33mWarning message.\u001b[0m"); LOG.info("\u001b[0;32mInformation message.\u001b[0m"); LOG.debug("\u001b[0;36mDebug message.\u001b[0m"); LOG.trace("\u001b[0;30mTrace message.\u001b[0m"); LOG.error("\u001b[1;31mError message.\u001b[0m", new IOException("test")); } }
Example #24
Source File: Jira739Test.java From logging-log4j2 with Apache License 2.0 | 5 votes |
public static void main(final String[] args) { try (final LoggerContext ctx = Configurator.initialize(Jira739Test.class.getName(), "target/test-classes/LOG4J2-739.xml")) { for (int i = 0; i < 10; i++) { LOG.trace("Entering Log4j Example " + i + " times"); LOG.error("Ohh!Failed!"); LOG.trace("Exiting Log4j Example." + i + " times"); } } }
Example #25
Source File: DefaultRewriteAuditAppender.java From syncope with Apache License 2.0 | 5 votes |
@Override public void init(final String domain) { super.init(domain); rewriteAppender = RewriteAppender.createAppender( getTargetAppenderName() + "_rewrite", "true", new AppenderRef[] { AppenderRef.createAppenderRef(getTargetAppenderName(), Level.DEBUG, null) }, ((LoggerContext) LogManager.getContext(false)).getConfiguration(), getRewritePolicy(), null); }
Example #26
Source File: MyXMLConfiguration.java From tutorials with MIT License | 5 votes |
@Override protected void doConfigure() { super.doConfigure(); final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); LoggerConfig loggerConfig = config.getLoggerConfig("com"); final Layout layout = PatternLayout.createLayout("[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n", null, config, null, null, false, false, null, null); Appender appender = FileAppender.createAppender("target/test.log", "false", "false", "File", "true", "false", "false", "4000", layout, null, "false", null, config); loggerConfig.addAppender(appender, Level.DEBUG, null); addAppender(appender); }
Example #27
Source File: SOFAConfigurationFactory.java From sofa-common-tools with Apache License 2.0 | 5 votes |
@Override public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) { if (source != null && source != ConfigurationSource.NULL_SOURCE) { return loggerContext.getExternalContext() != null ? new SOFAConfiguration() : new XmlConfiguration(loggerContext, source); } return null; }
Example #28
Source File: BasicConfigurationFactory.java From logging-log4j2 with Apache License 2.0 | 5 votes |
public BasicConfiguration(final LoggerContext loggerContext) { super(loggerContext, ConfigurationSource.NULL_SOURCE); final LoggerConfig root = getRootLogger(); setName("BasicConfiguration"); final String levelName = System.getProperty(DEFAULT_LEVEL); final Level level = (levelName != null && Level.getLevel(levelName) != null) ? Level.getLevel(levelName) : Level.DEBUG; root.setLevel(level); }
Example #29
Source File: LoggingConfigurator.java From teku with Apache License 2.0 | 5 votes |
public static synchronized void update(final LoggingConfiguration configuration) { COLOR.set(configuration.isColorEnabled()); DESTINATION = configuration.getDestination(); INCLUDE_EVENTS = configuration.isIncludeEventsEnabled(); INCLUDE_VALIDATOR_DUTIES = configuration.isIncludeValidatorDutiesEnabled(); FILE = configuration.getFile(); FILE_PATTERN = configuration.getFileNamePattern(); final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); addLoggers((AbstractConfiguration) ctx.getConfiguration()); ctx.updateLoggers(); }
Example #30
Source File: LogConfiguration.java From wekaDeeplearning4j with GNU General Public License v3.0 | 5 votes |
/** * Apply the logging configuration. */ public void apply() { LoggerContext context = getLoggerContext(); Configuration config = context.getConfiguration(); ConfigurationSource configSource = config.getConfigurationSource(); String packageHomeDir = WekaPackageManager.getPackageHome().getPath(); if (ConfigurationSource.NULL_SOURCE.equals(configSource)) { // Use log4j2.xml shipped with the package ... URI uri = Paths.get(packageHomeDir, "wekaDeeplearning4j", "src", "main", "resources", "log4j2.xml").toUri(); context.setConfigLocation(uri); log.info("Logging configuration loaded from source: {}", uri.toString()); } String fileAppenderName = "fileAppender"; if (!context.getRootLogger().getAppenders().containsKey(fileAppenderName)) { // Get console appender layout Appender consoleAppender = context.getLogger(log.getName()).getAppenders().get("Console"); Layout<? extends Serializable> layout = consoleAppender.getLayout(); // Add file appender String filePath = resolveLogFilePath(); FileAppender.Builder appenderBuilder = new FileAppender.Builder(); appenderBuilder.withFileName(filePath); appenderBuilder.withAppend(append); appenderBuilder.withName(fileAppenderName); appenderBuilder.withLayout(layout); FileAppender appender = appenderBuilder.build(); appender.start(); context.getRootLogger().addAppender(appender); } }