org.apache.logging.log4j.LogManager类的使用及代码示例

x33g5p2x  于2022-01-23 转载在 其他  
字(13.0k)|赞(0)|评价(0)|浏览(1280)

本文整理了Java中org.apache.logging.log4j.LogManager类的一些代码示例,展示了LogManager类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。LogManager类的具体详情如下:
包路径:org.apache.logging.log4j.LogManager
类名称:LogManager

LogManager介绍

[英]The anchor point for the logging system. The most common usage of this class is to obtain a named Logger. The method #getLogger() is provided as the most convenient way to obtain a named Logger based on the calling class name. This class also provides method for obtaining named Loggers that use String#format(String,Object...) style messages instead of the default type of parameterized messages. These are obtained through the #getFormatterLogger(Class) family of methods. Other service provider methods are given through the #getContext() and #getFactory() family of methods; these methods are not normally useful for typical usage of Log4j.
[中]测井系统的定位点。此类最常见的用法是获取命名记录器。方法#getLogger()是根据调用类名获取命名记录器的最方便的方法。此类还提供了获取使用字符串#格式(字符串、对象…)的命名记录器的方法设置消息样式,而不是参数化消息的默认类型。这些是通过#getFormatterLogger(类)方法家族获得的。其他服务提供者方法通过#getContext()和#getFactory()方法家族给出;这些方法通常不适用于Log4j的典型用法。

代码示例

代码示例来源:origin: org.apache.logging.log4j/log4j-core

  1. @Override
  2. public void run() {
  3. final Logger logger = LogManager.getLogger("org.apache.logging.log4j.test.WorkerThread");
  4. logger.debug("Worker is running");
  5. }
  6. }

代码示例来源:origin: Graylog2/graylog2-server

  1. private void initializeLogging(final Level logLevel) {
  2. final LoggerContext context = (LoggerContext) LogManager.getContext(false);
  3. final org.apache.logging.log4j.core.config.Configuration config = context.getConfiguration();
  4. config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).setLevel(logLevel);
  5. config.getLoggerConfig(Main.class.getPackage().getName()).setLevel(logLevel);
  6. context.updateLoggers(config);
  7. }

代码示例来源:origin: javamelody/javamelody

  1. void register() {
  2. if (LogManager.getContext(false) instanceof LoggerContext) {
  3. final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
  4. if (ctx.getConfiguration() instanceof AbstractConfiguration) {
  5. final AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration();
  6. final Appender appender = getSingleton();
  7. appender.start();
  8. config.addAppender(appender);
  9. final Logger rootLogger = LogManager.getRootLogger();
  10. final LoggerConfig loggerConfig = config.getLoggerConfig(rootLogger.getName());
  11. loggerConfig.addAppender(appender, null, null);
  12. ctx.updateLoggers();
  13. }
  14. }
  15. }

代码示例来源:origin: org.apache.logging.log4j/log4j-api

  1. /**
  2. * Shutdown the logging system if the logging system supports it.
  3. * This is equivalent to calling {@code LogManager.shutdown(LogManager.getContext(currentContext))}.
  4. *
  5. * This call is synchronous and will block until shut down is complete.
  6. * This may include flushing pending log events over network connections.
  7. *
  8. * @param currentContext if true a default LoggerContext (may not be the LoggerContext used to create a Logger
  9. * for the calling class) will be used.
  10. * If false the LoggerContext appropriate for the caller of this method is used. For
  11. * example, in a web application if the caller is a class in WEB-INF/lib then one LoggerContext may be
  12. * used and if the caller is a class in the container's classpath then a different LoggerContext may
  13. * be used.
  14. * @since 2.6
  15. */
  16. public static void shutdown(final boolean currentContext) {
  17. shutdown(getContext(currentContext));
  18. }

