Java Code Examples for org.apache.logging.log4j.core.config.LoggerConfig#addAppender()

The following examples show how to use org.apache.logging.log4j.core.config.LoggerConfig#addAppender() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MyServiceUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void testProgrammaticConfig() {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();

    PatternLayout layout = PatternLayout.newBuilder().withConfiguration(config).withPattern("%d{HH:mm:ss.SSS} %level %msg%n").build();

    Appender appender = FileAppender.newBuilder().setConfiguration(config).withName("programmaticFileAppender").withLayout(layout).withFileName("java.log").build();
    appender.start();
    config.addAppender(appender);
    AppenderRef ref = AppenderRef.createAppenderRef("programmaticFileAppender", null, null);
    AppenderRef[] refs = new AppenderRef[] { ref };

    LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "programmaticLogger", "true", refs, null, config, null);

    loggerConfig.addAppender(appender, null, null);
    config.addLogger("programmaticLogger", loggerConfig);
    ctx.updateLoggers();

    Logger pLogger = LogManager.getLogger("programmaticLogger");
    pLogger.info("Programmatic Logger Message");
}
 
Example 2
Source File: Log4JController.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Captures the given logger at the given level so it can be displayed directly by this controller.
 *
 * @param name the name
 * @param level the level
 * @param append the append
 * @return the response entity
 */
@RequestMapping(value = "capture/{name}/{level}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET,
    headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<LogResponse> capture(@PathVariable("name")
final String name, @PathVariable("level")
final Level level, @RequestParam(value = "append", defaultValue = "false") boolean append) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    synchronized (ctx) {
        if (inMemoryAppenderImpl != null) {
            final Configuration config = ctx.getConfiguration();
            //
            if (name.equalsIgnoreCase(config.getLoggerConfig(name).getName())) {
                config.removeLogger(name);
            }
            //
            AppenderRef ref = AppenderRef.createAppenderRef("InMemoryAppenderImplAppenderRef", level, null);
            AppenderRef[] refs = new AppenderRef[] {ref};
            LoggerConfig loggerConfig = LoggerConfig.createLogger(append, level, name, "true", refs, null, config, null);
            loggerConfig.addAppender(inMemoryAppenderImpl, null, null);
            config.addLogger(name, loggerConfig);
            ctx.updateLoggers();
        }
    }
    return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK);
}
 
Example 3
Source File: Main.java    From homework_tester with MIT License 6 votes vote down vote up
private static Logger configureLog4j() {
    LoggerContext context = (LoggerContext) LogManager.getContext();
    Configuration config = context.getConfiguration();

    PatternLayout layout = PatternLayout.createLayout("%m%n", null, null, Charset.defaultCharset(), false, false, null, null);
    Appender appender = ConsoleAppender.createAppender(layout, null, null, "CONSOLE_APPENDER", null, null);
    appender.start();
    AppenderRef ref = AppenderRef.createAppenderRef("CONSOLE_APPENDER", null, null);
    AppenderRef[] refs = new AppenderRef[]{ref};
    LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "CONSOLE_LOGGER", "com", refs, null, null, null);
    loggerConfig.addAppender(appender, null, null);

    config.addAppender(appender);
    config.addLogger("Main.class", loggerConfig);
    context.updateLoggers(config);
    return LogManager.getContext().getLogger("Main.class");
}
 
Example 4
Source File: S2STestService.java    From Openfire with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source File: Log4j2Watcher.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public void registerListener(ListenerConfig cfg) {
  if (history != null)
    throw new IllegalStateException("History already registered");

  history = new CircularList<LogEvent>(cfg.size);

  Level threshold = (cfg.threshold != null) ? Level.toLevel(cfg.threshold) : Level.WARN;
  ThresholdFilter filter = ThresholdFilter.createFilter(threshold, Filter.Result.ACCEPT, Filter.Result.DENY);

  // If there's already an appender like this, remove it
  LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
  LoggerConfig config = getLoggerConfig(ctx, LoggerInfo.ROOT_NAME);

  appender = new Log4j2Appender(this, filter, threshold); // "Log4j2WatcherAppender"

  config.removeAppender(appender.getName());

  if (!appender.isStarted())
    appender.start();

  config.addAppender(appender, threshold, filter);
  ctx.updateLoggers();
}
 
