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

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

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

Logger介绍

[英]This is the central interface in the log4j package. Most logging operations, except configuration, are done through this interface.

The canonical way to obtain a Logger for a class is through LogManager#getLogger(). Typically, each class gets its own Logger named after its fully qualified class name (the default Logger name when obtained through the LogManager#getLogger() method). Thus, the simplest way to use this would be like so:

public class MyClass { 
private static final Logger LOGGER = LogManager.getLogger(); 
// ... 
}

For ease of filtering, searching, sorting, etc., it is generally a good idea to create Loggers for each class rather than sharing Loggers. Instead, Marker should be used for shared, filterable identification.

For service provider implementations, it is recommended to extend the org.apache.logging.log4j.spi.AbstractLogger class rather than implementing this interface directly.
Since 2.4, methods have been added to the Logger interface to support lambda expressions. The new methods allow client code to lazily log messages without explicitly checking if the requested log level is enabled. For example, previously one would write:

// pre-Java 8 style optimization: explicitly check the log level 
// to make sure the expensiveOperation() method is only called if necessary 
if (logger.isTraceEnabled()) { 
logger.trace("Some long-running operation returned {}", expensiveOperation()); 
}

With Java 8, the same effect can be achieved with a lambda expression:

// Java-8 style optimization: no need to explicitly check the log level: 
// the lambda expression is not evaluated if the TRACE level is not enabled 
logger.trace("Some long-running operation returned {}", () -> expensiveOperation());

Note that although MessageSupplier is provided, using Supplier works just the same. MessageSupplier was deprecated in 2.6 and un-deprecated in 2.8.1. Anonymous class usage of these APIs should prefer using Supplier instead.
[中]这是log4j包中的中央接口。除配置外,大多数日志记录操作都是通过此接口完成的。
获取类的记录器的标准方法是通过LogManager#getLogger()。通常,每个类都以其完全限定类名(通过LogManager#getLogger()方法获得时的默认记录器名称)命名自己的记录器。因此,最简单的使用方法如下:

public class MyClass { 
private static final Logger LOGGER = LogManager.getLogger(); 
// ... 
}

为了便于过滤、搜索、排序等,通常最好为每个类创建记录器,而不是共享记录器。相反,标记应该用于共享的、可过滤的标识。
对于服务提供商实现,建议扩展组织。阿帕奇。登录中。log4j。spi。AbstractLogger类,而不是直接实现此接口。
自2.4以来,已将方法添加到记录器接口以支持lambda表达式。新方法允许客户端代码延迟记录消息,而无需显式检查请求的日志级别是否已启用。例如,前面会写:

// pre-Java 8 style optimization: explicitly check the log level 
// to make sure the expensiveOperation() method is only called if necessary 
if (logger.isTraceEnabled()) { 
logger.trace("Some long-running operation returned {}", expensiveOperation()); 
}

对于Java 8,使用lambda表达式可以实现相同的效果:

// Java-8 style optimization: no need to explicitly check the log level: 
// the lambda expression is not evaluated if the TRACE level is not enabled 
logger.trace("Some long-running operation returned {}", () -> expensiveOperation());

请注意,尽管提供了MessageSupplier,但使用Supplier的工作原理是一样的。MessageSupplier在2.6中已弃用,在2.8.1中未弃用。这些API的匿名类使用应该更倾向于使用供应商。

代码示例

代码示例来源:origin: apache/incubator-dubbo

@Override
public void error(String msg) {
  logger.error(msg);
}

代码示例来源:origin: apache/incubator-dubbo

@Override
public void info(String msg, Throwable e) {
  logger.info(msg, e);
}

代码示例来源:origin: apache/incubator-dubbo

@Override
public void debug(String msg) {
  logger.debug(msg);
}

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

public static void main(final String[] args) {
  try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),
      "target/test-classes/log4j2-console-highlight-logback.xml")) {
    LOG.fatal("Fatal message.");
    LOG.error("Error message.");
    LOG.warn("Warning message.");
    LOG.info("Information message.");
    LOG.debug("Debug message.");
    LOG.trace("Trace message.");
    LOG.error("Error message.", new IOException("test"));
  }
}

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

@Test
  public void logger3() {
    logger3.traceEntry();
    logger3.debug(testMarker, "debug message");
    logger3.error("Test Message");
    logger3.info(testMarker, "Info Message");
    logger3.warn("warn Message");
    logger3.traceExit();
    assertThat(app1.getEvents(), hasSize(4));
  }
}

