Java Code Examples for org.apache.logging.log4j.core.config.Configuration#addLogger()

The following examples show how to use org.apache.logging.log4j.core.config.Configuration#addLogger() . 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: Main.java    From homework_tester with MIT License 7 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 2
Source File: Log4j2MetricsTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void noDuplicateLoggingCountWhenMultipleNonAdditiveLoggersShareConfig() {
    LoggerContext loggerContext = new LoggerContext("test");

    LoggerConfig loggerConfig = new LoggerConfig("com.test", Level.INFO, false);
    Configuration configuration = loggerContext.getConfiguration();
    configuration.addLogger("com.test", loggerConfig);
    loggerContext.setConfiguration(configuration);
    loggerContext.updateLoggers();

    Logger logger1 = loggerContext.getLogger("com.test.log1");
    loggerContext.getLogger("com.test.log2");

    new Log4j2Metrics(emptyList(), loggerContext).bindTo(registry);

    assertThat(registry.get("log4j2.events").tags("level", "info").counter().count()).isEqualTo(0);
    logger1.info("Hello, world!");
    assertThat(registry.get("log4j2.events").tags("level", "info").counter().count()).isEqualTo(1);
}
 
Example 3
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 4
Source File: LoggerUtil.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * <p>
 * This method loads the required properties into log4j for the logger
 * </p>
 * 
 * @param logFileDir
 *            Log file directory
 * @param taskAttemptID
 *            The task attempt id
 * 
 * @throws IOException
 *             If any error occurs
 * @throws URISyntaxException
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws TransformerException
 */
public static void loadLogger(String logFileDir, String taskAttemptID) throws IOException, URISyntaxException, ParserConfigurationException,
		SAXException, TransformerException {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    ctx.reconfigure();
       Configuration config = ctx.getConfiguration();
       MemoryMappedFileAppender memoryMappedfileAppender = createMemoryMappedFileAppender(config, LOG_APPENDER_NAME + taskAttemptID, logFileDir, taskAttemptID, 0);
       memoryMappedfileAppender.start();
    AppenderRef[] ar = new AppenderRef [1];
       ar[0] = AppenderRef.createAppenderRef(LOG_APPENDER_NAME + taskAttemptID , Level.INFO, null);
       LoggerConfig lgf = LoggerConfig.createLogger("false",Level.INFO , LOG_CATEGORY + taskAttemptID , null, ar, null, config, null);
       config.addLogger(LOG_CATEGORY + taskAttemptID, lgf);
       ctx.getLogger(LOG_CATEGORY + taskAttemptID).addAppender(memoryMappedfileAppender);
       ctx.updateLoggers();
       ctx.start();
	mapReduceLoggers = new ArrayList<Logger>(1);
	mapReduceLoggers.add(LogManager.getLogger(LOG_CATEGORY + taskAttemptID));
	LOG.debug("Finished loading logger");

}
 
Example 5
Source File: ESLoggerConfigFactory.java    From core-ng-project with Apache License 2.0 6 votes vote down vote up
public static void configureLogger() {
    LoggerContext context = (LoggerContext) LogManager.getContext(false);
    Configuration config = context.getConfiguration();

    Map<String, ESLogger> loggers = Maps.newConcurrentHashMap();
    Appender appender = new AbstractAppender("", null, null) {
        @Override
        public void append(LogEvent event) {
            String name = event.getLoggerName();
            ESLogger logger = loggers.computeIfAbsent(name, key -> new ESLogger(key, null, (LoggerImpl) LoggerFactory.getLogger(key)));
            logger.log(event.getLevel(), event.getMarker(), event.getMessage(), event.getThrown());
        }
    };
    appender.start();
    config.addAppender(appender);

    var loggerConfig = new LoggerConfig("", Level.INFO, false); // only enable info and higher level
    loggerConfig.addAppender(appender, null, null);
    config.addLogger("", loggerConfig);
    context.updateLoggers();
}
 
Example 6
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 7
Source File: Log4JController.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Frees the given logger from the appender used to be displayed directly by this controller.
 *
 * @param name the name
 * @return the response entity
 */
@RequestMapping(value = "free/{name}/", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET,
    headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<LogResponse> free(@PathVariable("name")
final String name) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    synchronized (ctx) {
        final Configuration config = ctx.getConfiguration();
        LoggerConfig loggerConfig = config.getLoggerConfig(name);
        if (name.equalsIgnoreCase(loggerConfig.getName())) {
            config.removeLogger(name);
            LoggerConfig newloggerConfig = new LoggerConfig(name, loggerConfig.getLevel(), true);
            config.addLogger(name, newloggerConfig);
        }
        ctx.updateLoggers();
    }
    return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK);
}
 
Example 8
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 9
Source File: Log4JController.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Sets the.
 *
 * @param name
 *        the name
 * @param level
 *        the level
 * @return the response entity
 */