Example 6
Source File: Main.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
private static void addFileAppender(String logFilename) throws IOException {
  File logFile = new File(logFilename);
  Object ctx = LogManager.getContext(false);
  if (ctx instanceof LoggerContext) {
    try (LoggerContext context = (LoggerContext) ctx) {
      Configuration configuration = context.getConfiguration();
      LoggerConfig loggerConfig = configuration.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
      FileAppender fileAppender =
          FileAppender.newBuilder()
              .setName("file")
              .setLayout(
                  PatternLayout.newBuilder()
                      .withPattern("[%d][%-5.-5p][%-14.-14c{1}:%4L] %-22.-22M - %m%n")
                      .build())
              .withFileName(logFile.getCanonicalPath())
              .build();
      configuration.addAppender(fileAppender);
      loggerConfig.addAppender(fileAppender, Level.ERROR, null);
      context.updateLoggers();
    }
  }
}
 
Example 7
Source File: LogTestRule.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
public void watch(Class<?> loggerClass, Level level) {
    this.loggerClass = loggerClass;
    Appender appender = new AbstractAppender(APPENDER_NAME, null, PatternLayout.createDefaultLayout()) {
        @Override
        public void append(LogEvent event) {
            logEvents.add(new RecordedLogEvent(event));
        }
    };
    appender.start();
    final LoggerContext ctx = getLoggerContext();
    LoggerConfig loggerConfig = ctx.getConfiguration().getLoggerConfig(loggerClass.getName());
    oldLevel = loggerConfig.getLevel();
    loggerConfig.setLevel(level);
    loggerConfig.addAppender(appender, level, null);
    ctx.updateLoggers();
}
 
Example 8
Source File: LoggingMixin.java    From picocli with Apache License 2.0 6 votes vote down vote up
/**
 * Configures the Log4j2 console appender(s), using the specified verbosity:
 * <ul>
 *   <li>{@code -vvv} : enable TRACE level</li>
 *   <li>{@code -vv} : enable DEBUG level</li>
 *   <li>{@code -v} : enable INFO level</li>
 *   <li>(not specified) : enable WARN level</li>
 * </ul>
 */
public void configureLoggers() {
    Level level = getTopLevelCommandLoggingMixin(mixee).calcLogLevel();

    LoggerContext loggerContext = LoggerContext.getContext(false);
    LoggerConfig rootConfig = loggerContext.getConfiguration().getRootLogger();
    for (Appender appender : rootConfig.getAppenders().values()) {
        if (appender instanceof ConsoleAppender) {
            rootConfig.removeAppender(appender.getName());
            rootConfig.addAppender(appender, level, null);
        }
    }
    if (rootConfig.getLevel().isMoreSpecificThan(level)) {
        rootConfig.setLevel(level);
    }
    loggerContext.updateLoggers(); // apply the changes
}
 
Example 9
Source File: MyXMLConfiguration.java    From tutorials with MIT License 5 votes vote down vote up
@Override
protected void doConfigure() {
    super.doConfigure();
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    LoggerConfig loggerConfig = config.getLoggerConfig("com");
    final Layout layout = PatternLayout.createLayout("[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n", null, config, null, null, false, false, null, null);
    Appender appender = FileAppender.createAppender("target/test.log", "false", "false", "File", "true", "false", "false", "4000", layout, null, "false", null, config);
    loggerConfig.addAppender(appender, Level.DEBUG, null);
    addAppender(appender);
}
 
Example 10
Source File: ConfigurationTestUtils.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
static void updateLoggers(final Appender appender, final Configuration config) {
    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);
}
 
