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

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

本文整理了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

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

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

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

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

void register() {
  if (LogManager.getContext(false) instanceof LoggerContext) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    if (ctx.getConfiguration() instanceof AbstractConfiguration) {
      final AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration();
      final Appender appender = getSingleton();
      appender.start();
      config.addAppender(appender);
      final Logger rootLogger = LogManager.getRootLogger();
      final LoggerConfig loggerConfig = config.getLoggerConfig(rootLogger.getName());
      loggerConfig.addAppender(appender, null, null);
      ctx.updateLoggers();
    }
  }
}

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

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

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

void deregister() {
  if (LogManager.getContext(false) instanceof LoggerContext) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    if (ctx.getConfiguration() instanceof AbstractConfiguration) {
      final AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration();
      final Appender appender = getSingleton();
      appender.stop();
      config.removeAppender(appender.getName());
      final Logger rootLogger = LogManager.getRootLogger();
      final LoggerConfig loggerConfig = config.getLoggerConfig(rootLogger.getName());
      loggerConfig.removeAppender(appender.getName());
      ctx.updateLoggers();
    }
  }
}

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

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

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

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

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

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

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

/**
   * .
   */
  @Test
  public void testCircularCauseExceptions() {
    final Exception e1 = new Exception();
    final Exception e2 = new Exception(e1);
    e1.initCause(e2);
    LogManager.getLogger().error("Error", e1);
  }
}

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

@Test
  public void test1() {
    final Logger logger = LogManager.getLogger(BasicLoggingTest.class.getName());
    logger.debug("debug not set");
    logger.error("Test message");
  }
}

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

@Test
  public void testPropertiesConfiguration() {
    final Configuration config = context.getConfiguration();
    assertNotNull("No configuration created", config);
    assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
    final Map<String, Appender> appenders = config.getAppenders();
    assertNotNull(appenders);
    assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1);
    final Map<String, LoggerConfig> loggers = config.getLoggers();
    assertNotNull(loggers);
    assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 1);
    final Filter filter = config.getFilter();
    assertNotNull("No Filter", filter);
    assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
    final Logger logger = LogManager.getLogger(getClass());
    logger.info("Welcome to Log4j!");
  }
}

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

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

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

ex.getErrorMessages().stream().forEach(m -> {
  if (m.getCause() != null) {
   LOGGER.error(m.getCause().getMessage());
  } else {
   LOGGER.error(m.getMessage());
 LogManager.shutdown();
 System.exit(1);
LOGGER.debug("Fatal error on initialization", ex);
Throwable rootCause = Throwables.getRootCause(ex);
String causeMessage = rootCause.getMessage() != null ? rootCause.getMessage() : 
  "internal error";
LogManager.shutdown();
JCommander.getConsole().println("Fatal error while ToroDB was starting: " + causeMessage);
System.exit(1);

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

/**
   * Validates that the code pattern we use to add an appender on the fly
   * works with a basic appender that is not the new OutputStream appender or
   * new Writer appender.
   */
  @Test
  public void testUpdatePatternWithFileAppender() {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    // @formatter:off
    final Appender appender = FileAppender.newBuilder()
      .withFileName("target/" + getClass().getName() + ".log")
      .withAppend(false)
      .withName("File")
      .withIgnoreExceptions(false)
      .withBufferedIo(false)
      .withBufferSize(4000)
      .setConfiguration(config)
      .build();
    // @formatter:on
    appender.start();
    config.addAppender(appender);
    ConfigurationTestUtils.updateLoggers(appender, config);
    LogManager.getLogger().error("FOO MSG");
  }
}

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

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

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

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

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

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

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

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

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

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

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

@Test
public void testConsecutiveReconfigure() throws Exception {
  System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
      "AsyncLoggerConfigTest2.xml");
  final File file = new File("target", "AsyncLoggerConfigTest2.log");
  assertTrue("Deleted old file before test", !file.exists() || file.delete());
  
  final Logger log = LogManager.getLogger("com.foo.Bar");
  final String msg = "Message before reconfig";
  log.info(msg);
  final LoggerContext ctx = LoggerContext.getContext(false);
  ctx.reconfigure();
  ctx.reconfigure();
  
  final String msg2 = "Message after reconfig";
  log.info(msg2);
  CoreLoggerContexts.stopLoggerContext(file); // stop async thread
  final BufferedReader reader = new BufferedReader(new FileReader(file));
  final String line1 = reader.readLine();
  final String line2 = reader.readLine();
  reader.close();
  file.delete();
  assertNotNull("line1", line1);
  assertNotNull("line2", line2);
  assertTrue("line1 " + line1, line1.contains(msg));
  assertTrue("line2 " + line2, line2.contains(msg2));
}

相关文章