@RequestMapping(value = "set/{name}/{level}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET,
    headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<LogResponse> set(@PathVariable("name")
final String name, @PathVariable("level")
final Level level) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    synchronized (ctx) {
        final Configuration config = ctx.getConfiguration();
        LoggerConfig loggerConfig = config.getLoggerConfig(name);
        if (name.equalsIgnoreCase(loggerConfig.getName())) {
            loggerConfig.setLevel(level);
        } else {
            LoggerConfig newloggerConfig = new LoggerConfig(name, level, true);
            config.addLogger(name, newloggerConfig);
        }
        ctx.updateLoggers();
    }
    return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK);
}
 
Example 10
Source File: Log4j2Configuration.java    From summerframework with Apache License 2.0 6 votes vote down vote up
private void createBizLogger() {
    if (env.containsProperty(MonitorConfigSpringApplicationRunListener.LOG_KAFKA_BOOTSTRAPSERVERS)) {
        String appenderName = "AdvancedKafkaAppender";
        LoggerContext loggerContext = (LoggerContext)LogManager.getContext(false);
        Configuration configuration = loggerContext.getConfiguration();
        AdvancedKafkaAppender kafkaAppender =
            AdvancedKafkaAppender.createAppender(CustomJsonLayout.createDefaultLayout(), null, configuration,
                appenderName, getKafkaTopic(), getBootstrapservers());
        kafkaAppender.start();
        AppenderRef ref = AppenderRef.createAppenderRef(appenderName, null, null);
        AppenderRef[] refs = new AppenderRef[] {ref};
        LoggerConfig loggerConfig =
            LoggerConfig.createLogger(false, Level.INFO, "BizLogger", null, refs, null, configuration, null);
        loggerConfig.addAppender(kafkaAppender, null, null);
        configuration.addLogger("BizLogger", loggerConfig);
    }
}
 
Example 11
Source File: LogFactory.java    From chronus with Apache License 2.0 5 votes vote down vote up
public void start(LogConfig abyLogConfig) {
    //为false时,返回多个LoggerContext对象, true:返回唯一的单例LoggerContext
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    org.apache.logging.log4j.core.Logger cfgLogger = (org.apache.logging.log4j.core.Logger) LogManager.getLogger(abyLogConfig.getCfgLogName());
    if (cfgLogger == null) {
        LogManager.getLogger(LogFactory.class).error("not found {} logger (please define in log4j2.xml)", abyLogConfig.getCfgLogName());
        return;
    }

    List<AppenderRef> appenderRefs = new ArrayList<>();
    Map<String, Appender> appenderMap = cfgLogger.getAppenders();
    List<Appender> appenders = new ArrayList<>();
    appenderMap.forEach((key, appenderCfg) -> {
        Appender appender;
        if (appenderCfg instanceof ConsoleAppender) {
            appender = appenderCfg;
        } else {
            appender = getAppender(abyLogConfig, config, appenderCfg);
        }

        if (appender != null) {
            AppenderRef ref = AppenderRef.createAppenderRef(appender.getName(), Level.ALL, null);
            appenderRefs.add(ref);
            appenders.add(appender);
        }
    });
    if (CollectionUtils.isEmpty(appenders)) {
        return;
    }
    AppenderRef[] refs = new AppenderRef[appenderRefs.size()];
    refs = appenderRefs.toArray(refs);
    LoggerConfig loggerConfig = LoggerConfig.createLogger(false, cfgLogger.getLevel(), abyLogConfig.getName(),
            "true", refs, null, config, null);
    appenders.stream().forEach(e ->
            loggerConfig.addAppender(e, Level.ALL, null)
    );
    config.addLogger(abyLogConfig.getName(), loggerConfig);
    ctx.updateLoggers(config);
}
 
Example 12
Source File: LogUtil.java    From fix-orchestra with Apache License 2.0 5 votes vote down vote up
public static Logger initializeDefaultLogger(Level level, Class<?> clazz) {
  final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
  final Configuration config = ctx.getConfiguration();
  final ConsoleAppender appender = ConsoleAppender.newBuilder().setName("Console").build();
  config.addAppender(appender);
  final AppenderRef ref = AppenderRef.createAppenderRef("Console", level, null);
  final AppenderRef[] refs = new AppenderRef[] {ref};
  final LoggerConfig loggerConfig =
      LoggerConfig.createLogger(true, level, clazz.getName(), null, refs, null, config, null);
  config.addLogger(clazz.getName(), loggerConfig);
  ctx.updateLoggers();
  return LogManager.getLogger(clazz);
}
 