Example 11
Source File: Log4J2Appender.java    From javamelody with Apache License 2.0 5 votes vote down vote up
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();
		}
	}
}
 
Example 12
Source File: TestLogStrategy.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Initialize this test.
 */
@BeforeClass
public static void init() {
    final LoggerContext context = LoggerContext.getContext(false);
    final Configuration config = context.getConfiguration();
    final Appender appender = new TestAppender();
    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);
}
 
Example 13
Source File: SpectatorAppender.java    From spectator with Apache License 2.0 5 votes vote down vote up
private static void addToRootLogger(final Appender appender) {
  LoggerContext context = (LoggerContext) LogManager.getContext(false);
  Configuration config = context.getConfiguration();
  LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
  loggerConfig.addAppender(appender, Level.ALL, null);
  context.updateLoggers(config);
}
 
Example 14
Source File: LoggingConfigurator.java    From teku with Apache License 2.0 5 votes vote down vote up
private static LoggerConfig setUpValidatorLogger(final Appender appender) {
  // Don't disable validator error logs unless the root log level disables error.
  final Level validatorLogLevel =
      INCLUDE_VALIDATOR_DUTIES || ROOT_LOG_LEVEL.isMoreSpecificThan(Level.ERROR)
          ? ROOT_LOG_LEVEL
          : Level.ERROR;
  final LoggerConfig logger = new LoggerConfig(VALIDATOR_LOGGER_NAME, validatorLogLevel, true);
  logger.addAppender(appender, ROOT_LOG_LEVEL, null);
  return logger;
}
 
Example 15
Source File: CLogOut.java    From TweetwallFX with MIT License 5 votes vote down vote up
private void updateLoggers(final Appender appender, final Configuration config) {
    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);
}
 
Example 16
Source File: ExecutorLoggerFactory.java    From liteflow with Apache License 2.0 4 votes vote down vote up
/**
 * 创建并启动一个的logger
 */
private static void start(String loggerName, String logPath) {
    /**
     * 设置layout
     */
    Layout layout = PatternLayout
            .newBuilder()
            .withConfiguration(config)
            .withPattern(LAYOUT_TEMPLATE)
            .build();

    String fileName = logPath;
    /**
     * 设置appender
     */
    FileAppender fileAppender = FileAppender.newBuilder()
            .withName(loggerName)
            .withFileName(fileName)
            .withLayout(layout)
            .build();

    AppenderRef appenderRef = AppenderRef.createAppenderRef(APPRENDER_REF, APPRENDER_LEVEL, APPRENDER_FILTER);
    LoggerConfig loggerConfig = LoggerConfig.createLogger(
            LOGGER_ADDITIVITY,
            Level.ALL,
            loggerName,
            LOGGER_INCLUDE_LOCATIOIN,
            new AppenderRef[] {appenderRef},
            LOGGER_PROPERTY,
            config,
            APPRENDER_FILTER
    );
    loggerConfig.addAppender(fileAppender, APPRENDER_LEVEL, APPRENDER_FILTER);
    /**
     * 添加appender
     */
    config.addLogger(loggerName, loggerConfig);
    ctx.updateLoggers();
    LOG.info("create logger {}, path is {}", loggerName, logPath);
    /**
     * start
     */
    loggerConfig.start();
}
 
