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

x33g5p2x  于2022-01-16 转载在 其他  
字(14.0k)|赞(0)|评价(0)|浏览(426)

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

Appender介绍

[英]Appends LogEvents. An Appender can contain a Layout if applicable as well as an ErrorHandler. Typical Appender implementations coordinate with an implementation of org.apache.logging.log4j.core.appender.AbstractManager to handle external resources such as streams, connections, and other shared state. As Appenders are plugins, concrete implementations need to be annotated with org.apache.logging.log4j.core.config.plugins.Plugin and need to provide a static factory method annotated with org.apache.logging.log4j.core.config.plugins.PluginFactory.

Most core plugins are written using a related Manager class that handle the actual task of serializing a LogEvent to some output location. For instance, many Appenders can take advantage of the org.apache.logging.log4j.core.appender.OutputStreamManager class.

It is recommended that Appenders don't do any heavy lifting since there can be many instances of the class being used at any given time. When resources require locking (e.g., through java.nio.channels.FileLock), it is important to isolate synchronized code to prevent concurrency issues.
[中]附加日志事件。如果适用,Appender可以包含布局以及ErrorHandler。典型的Appender实现与org的实现相协调。阿帕奇。登录中。log4j。果心阿佩德。AbstractManager处理外部资源,如流、连接和其他共享状态。由于appender是插件,具体的实现需要用org注释。阿帕奇。登录中。log4j。果心配置。插件。插件,需要提供一个用org注释的静态工厂方法。阿帕奇。登录中。log4j。果心配置。插件。插件工厂。
大多数核心插件都是使用相关的管理器类编写的,该类处理将LogEvent序列化到某个输出位置的实际任务。例如,许多附加者可以利用组织。阿帕奇。登录中。log4j。果心阿佩德。OutputStreamManager类。
建议appender不要执行任何繁重的操作,因为在任何给定的时间都可能使用该类的许多实例。当资源需要锁定时(例如,通过java.nio.channels.FileLock),隔离同步代码以防止并发问题非常重要。

代码示例

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

