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

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

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

Logger介绍

[英]The core implementation of the org.apache.logging.log4j.Logger interface. Besides providing an implementation of all the Logger methods, this class also provides some convenience methods for Log4j 1.x compatibility as well as access to the org.apache.logging.log4j.core.Filter and org.apache.logging.log4j.core.Appender associated with this Logger. Note that access to these underlying objects is provided primarily for use in unit tests or bridging legacy Log4j 1.x code. Future versions of this class may or may not include the various methods that are noted as not being part of the public API. TODO All the isEnabled methods could be pushed into a filter interface. Not sure of the utility of having isEnabled be able to examine the message pattern and parameters. (RG) Moving the isEnabled methods out of Logger noticeably impacts performance. The message pattern and parameters are required so that they can be used in global filters.
[中]组织的核心实现。阿帕奇。登录中。log4j。记录器接口。除了提供所有Logger方法的实现外,该类还为Log4j 1提供了一些方便的方法。x兼容性以及对组织的访问。阿帕奇。登录中。log4j。果心过滤和组织。阿帕奇。登录中。log4j。果心与此记录器关联的附加程序。请注意,提供对这些底层对象的访问主要是为了在单元测试或桥接遗留Log4j 1中使用。x代码。这个类的未来版本可能包括也可能不包括各种方法,这些方法被认为不是公共API的一部分。TODO可以将所有isEnabled方法推送到筛选器接口中。不确定isEnabled的实用性,因此无法检查消息模式和参数。(RG)将isEnabled方法移出记录器会显著影响性能。需要消息模式和参数,以便在全局筛选器中使用它们。

代码示例

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

@Test
  public void testParameterizedMessage() {
    for (final Appender appender : root.getAppenders().values()) {
      root.removeAppender(appender);
    }
    // set up appender
    final AbstractStringLayout layout = Rfc5424Layout.createLayout(Facility.LOCAL0, "Event", 3692, true, "RequestContext",
      null, null, true, null, "ATM", null, "key1, key2, locale", null, null, null, true, null, null);
    final ListAppender appender = new ListAppender("List", null, layout, true, false);

    appender.start();

    // set appender on root and set level to debug
    root.addAppender(appender);
    root.setLevel(Level.DEBUG);
    root.info("Hello {}", "World");
    try {
      final List<String> list = appender.getMessages();
      assertTrue("Not enough list entries", list.size() > 0);
      final String message =  list.get(0);
      assertTrue("Incorrect message. Expected - Hello World, Actual - " + message, message.contains("Hello World"));
    } finally {
      root.removeAppender(appender);
      appender.stop();
    }
  }
}

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

/**
 * Add an appender to Log4j which sends all INFO+ messages to a separate file which will be used
 * later to scan for suspect strings. The pattern of the messages conforms to the original log
 * format so that hydra will be able to parse them.
 */
private static void addSuspectFileAppender(final String workspaceDir) {
 final String suspectFilename = new File(workspaceDir, SUSPECT_FILENAME).getAbsolutePath();
 final LoggerContext appenderContext =
   ((org.apache.logging.log4j.core.Logger) LogManager
     .getLogger(Configuration.MAIN_LOGGER_NAME))
       .getContext();
 final PatternLayout layout = PatternLayout.createLayout(
   "[%level{lowerCase=true} %date{yyyy/MM/dd HH:mm:ss.SSS z} <%thread> tid=%tid] %message%n%throwable%n",
   null, null, null, Charset.defaultCharset(), true, false, "", "");
 final FileAppender fileAppender = FileAppender.createAppender(suspectFilename, "true", "false",
   DUnitLauncher.class.getName(), "true", "false", "false", "0", layout, null, null, null,
   appenderContext.getConfiguration());
 fileAppender.start();
 LoggerConfig loggerConfig =
   appenderContext.getConfiguration().getLoggerConfig(Configuration.MAIN_LOGGER_NAME);
 loggerConfig.addAppender(fileAppender, Level.INFO, null);
}

代码示例来源:origin: alibaba/nacos

@Override
public void setLevel(Level level) {
  this.level = level;
  org.apache.logging.log4j.Level l = org.apache.logging.log4j.Level.toLevel(level.getName(),
    org.apache.logging.log4j.Level.ERROR);
  logger.setLevel(l);
  logger.getContext().getConfiguration().getLoggerConfig(this.logger.getName()).setLevel(l);
}

代码示例来源:origin: alibaba/nacos