Example 17
Source File: CloudStorageLoggerFactory.java    From ambari-logsearch with Apache License 2.0 4 votes vote down vote up
public static Logger createLogger(Input input, LoggerContext loggerContext, LogFeederProps logFeederProps) {
  boolean useJsonFormat = logFeederProps.isCloudStorageUseFilters();
  String type = input.getLogType().replace(LogFeederConstants.CLOUD_PREFIX, "");
  String uniqueThreadName = input.getThread().getName();
  Configuration config = loggerContext.getConfiguration();
  String baseDir = logFeederProps.getRolloverConfig().getRolloverArchiveBaseDir();
  String destination = logFeederProps.getCloudStorageDestination().getText();
  String clusterHostnameBaseDir = Paths.get(baseDir, destination, logFeederProps.getClusterName(), LogFeederUtil.hostName).toFile().getAbsolutePath();
  String activeLogDir = Paths.get(clusterHostnameBaseDir, ACTIVE_FOLDER, type).toFile().getAbsolutePath();
  String archiveLogDir = Paths.get(clusterHostnameBaseDir, ARCHIVED_FOLDER, type).toFile().getAbsolutePath();

  boolean useGzip = logFeederProps.getRolloverConfig().isUseGzip();
  final String archiveFilePattern;
  if (useJsonFormat) {
    archiveFilePattern = useGzip ? JSON_DATE_PATTERN_SUFFIX_GZ : JSON_DATE_PATTERN_SUFFIX;
  } else {
    archiveFilePattern = useGzip ? DATE_PATTERN_SUFFIX_GZ : DATE_PATTERN_SUFFIX;
  }

  String logSuffix = useJsonFormat ? ".json" : ".log";
  String fileName = String.join(File.separator, activeLogDir, type + logSuffix);
  String filePattern = String.join(File.separator, archiveLogDir, type + archiveFilePattern);
  PatternLayout layout = PatternLayout.newBuilder()
    .withPattern(PatternLayout.DEFAULT_CONVERSION_PATTERN).build();

  String rolloverSize = logFeederProps.getRolloverConfig().getRolloverSize().toString() + logFeederProps.getRolloverConfig().getRolloverSizeFormat();
  SizeBasedTriggeringPolicy sizeBasedTriggeringPolicy = SizeBasedTriggeringPolicy.createPolicy(rolloverSize);

  final Integer thresholdMin = logFeederProps.getRolloverConfig().getRolloverThresholdTimeMins();
  final Integer thresholdInterval = thresholdMin * 60000; // 1 min = 60000 milliseconds

  TimeBasedTriggeringPolicy timeBasedTriggeringPolicy = TimeBasedTriggeringPolicy.newBuilder()
    .withInterval(thresholdInterval)
    .build();

  final CompositeTriggeringPolicy compositeTriggeringPolicy;

  if (logFeederProps.getRolloverConfig().isRolloverOnStartup()) {
    OnStartupTriggeringPolicy onStartupTriggeringPolicy = OnStartupTriggeringPolicy.createPolicy(1);
    compositeTriggeringPolicy = CompositeTriggeringPolicy
      .createPolicy(sizeBasedTriggeringPolicy, timeBasedTriggeringPolicy, onStartupTriggeringPolicy);
  } else {
    compositeTriggeringPolicy = CompositeTriggeringPolicy
      .createPolicy(sizeBasedTriggeringPolicy, timeBasedTriggeringPolicy);
  }

  DefaultRolloverStrategy defaultRolloverStrategy = DefaultRolloverStrategy.newBuilder()
    .withMax(String.valueOf(logFeederProps.getRolloverConfig().getRolloverMaxBackupFiles()))
    .build();

  boolean immediateFlush = logFeederProps.getRolloverConfig().isImmediateFlush();
  RollingFileAppender appender = RollingFileAppender.newBuilder()
    .withFileName(fileName)
    .withFilePattern(filePattern)
    .withLayout(layout)
    .withName(type)
    .withPolicy(compositeTriggeringPolicy)
    .withStrategy(defaultRolloverStrategy)
    .withImmediateFlush(immediateFlush)
    .build();

  appender.start();
  config.addAppender(appender);

  AppenderRef ref = AppenderRef.createAppenderRef(type, null, null);
  AppenderRef[] refs = new AppenderRef[] {ref};

  LoggerConfig loggerConfig = LoggerConfig
    .createLogger(false, Level.ALL, input.getThread().getName(),
      "true", refs, null, config, null);
  loggerConfig.addAppender(appender, null, null);
  config.addLogger(uniqueThreadName, loggerConfig);
  loggerContext.updateLoggers();
  return loggerContext.getLogger(uniqueThreadName);
}
 