Example 13
Source File: ActorLogger.java    From actor4j-core with Apache License 2.0 5 votes vote down vote up
private ActorLogger() {
	loggerContext = (LoggerContext) LogManager.getContext(LogManager.class.getClassLoader(), false);
	Configuration config = loggerContext.getConfiguration();

	Appender systemConsoleAppender = ConsoleAppender.newBuilder()
		.setName(SYSTEM_CONSOLE_APPENDER_NAME)
		.setLayout(PatternLayout.newBuilder().withPattern(LAYOUT_CONSOLE_SYSTEM).build())
		.setConfiguration(config)
		.build();
	systemConsoleAppender.start();
    AppenderRef[] systemAppenderRefs = new AppenderRef[]{AppenderRef.createAppenderRef(SYSTEM_CONSOLE_APPENDER_NAME, null, null)};
    systemLoggerConfig = LoggerConfig.createLogger(false, Level.DEBUG, SYSTEM_LOGGER_NAME, "true", systemAppenderRefs, null, config, null);
    systemLoggerConfig.addAppender(systemConsoleAppender, null, null);
    
    Appender userConsoleAppender = ConsoleAppender.newBuilder()
		.setName(USER_CONSOLE_APPENDER_NAME)
		.setLayout(PatternLayout.newBuilder().withPattern(LAYOUT_CONSOLE_USER).build())
		.setConfiguration(config)
		.build();
	userConsoleAppender.start();
	AppenderRef[] userAppenderRefs = new AppenderRef[]{AppenderRef.createAppenderRef(USER_CONSOLE_APPENDER_NAME, null, null)};
	userLoggerConfig = LoggerConfig.createLogger(false, Level.DEBUG, USER_LOGGER_NAME, "true", userAppenderRefs, null, config, null);
	userLoggerConfig.addAppender(userConsoleAppender, null, null);

    config.addAppender(systemConsoleAppender);
    config.addAppender(userConsoleAppender);
    config.addLogger(SYSTEM_LOGGER_NAME, systemLoggerConfig);
    config.addLogger(USER_LOGGER_NAME, userLoggerConfig);
	loggerContext.updateLoggers(config);
}
 
Example 14
Source File: LogFactory.java    From chronus with Apache License 2.0 5 votes vote down vote up
public void start(Logger cfgLogger, String clKey) {
    //为false时,返回多个LoggerContext对象, true:返回唯一的单例LoggerContext
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    List<AppenderRef> appenderRefs = new ArrayList<>();
    Map<String, Appender> appenderMap = ((org.apache.logging.log4j.core.Logger) cfgLogger).getAppenders();
    List<Appender> appenders = new ArrayList<>();
    appenderMap.forEach((key, appenderCfg) -> {
        Appender appender;
        if (appenderCfg instanceof ConsoleAppender) {
            appender = appenderCfg;
        } else {
            appender = getAppender(clKey, config, appenderCfg);
        }
        if (appender != null && appender.isStopped()) {
            appender.start();
        }
        if (appender != null) {
            AppenderRef ref = AppenderRef.createAppenderRef(appender.getName(), Level.ALL, null);
            appenderRefs.add(ref);
            appenders.add(appender);
        }
    });
    if (CollectionUtils.isEmpty(appenders)) {
        return;
    }
    AppenderRef[] refs = new AppenderRef[appenderRefs.size()];
    refs = appenderRefs.toArray(refs);
    LoggerConfig loggerConfig = LoggerConfig.createLogger(false, cfgLogger.getLevel(), clKey, "true", refs, null, config, null);
    appenders.stream().forEach(e ->
            loggerConfig.addAppender(e, Level.ALL, null)
    );
    config.addLogger(clKey, loggerConfig);
    ctx.updateLoggers(config);
}
 
Example 15
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 16
Source File: LoggerTest.java    From feign-reactive with Apache License 2.0 4 votes vote down vote up
private static LoggerConfig getLoggerConfig() {
  LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
  Configuration configuration = loggerContext.getConfiguration();
  configuration.addLogger(LOGGER_NAME, new LoggerConfig());
  return configuration.getLoggerConfig(LOGGER_NAME);
}
 
Example 17
Source File: SmokeTestBase.java    From log4j2-elasticsearch with Apache License 2.0 4 votes vote down vote up
public final void createLoggerProgrammatically(Supplier<ElasticsearchAppender.Builder> appenderBuilder, Function<Configuration, AsyncLoggerConfigDelegate> delegateSupplier) {

        LoggerContext ctx = LoggerContext.getContext(false);

        final Configuration config = ctx.getConfiguration();

        Appender appender = appenderBuilder.get().build();
        appender.start();

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

        // set up disruptor forcefully
        ((LifeCycle)delegateSupplier.apply(config)).start();

        AsyncLoggerConfig loggerConfig = (AsyncLoggerConfig) AsyncLoggerConfig.createLogger(false, Level.INFO, DEFAULT_LOGGER_NAME,
                "false", refs, null, config, null );

        loggerConfig.addAppender(appender, Level.INFO, null);

        config.addAppender(appender);
        config.addLogger(DEFAULT_LOGGER_NAME, loggerConfig);

    }
 
Example 18
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 19
Source File: LoggerTest.java    From feign-reactive with Apache License 2.0 4 votes vote down vote up
private static LoggerConfig getLoggerConfig() {
  LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
  Configuration configuration = loggerContext.getConfiguration();
  configuration.addLogger(LOGGER_NAME, new LoggerConfig());
  return configuration.getLoggerConfig(LOGGER_NAME);
}
 
Example 20
Source File: LoggerTest.java    From feign-reactive with Apache License 2.0 4 votes vote down vote up
private static LoggerConfig getLoggerConfig() {
  LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
  Configuration configuration = loggerContext.getConfiguration();
  configuration.addLogger(LOGGER_NAME, new LoggerConfig());
  return configuration.getLoggerConfig(LOGGER_NAME);
}