代码示例来源:origin: javamelody/javamelody

  1. void deregister() {
  2. if (LogManager.getContext(false) instanceof LoggerContext) {
  3. final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
  4. if (ctx.getConfiguration() instanceof AbstractConfiguration) {
  5. final AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration();
  6. final Appender appender = getSingleton();
  7. appender.stop();
  8. config.removeAppender(appender.getName());
  9. final Logger rootLogger = LogManager.getRootLogger();
  10. final LoggerConfig loggerConfig = config.getLoggerConfig(rootLogger.getName());
  11. loggerConfig.removeAppender(appender.getName());
  12. ctx.updateLoggers();
  13. }
  14. }
  15. }

代码示例来源:origin: dadoonet/fscrawler

  1. LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
  2. Configuration config = ctx.getConfiguration();
  3. LoggerConfig loggerConfig = config.getLoggerConfig(FsCrawlerCli.class.getPackage().getName());
  4. logger.warn("--debug or --trace can't be used when --silent is set. Only silent mode will be activated.");
  5. logger.warn("--silent is set but no job has been defined. Add a job name or remove --silent option. Exiting.");
  6. jCommander.usage();
  7. return;
  8. LoggerConfig rootLogger = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
  9. loggerConfig.setLevel(Level.OFF);
  10. rootLogger.setLevel(Level.OFF);
  11. } else {
  12. loggerConfig.setLevel(commands.debug ? Level.DEBUG : Level.TRACE);
  13. ctx.updateLoggers();
  14. logger.info("No job specified. Here is the list of existing jobs:");

代码示例来源:origin: org.apache.logging.log4j/log4j-core

  1. @Test
  2. public void validateXmlSchema() throws Exception {
  3. final File file = new File("target", "XmlCompactFileAppenderValidationTest.log.xml");
  4. file.delete();
  5. final Logger log = LogManager.getLogger("com.foo.Bar");
  6. log.warn("Message 1");
  7. log.info("Message 2");
  8. log.debug("Message 3");
  9. Configurator.shutdown(this.loggerContext);
  10. this.validateXmlSchema(file);
  11. }

代码示例来源:origin: apache/hive

  1. Logger logger = LogManager.getLogger(LineageLogger.class);
  2. (org.apache.logging.log4j.core.Logger) logger;
  3. LoggerConfig loggerConfig = coreLogger.get();
  4. Map<String, Appender> appenders = loggerConfig.getAppenders();
  5. logger.debug("Debug Message Logged !!!");
  6. logger.info("Info Message Logged !!!");
  7. logger.error(errorString + i,
  8. new RuntimeException("part of a test"));

代码示例来源:origin: org.apache.logging.log4j/log4j-core

  1. /**
  2. * .
  3. */
  4. @Test
  5. public void testCircularCauseExceptions() {
  6. final Exception e1 = new Exception();
  7. final Exception e2 = new Exception(e1);
  8. e1.initCause(e2);
  9. LogManager.getLogger().error("Error", e1);
  10. }
  11. }

代码示例来源:origin: org.apache.logging.log4j/log4j-core

  1. @Test
  2. public void test1() {
  3. final Logger logger = LogManager.getLogger(BasicLoggingTest.class.getName());
  4. logger.debug("debug not set");
  5. logger.error("Test message");
  6. }
  7. }

代码示例来源:origin: org.apache.logging.log4j/log4j-core

  1. @Test
  2. public void testPropertiesConfiguration() {
  3. final Configuration config = context.getConfiguration();
  4. assertNotNull("No configuration created", config);
  5. assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
  6. final Map<String, Appender> appenders = config.getAppenders();
  7. assertNotNull(appenders);
  8. assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1);
  9. final Map<String, LoggerConfig> loggers = config.getLoggers();
  10. assertNotNull(loggers);
  11. assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 1);
  12. final Filter filter = config.getFilter();
  13. assertNotNull("No Filter", filter);
  14. assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
  15. final Logger logger = LogManager.getLogger(getClass());
  16. logger.info("Welcome to Log4j!");
  17. }
  18. }