Example 18
Source File: LoggingConfigurator.java    From teku with Apache License 2.0 4 votes vote down vote up
private static LoggerConfig setUpEventsLogger(final Appender appender) {
  final Level eventsLogLevel = INCLUDE_EVENTS ? ROOT_LOG_LEVEL : Level.OFF;
  final LoggerConfig logger = new LoggerConfig(EVENT_LOGGER_NAME, eventsLogLevel, true);
  logger.addAppender(appender, eventsLogLevel, null);
  return logger;
}
 
Example 19
Source File: LoggerLoader.java    From Zebra with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public static synchronized void init() {
	final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
	final Configuration config = ctx.getConfiguration();
	Layout layout = PatternLayout.newBuilder().withPattern("%d{yyyy-MM-dd HH:mm:ss}:%p %t %c - %m%n")
	      .withConfiguration(config).withRegexReplacement(null).withCharset(null).withAlwaysWriteExceptions(true)
	      .withNoConsoleNoAnsi(false).withHeader(null).withFooter(null).build();

	// file info
	Filter fileInfoFilter = ThresholdFilter.createFilter(Level.ERROR, Result.DENY, Result.ACCEPT);
	Appender fileInfoAppender = RollingFileAppender.createAppender(LOG_ROOT + "/zebra.log", LOG_ROOT
	      + "/zebra.log.%d{yyyy-MM-dd}.gz", "true", "FileInfo", "true", "4000", "true",
	      TimeBasedTriggeringPolicy.createPolicy("1", "true"),
	      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);

	// console error
	Appender consoleErrorAppender = ConsoleAppender.createAppender(layout, null, "SYSTEM_ERR", "ConsoleError",
	      "false", "false");
	config.addAppender(consoleErrorAppender);
	consoleErrorAppender.start();

	// console info
	Filter consoleWarnFilter = ThresholdFilter.createFilter(Level.ERROR, Result.DENY, Result.NEUTRAL);
	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);

	AppenderRef[] refs = new AppenderRef[] { consoleErrorAppenderRef, consoleWarnAppenderRef, fileInfoRef };

	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();

	context = ctx;
}
 
Example 20
Source File: PropertiesConfiguration.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
/**
 * This method must work for the root category as well.
 */
private void parseLogger(Properties props, LoggerConfig logger, String optionKey, String loggerName, String value) {

    LOGGER.debug("Parsing for [{}] with value=[{}].", loggerName, value);
    // We must skip over ',' but not white space
    StringTokenizer st = new StringTokenizer(value, ",");

    // If value is not in the form ", appender.." or "", then we should set the level of the logger.

    if (!(value.startsWith(",") || value.equals(""))) {

        // just to be on the safe side...
        if (!st.hasMoreTokens()) {
            return;
        }

        String levelStr = st.nextToken();
        LOGGER.debug("Level token is [{}].", levelStr);

        org.apache.logging.log4j.Level level = levelStr == null ? org.apache.logging.log4j.Level.ERROR :
                OptionConverter.convertLevel(levelStr, org.apache.logging.log4j.Level.DEBUG);
        logger.setLevel(level);
        LOGGER.debug("Logger {} level set to {}", loggerName, level);
    }

    Appender appender;
    String appenderName;
    while (st.hasMoreTokens()) {
        appenderName = st.nextToken().trim();
        if (appenderName == null || appenderName.equals(",")) {
            continue;
        }
        LOGGER.debug("Parsing appender named \"{}\".", appenderName);
        appender = parseAppender(props, appenderName);
        if (appender != null) {
            LOGGER.debug("Adding appender named [{}] to loggerConfig [{}].", appenderName,
                    logger.getName());
            logger.addAppender(getAppender(appenderName), null, null);
        } else {
            LOGGER.debug("Appender named [{}}] not found.", appenderName);
        }
    }
}