代码示例来源: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: floragunncom/search-guard

@Override
public void success(String id, Tuple<Long, Settings> settings) {
  if(latch.getCount() <= 0) {
    log.error("Latch already counted down (for {} of {})  (index={})", id, Arrays.toString(events), searchguardIndex);
  }
  
  rs.put(id, settings);
  latch.countDown();
  if(log.isDebugEnabled()) {
    log.debug("Received config for {} (of {}) with current latch value={}", id, Arrays.toString(events), latch.getCount());
  }
}

代码示例来源:origin: apache/incubator-dubbo

@Override
public void warn(String msg, Throwable e) {
  logger.warn(msg, e);
}

代码示例来源:origin: floragunncom/search-guard

public Set<String> reduce(Resolved resolved, User user, String[] actions, IndexNameExpressionResolver resolver, ClusterService cs) {
  Set<String> retVal = new HashSet<>();
  for(SgRole sgr: roles) {
    retVal.addAll(sgr.getAllResolvedPermittedIndices(resolved, user, actions, resolver, cs));
  }
  if(log.isDebugEnabled()) {
    log.debug("Reduced requested resolved indices {} to permitted indices {}.", resolved, retVal.toString());
  }
  return Collections.unmodifiableSet(retVal);
}

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

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");
    }
  }
}

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

@Override
public String buildSSLArguments(DistributedSystemConfig config) {
 if (logger.isTraceEnabled(LogMarker.MANAGED_ENTITY_VERBOSE)) {
  logger.trace(LogMarker.MANAGED_ENTITY_VERBOSE,
    "DisabledManagedEntityController#buildSSLArguments {}", EXCEPTION_MESSAGE);
 }
 throw new UnsupportedOperationException(EXCEPTION_MESSAGE);
}

代码示例来源:origin: apache/incubator-dubbo

@Override
public void trace(String msg, Throwable e) {
  logger.trace(msg, e);
}

代码示例来源:origin: apache/incubator-dubbo

@Override
public boolean isDebugEnabled() {
  return logger.isDebugEnabled();
}

代码示例来源:origin: apache/incubator-dubbo

@Override
public boolean isTraceEnabled() {
  return logger.isTraceEnabled();
}

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

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-highlight-default.xml")) {
    LOG.fatal("Fatal message.");
    LOG.error("Error message.");
    LOG.warn("Warning message.");
    LOG.info("Information message.");
    LOG.debug("Debug message.");
    LOG.trace("Trace message.");
    LOG.error("Error message.", new IOException("test"));
  }
}

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

@Test
  public void logger3() {
    logger3.traceEntry();
    logger3.debug(testMarker, "debug message");
    logger3.error("Test Message");
    logger3.info(testMarker, "Info Message");
    logger3.warn("warn Message");
    logger3.traceExit();
    final List<LogEvent> events = app1.getEvents();
    assertEquals("Incorrect number of events. Expected 4, actual " + events.size(), 4, events.size());
  }
}

代码示例来源:origin: floragunncom/search-guard

@Override
public void success(String type, Tuple<Long, Settings> settings) {
  if(latch.getCount() <= 0) {
    log.error("Latch already counted down (for {} of {})  (index={})", type, Arrays.toString(events), searchguardIndex);
  }
  
  rs.put(type, settings);
  latch.countDown();
  if(log.isDebugEnabled()) {
    log.debug("Received config for {} (of {}) with current latch value={}", type, Arrays.toString(events), latch.getCount());
  }
}

代码示例来源:origin: apache/incubator-dubbo

@Override
public void warn(String msg) {
  logger.warn(msg);
}

代码示例来源:origin: floragunncom/search-guard

public Boolean hasNode(DiscoveryNode node) {
  if(nodes == null) {
    if(log.isDebugEnabled()) {
      log.debug("Cluster Info Holder not initialized yet for 'nodes'");
    }
    return null;
  }
  
  return nodes.nodeExists(node)?Boolean.TRUE:Boolean.FALSE;
}

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

private static String readStringUTFFromDataInput(DataInput in) throws IOException {
 if (logger.isTraceEnabled(LogMarker.SERIALIZER_VERBOSE)) {
  logger.trace(LogMarker.SERIALIZER_VERBOSE, "Reading utf STRING");
 }
 return in.readUTF();
}

相关文章