protected void removeAllAppenders(org.apache.logging.log4j.core.Logger logger) {
    Map<String, Appender> appenders = logger.getAppenders();
    if (appenders != null) {
      for (Appender appender : appenders.values()) {
        logger.removeAppender(appender);
      }
    }
  }
}

代码示例来源:origin: alibaba/nacos

protected void activateAppender(org.apache.logging.log4j.core.Logger logger) {
  removeAllAppenders(this.logger);
  Map<String, Appender> appenders = null;
  if ((appenders = logger.getAppenders()) != null) {
    for (Appender appender : appenders.values()) {
      this.logger.addAppender(appender);
    }
  }
}

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

protected void initRootLogger(final Appender appender) {
  root.addAppender(appender);
  root.setAdditive(false);
  root.setLevel(Level.DEBUG);
}

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

final Map<String, Appender> appenders = this.rootLogger.getAppenders();
for (final Appender appender : appenders.values()) {
  this.rootLogger.removeAppender(appender);
final Configuration configuration = rootLogger.getContext().getConfiguration();
this.rootLogger.addAppender(appender);
this.rootLogger.setLevel(Level.DEBUG);
this.rootLogger.debug("starting mdc pattern test");
this.rootLogger.debug("empty mdc");
this.rootLogger.debug("filled mdc");
this.rootLogger.error("finished mdc pattern test", new NullPointerException("test"));
this.checkContains("message: \"starting mdc pattern test\"", list);
for (final Appender app : appenders.values()) {
  this.rootLogger.addAppender(app);

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

@AfterClass
public static void tearDownStatic()
{
 final Logger logger = (Logger) LogManager.getLogger(
   LoggingRequestLogger.class);
 logger.removeAppender(appender);
 appender.stop();
}

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

String getLogDir(Configuration conf) {
 String logDir = conf.get("hive.log.dir");
 if (logDir == null) {
  logDir = System.getProperty("hive.log.dir");
 }
 if (logDir != null) {
  return logDir;
 }
 LoggerContext context = (LoggerContext)LogManager.getContext(false);
 for (Logger logger: context.getLoggers()) {
  for (Appender appender: logger.getAppenders().values()) {
   if (appender instanceof AbstractOutputStreamAppender) {
    OutputStreamManager manager =
     ((AbstractOutputStreamAppender<?>)appender).getManager();
    if (manager instanceof FileManager) {
     String fileName = ((FileManager)manager).getFileName();
     if (fileName != null) {
      return fileName.substring(0, fileName.lastIndexOf('/'));
     }
    }
   }
  }
 }
 return null;
}

代码示例来源:origin: spring-projects/spring-amqp

@BeforeAll
public static void setUp() {
  Logger logger = (Logger) LogManager
      .getLogger("org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer");
  savedLevel = logger.getLevel();
  logger.setLevel(Level.DEBUG);
}

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

@BeforeClass
public static void setUpStatic()
{
 appender = OutputStreamAppender
   .newBuilder()
   .setName("test stream")
   .setTarget(baos)
   .setLayout(JsonLayout.createLayout(false, true, false, true, true, StandardCharsets.UTF_8))
   .build();
 final Logger logger = (Logger)
   LogManager.getLogger(LoggingRequestLogger.class);
 appender.start();
 logger.addAppender(appender);
}

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

@Test
 public void test() {
  String testLog = "testing";
  Logger logger = (Logger) LogManager.getLogger(TestLoggingEventStringSerde.class);
  LogEvent log = Log4jLogEvent.newBuilder()
    .setLevel(logger.getLevel())
    .setLoggerName(logger.getName())
    .setMessage(new SimpleMessage(testLog))
    .setThrown(null)
    .build();
  LoggingEventStringSerde loggingEventStringSerde = new LoggingEventStringSerde();

  assertNull(loggingEventStringSerde.fromBytes(null));
  assertNull(loggingEventStringSerde.toBytes(null));

  assertArrayEquals(testLog.getBytes(), loggingEventStringSerde.toBytes(log));
  // only the log messages are guaranteed to be equivalent
  assertEquals(log.getMessage().toString(), loggingEventStringSerde.fromBytes(testLog.getBytes()).getMessage().toString());
 }
}

代码示例来源:origin: spring-projects/spring-amqp

@AfterAll
public static void tearDown() {
  Logger logger = (Logger) LogManager
      .getLogger("org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer");
  logger.setLevel(savedLevel);
}

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

private void testCompressedLayout(final CompressionType compressionType, final boolean includeStacktrace,
                 final boolean includeThreadContext, String host, final boolean includeNullDelimiter) throws IOException {
  for (final Appender appender : root.getAppenders().values()) {
    root.removeAppender(appender);
    .setConfiguration(ctx.getConfiguration())
    .setHost(host)
    .setAdditionalFields(new KeyValuePair[] {
  root.addAppender(eventAppender);
  root.addAppender(rawAppender);
  root.addAppender(formattedAppender);
  root.addAppender(encodedAppender);
  root.setLevel(Level.DEBUG);
  root.debug(LINE1);
  root.info(LINE2);
  root.error(LINE3, exception);

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

/**
 * Creates console appender with some reasonable default logging settings.
 *
 * @return Logger with auto configured console appender.
 */
public Logger createConsoleLogger() {
  // from http://logging.apache.org/log4j/2.x/manual/customconfig.html
  final LoggerContext ctx = impl.getContext();
  final Configuration cfg = ctx.getConfiguration();
  PatternLayout.Builder builder = PatternLayout.newBuilder()
    .withPattern("%d{ISO8601}][%-5p][%t][%c{1}] %m%n")
    .withCharset(Charset.defaultCharset())
    .withAlwaysWriteExceptions(false)
    .withNoConsoleNoAnsi(false);
  PatternLayout layout = builder.build();
  ConsoleAppender.Builder consoleAppenderBuilder = ConsoleAppender.newBuilder()
    .withName(CONSOLE_APPENDER)
    .withLayout(layout);
  ConsoleAppender consoleApp = consoleAppenderBuilder.build();
  consoleApp.start();
  cfg.addAppender(consoleApp);
  cfg.getRootLogger().addAppender(consoleApp, Level.TRACE, null);
  ctx.updateLoggers(cfg);
  return ctx.getRootLogger();
}

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

public LoggerConfig getLoggerConfig() {
 final Logger logger = getLogger();
 final LoggerContext context = logger.getContext();
 return context.getConfiguration().getLoggerConfig(logger.getName());
}

代码示例来源:origin: alibaba/nacos

public Slf4jLog4j2AdapterActivateOption(Object logger) {
  super(null);
  try {
    org.apache.logging.log4j.core.Logger log4j2Logger = (org.apache.logging.log4j.core.Logger)loggerField.get(
      logger);
    super.logger = log4j2Logger;
    super.configuration = super.logger.getContext().getConfiguration();
  } catch (Exception e) {
    throw new RuntimeException("logger must be instanceof org.apache.logging.slf4j.Log4jLogger", e);
  }
}

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

@Test
public void testTcpAppenderNoWait() throws Exception {
  // @formatter:off
  final SocketAppender appender = SocketAppender.newBuilder()
      .withHost("localhost")
      .withPort(ERROR_PORT)
      .withReconnectDelayMillis(100)
      .withName("test")
      .withImmediateFail(false)
      .withIgnoreExceptions(false)
      .withLayout(JsonLayout.newBuilder().setProperties(true).build())
      .build();
  // @formatter:on
  appender.start();
  // set appender on root and set level to debug
  logger.addAppender(appender);
  logger.setAdditive(false);
  logger.setLevel(Level.DEBUG);
  try {
    logger.debug("This message is written because a deadlock never.");
    fail("No Exception was thrown");
  } catch (final Exception ex) {
    // TODO: move exception to @Test(expect = Exception.class)
    // Failure is expected.
    // ex.printStackTrace();
  }
}

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

public void localJobDebugger(int exitVal, String taskId) {
 StringBuilder sb = new StringBuilder();
 sb.append("\n");
 sb.append("Task failed!\n");
 sb.append("Task ID:\n  " + taskId + "\n\n");
 sb.append("Logs:\n");
 console.printError(sb.toString());
 for (Appender appender : ((Logger) LogManager.getRootLogger()).getAppenders().values()) {
  if (appender instanceof FileAppender) {
   console.printError(((FileAppender) appender).getFileName());
  } else if (appender instanceof RollingFileAppender) {
   console.printError(((RollingFileAppender) appender).getFileName());
  }
 }
}

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

appender.start();
final LoggerContext context = LoggerContext.getContext();
final Logger root = context.getLogger("SMTPAppenderTest");
root.addAppender(appender);
root.setAdditive(false);
root.setLevel(Level.DEBUG);
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");

相关文章