for (final Node cnode : node.getChildren()) {
 final Node appNode = new Node(cnode);
 config.createConfiguration(appNode, event);
 if (appNode.getObject() instanceof Appender) {
  final Appender app = appNode.getObject();
  app.start();
  if (!(app instanceof RandomAccessFileAppender)) {
   String message =
     "Cannot handle appenders other than " + RandomAccessFileAppender.class.getName() +
       ". Found: " + app.getClass().getName();
   LOGGER.error(message);
   throw new IllegalStateException(message);
  if (LOGGER.isDebugEnabled()) {
   RandomAccessFileAppender raf = (RandomAccessFileAppender) app;
   LOGGER.debug(
     "Setup new appender to write to file: " + raf.getFileName() + ", appenderName=" +
       raf.getName() + ", appenderManagerName=" + raf.getManager().getName());

代码示例来源: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: org.apache.logging.log4j/log4j-core

@Test
public void testAppendWithKeyLookup() throws Exception {
  final Appender appender = ctx.getRequiredAppender("KafkaAppenderWithKeyLookup");
  final LogEvent logEvent = createLogEvent();
  Date date = new Date();
  SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
  appender.append(logEvent);
  final List<ProducerRecord<byte[], byte[]>> history = kafka.history();
  assertEquals(1, history.size());
  final ProducerRecord<byte[], byte[]> item = history.get(0);
  assertNotNull(item);
  assertEquals(TOPIC_NAME, item.topic());
  byte[] keyValue = format.format(date).getBytes(StandardCharsets.UTF_8);
  assertArrayEquals(item.key(), keyValue);
  assertEquals(LOG_MESSAGE, new String(item.value(), StandardCharsets.UTF_8));
}

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

if (appenderControl.get() != null) {
 appenderControl.get().stop();
 realAppender.get().stop();
if (LOGGER.isDebugEnabled()) {
 LOGGER.debug(
   "Stop invoked for " + ((RandomAccessFileAppender) realAppender.get()).getFileName());
 LOGGER.info("RealAppender is null. Ignoring stop");
 return;

代码示例来源:origin: igniterealtime/Openfire

String addAppender(final Writer writer) {
  final String name = "openfire-s2s-test-appender-" + StringUtils.randomString( 10 );
  final LoggerContext context = LoggerContext.getContext(false);
  final Configuration config = context.getConfiguration();
  final PatternLayout layout = PatternLayout.createDefaultLayout(config);
  final Appender appender = WriterAppender.createAppender(layout, null, writer, name, false, true);
  appender.start();
  config.addAppender(appender);
  final Level level = null;
  final Filter filter = null;
  for (final LoggerConfig loggerConfig : config.getLoggers().values()) {
    loggerConfig.addAppender(appender, level, filter);
  }
  config.getRootLogger().addAppender(appender, level, filter);
  return name;
}

代码示例来源: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: Waikato/wekaDeeplearning4j

Configuration config = context.getConfiguration();
ConfigurationSource configSource = config.getConfigurationSource();
String packageHomeDir = WekaPackageManager.getPackageHome().getPath();
if (ConfigurationSource.NULL_SOURCE.equals(configSource)) {
  context.setConfigLocation(uri);
  log.info("Logging configuration loaded from source: {}", uri.toString());
if(!context.getRootLogger().getAppenders().containsKey(fileAppenderName)){
  Appender consoleAppender = context.getLogger(log.getName()).getAppenders().get("Console");
  Layout<? extends Serializable> layout = consoleAppender.getLayout();

代码示例来源:origin: ops4j/org.ops4j.pax.logging

this.setStopping();
super.stop(timeout, timeUnit, false);
LOGGER.trace("Stopping {}...", this);
  loggerConfig.getReliabilityStrategy().beforeStopConfiguration(this);
root.getReliabilityStrategy().beforeStopConfiguration(this);
LOGGER.trace("{} notified {} ReliabilityStrategies that config will be stopped.", cls, loggerConfigs.size()
    + 1);
  LOGGER.trace("{} stopping {} LoggerConfigs.", cls, loggerConfigs.size());
  for (final LoggerConfig logger : loggerConfigs.values()) {
    logger.stop(timeout, timeUnit);
      ((LifeCycle2) appender).stop(timeout, timeUnit);
    } else {
      appender.stop();
int appenderCount = 0;
for (int i = array.length - 1; i >= 0; --i) {
  if (array[i].isStarted()) { // then stop remaining Appenders
    if (array[i] instanceof LifeCycle2) {
      ((LifeCycle2) array[i]).stop(timeout, timeUnit);
    } else {
      array[i].stop();

代码示例来源:origin: ops4j/org.ops4j.pax.logging

/**
 * Deletes the specified appender.
 *
 * @param key The appender's key
 */
public void deleteAppender(final String key) {
  LOGGER.debug("Deleting route with " + key + " key ");
  final AppenderControl control = appenders.remove(key);
  if (null != control) {
    LOGGER.debug("Stopping route with " + key + " key");
    control.getAppender().stop();
  } else {
    LOGGER.debug("Route with " + key + " key already deleted");
  }
}

代码示例来源:origin: org.nuxeo.runtime/nuxeo-runtime-test

@Override
public void beforeRun(FeaturesRunner runner) throws Exception {
  // create class filter
  classFilter = instantiateFilter(() -> runner.getConfig(FilterWith.class),
      () -> runner.getConfig(FilterOn.class));
  if (classFilter == null) {
    log.info("Class {} uses LogCaptureFeature without defining a filter",
        runner.getTargetTestClass().getName());
  }
  // set current filter and start appender
  currentFilter = classFilter;
  logAppender.start();
  LoggerContext.getContext(false).getRootLogger().addAppender(logAppender);
}

代码示例来源:origin: org.elasticsearch/elasticsearch

public static void removeAppender(final Logger logger, final Appender appender) {
  final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
  final Configuration config = ctx.getConfiguration();
  LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName());
  if (!logger.getName().equals(loggerConfig.getName())) {
    loggerConfig = new LoggerConfig(logger.getName(), logger.getLevel(), true);
    config.addLogger(logger.getName(), loggerConfig);
  }
  loggerConfig.removeAppender(appender.getName());
  ctx.updateLoggers();
}

代码示例来源:origin: ops4j/org.ops4j.pax.logging

initialize();
LOGGER.debug("Starting configuration {}", this);
this.setStarting();
if (watchManager.getIntervalSeconds() > 0) {
  logger.start();
  alreadyStarted.add(logger);
  appender.start();
  root.start(); // LOG4J2-336
LOGGER.debug("Started configuration {} OK.", this);

代码示例来源:origin: Meituan-Dianping/Zebra

ZebraRolloverStrategy.createStrategy("30", "1", null, Deflater.DEFAULT_COMPRESSION + "", config), layout,
   fileInfoFilter, "false", null, null, config);
config.addAppender(fileInfoAppender);
fileInfoAppender.start();
AppenderRef fileInfoRef = AppenderRef.createAppenderRef("FileInfo", null, fileInfoFilter);
config.addAppender(consoleErrorAppender);
consoleErrorAppender.start();
Appender consoleWarnAppender = ConsoleAppender.createAppender(layout, consoleWarnFilter, "SYSTEM_OUT",
   "ConsoleWarn", "false", "false");
config.addAppender(consoleWarnAppender);
consoleWarnAppender.start();
AppenderRef consoleWarnAppenderRef = AppenderRef.createAppenderRef("ConsoleWarn", Level.WARN, consoleWarnFilter);
AppenderRef consoleErrorAppenderRef = AppenderRef.createAppenderRef("ConsoleError", Level.WARN, null);
LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "com.dianping.zebra", "true", refs,
   null, config, null);
loggerConfig.addAppender(consoleErrorAppender, Level.ERROR, null);
loggerConfig.addAppender(consoleWarnAppender, Level.INFO, null);
loggerConfig.addAppender(fileInfoAppender, Level.INFO, null);
config.addLogger("com.dianping.zebra", loggerConfig);
ctx.updateLoggers();

代码示例来源:origin: mulesoft/mule

private void doAddAppender(LoggerContext context, Appender appender) {
 appender.start();
 context.getConfiguration().addAppender(appender);
 getRootLogger(context).addAppender(appender, Level.ALL, null);
}

代码示例来源: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: fbacchella/LogHub

public static void setAppender() {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(true);
    org.apache.logging.log4j.core.config.Configuration config = ctx.getConfiguration();
    // If the event logger already exists, do nothing
    if (config.getLoggers().containsKey(LOGGERNAME)) {
      return;
    }
    Layout<String> layout = PatternLayout.newBuilder().withPattern("%msg%n").withConfiguration(config).build();
    Appender jsonappender = ConsoleAppender.newBuilder()
            .withName(APPENDERNAME)
            .setTarget(ConsoleAppender.Target.SYSTEM_ERR)
            .withLayout(layout)
            .setConfiguration(config)
            .build();
    jsonappender.start();
    config.addAppender(jsonappender);
    AppenderRef ref = AppenderRef.createAppenderRef(APPENDERNAME, null, null);
    LoggerConfig loggerConfig = LoggerConfig.createLogger(false, LOGLEVEL, LOGGERNAME, "false", new AppenderRef[] {ref}, new Property[]{}, config, (Filter) null);
    loggerConfig.addAppender(jsonappender, null, null);
    config.removeLogger(LOGGERNAME);
    config.addLogger(LOGGERNAME, loggerConfig);
    ctx.updateLoggers();
  }
}

代码示例来源:origin: com.mchange/mchange-commons-java

@Override
public void removeHandler(Object h) throws SecurityException
{
  if(!(h instanceof Appender))
    throw new IllegalArgumentException("The 'handler' " + h + " is not compatible with MLogger " + this);
  LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
  Configuration config = ctx.getConfiguration();
  LoggerConfig loggerConfig = config.getLoggerConfig(this.logger.getName());
  loggerConfig.removeAppender(((Appender) h).getName());
  ctx.updateLoggers();
}

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

public static void redirectLoggingToConsole() {
    final LoggerContext context = LoggerContext.getContext(false);
    final Configuration config = context.getConfiguration();

    Appender appender = config.getAppender("Console");
    if (appender == null) {
      Optional<Appender> result =
          config.getAppenders().values().stream().filter(a -> a instanceof ConsoleAppender).findFirst();
      if (!result.isPresent()) {
        System.err.println(
            "ERROR: cannot find appender named 'Console'; unable to find alternate ConsoleAppender!");
      } else {
        appender = result.get();
        System.err.println("ERROR: cannot find appender named 'Console'; using alternate ConsoleAppender named "
            + appender.getName());
      }
    }
    if (appender != null) {
      config.getRootLogger().addAppender(appender, null, null);
      context.updateLoggers();
    }
  }
}

代码示例来源:origin: igniterealtime/Openfire

void removeAppender(final String name) {
  final LoggerContext context = LoggerContext.getContext(false);
  final Configuration config = context.getConfiguration();
  config.getAppenders().remove( name ).stop();
  for (final LoggerConfig loggerConfig : config.getLoggers().values()) {
    loggerConfig.removeAppender( name );
  }
  config.getRootLogger().removeAppender( name );
}

代码示例来源:origin: info.magnolia/magnolia-core

/**
   * Removes the given appender from the root logger; typically upon tear-down (@After).
   */
  public static void stopRecordingLogs(Appender appender) {
    LoggerContext context = LoggerContext.getContext(false);
    Configuration config = context.getConfiguration();

    String appenderName = appender.getName();
    if (config.getAppenders().remove(appenderName) != null) {
      appender.stop();
      config.getRootLogger().removeAppender(appenderName);
      context.updateLoggers(config);
    }
  }
}

相关文章