代码示例来源:origin: org.apache.logging.log4j/log4j-core

  1. private void validateAppender(final LoggerContext loggerContext, final String expectedFilePattern) {
  2. final RollingFileAppender appender = loggerContext.getConfiguration().getAppender("fooAppender");
  3. Assert.assertNotNull(appender);
  4. Assert.assertEquals(expectedFilePattern, appender.getFilePattern());
  5. LogManager.getLogger("root").info("just to show it works.");
  6. }
  7. }

代码示例来源:origin: torodb/stampede

  1. ex.getErrorMessages().stream().forEach(m -> {
  2. if (m.getCause() != null) {
  3. LOGGER.error(m.getCause().getMessage());
  4. } else {
  5. LOGGER.error(m.getMessage());
  6. LogManager.shutdown();
  7. System.exit(1);
  8. LOGGER.debug("Fatal error on initialization", ex);
  9. Throwable rootCause = Throwables.getRootCause(ex);
  10. String causeMessage = rootCause.getMessage() != null ? rootCause.getMessage() :
  11. "internal error";
  12. LogManager.shutdown();
  13. JCommander.getConsole().println("Fatal error while ToroDB was starting: " + causeMessage);
  14. System.exit(1);

代码示例来源:origin: org.apache.logging.log4j/log4j-core

  1. /**
  2. * Validates that the code pattern we use to add an appender on the fly
  3. * works with a basic appender that is not the new OutputStream appender or
  4. * new Writer appender.
  5. */
  6. @Test
  7. public void testUpdatePatternWithFileAppender() {
  8. final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
  9. final Configuration config = ctx.getConfiguration();
  10. // @formatter:off
  11. final Appender appender = FileAppender.newBuilder()
  12. .withFileName("target/" + getClass().getName() + ".log")
  13. .withAppend(false)
  14. .withName("File")
  15. .withIgnoreExceptions(false)
  16. .withBufferedIo(false)
  17. .withBufferSize(4000)
  18. .setConfiguration(config)
  19. .build();
  20. // @formatter:on
  21. appender.start();
  22. config.addAppender(appender);
  23. ConfigurationTestUtils.updateLoggers(appender, config);
  24. LogManager.getLogger().error("FOO MSG");
  25. }
  26. }

代码示例来源:origin: org.apache.logging.log4j/log4j-core

  1. ThreadContext.put("KEY", "mapvalue");
  2. final Logger log = LogManager.getLogger("com.foo.Bar");
  3. final LoggerContext loggerContext = LogManager.getContext(false);
  4. final String loggerContextName = loggerContext.getClass().getSimpleName();
  5. RingBufferAdmin ring;
  6. ThreadContext.remove("count");
  7. log.info("{} {} {} i={}", contextImpl, contextMap(), loggerContextName, Unbox.box(i));
  8. LogManager.shutdown();

代码示例来源:origin: org.apache.logging.log4j/log4j-core

  1. public static void main(final String[] args) {
  2. MainMapLookup.setMainArguments(args);
  3. try (final LoggerContext ctx = Configurator.initialize(MainInputArgumentsLookupTest.class.getName(),
  4. "target/test-classes/log4j-lookup-main.xml")) {
  5. LogManager.getLogger().error("this is an error message");
  6. }
  7. }

代码示例来源:origin: org.apache.logging.log4j/log4j-core

  1. @Override
  2. protected void log(final int runNumber) {
  3. if (runNumber == 2) {
  4. // System.out.println("Set a breakpoint here.");
  5. }
  6. final Logger logger = LogManager.getLogger("auditcsvfile");
  7. final int val1 = 9, val2 = 11, val3 = 12;
  8. logger.info("Info Message!", val1, val2, val3);
  9. logger.info("Info Message!", val1, val2, val3);
  10. logger.info("Info Message!", val1, val2, val3);
  11. }

代码示例来源:origin: org.apache.logging.log4j/log4j-core

  1. private void validate(final Configuration config) {
  2. assertNotNull(config);
  3. assertNotNull(config.getName());
  4. assertFalse(config.getName().isEmpty());
  5. assertNotNull("No configuration created", config);
  6. assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
  7. final Map<String, Appender> appenders = config.getAppenders();
  8. assertNotNull(appenders);
  9. assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2);
  10. final LoggerConfig rootLoggerConfig = loggers.get("");
  11. assertEquals(Level.ERROR, rootLoggerConfig.getLevel());
  12. assertFalse(rootLoggerConfig.isIncludeLocation());
  13. final LoggerConfig loggerConfig = loggers.get("org.apache.logging.log4j");
  14. assertEquals(Level.DEBUG, loggerConfig.getLevel());
  15. assertTrue(loggerConfig.isIncludeLocation());
  16. final Filter filter = config.getFilter();
  17. assertEquals("Panic", customLevel.getLevelName());
  18. assertEquals(17, customLevel.getIntLevel());
  19. final Logger logger = LogManager.getLogger(getClass());
  20. logger.info("Welcome to Log4j!");

代码示例来源:origin: org.apache.logging.log4j/log4j-core

  1. final File file = new File("target/test-classes/log4j2-config.xml");
  2. assertTrue("setLastModified should have succeeded.", file.setLastModified(System.currentTimeMillis() - 120000));
  3. ctx = Configurator.initialize("Test1", "target/test-classes/log4j2-config.xml");
  4. final Logger logger = LogManager.getLogger("org.apache.test.TestConfigurator");
  5. Configuration config = ctx.getConfiguration();
  6. assertNotNull("No configuration", config);
  7. assertEquals("Incorrect Configuration.", CONFIG_NAME, config.getName());
  8. final Map<String, Appender> map = config.getAppenders();
  9. assertNotNull("Appenders map should not be null.", map);
  10. assertThat(map, hasSize(greaterThan(0)));
  11. TimeUnit.SECONDS.sleep(config.getWatchManager().getIntervalSeconds()+1);
  12. for (int i = 0; i < 17; ++i) {
  13. logger.debug("Test message " + i);
  14. if (is(theInstance(config)).matches(ctx.getConfiguration())) {
  15. Thread.sleep(500);
  16. final Configuration newConfig = ctx.getConfiguration();
  17. assertThat("Configuration not reset", newConfig, is(not(theInstance(config))));
  18. Configurator.shutdown(ctx);
  19. config = ctx.getConfiguration();
  20. assertEquals("Unexpected Configuration.", NullConfiguration.NULL_NAME, config.getName());

代码示例来源:origin: org.apache.logging.log4j/log4j-core

  1. @Test
  2. public void testConsecutiveReconfigure() throws Exception {
  3. System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
  4. "AsyncLoggerConfigTest2.xml");
  5. final File file = new File("target", "AsyncLoggerConfigTest2.log");
  6. assertTrue("Deleted old file before test", !file.exists() || file.delete());
  7. final Logger log = LogManager.getLogger("com.foo.Bar");
  8. final String msg = "Message before reconfig";
  9. log.info(msg);
  10. final LoggerContext ctx = LoggerContext.getContext(false);
  11. ctx.reconfigure();
  12. ctx.reconfigure();
  13. final String msg2 = "Message after reconfig";
  14. log.info(msg2);
  15. CoreLoggerContexts.stopLoggerContext(file); // stop async thread
  16. final BufferedReader reader = new BufferedReader(new FileReader(file));
  17. final String line1 = reader.readLine();
  18. final String line2 = reader.readLine();
  19. reader.close();
  20. file.delete();
  21. assertNotNull("line1", line1);
  22. assertNotNull("line2", line2);
  23. assertTrue("line1 " + line1, line1.contains(msg));
  24. assertTrue("line2 " + line2, line2.contains(msg2));
  25. }

相关文章