ch.qos.logback.core.ConsoleAppender Java Examples

The following examples show how to use ch.qos.logback.core.ConsoleAppender. 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: Emissary.java    From emissary with Apache License 2.0 6 votes vote down vote up
static void setupLogbackForConsole() {
    // So it looks better when commands are run
    ch.qos.logback.classic.Logger root =
            (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
    root.detachAndStopAllAppenders();
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    lc.reset();

    PatternLayoutEncoder ple = new PatternLayoutEncoder();
    ple.setPattern("%msg%n");
    ple.setContext(lc);
    ple.start();

    ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();
    consoleAppender.setEncoder(ple);
    consoleAppender.setContext(lc);
    consoleAppender.start();

    root.addAppender(consoleAppender);
    root.setLevel(Level.INFO);
    root.setAdditive(false);
}
 
Example #2
Source File: BaleenLoggerBuilderTest.java    From baleen with Apache License 2.0 6 votes vote down vote up
/** Test abstract functions (using console implementation) and the functions of console */
@Test
public void testAbstractAndConsole() {
  BaleenConsoleLoggerBuilder builder =
      new BaleenConsoleLoggerBuilder(
          NAME, BaleenLogging.DEFAULT_PATTERN, new MinMaxFilter(Level.INFO, Level.WARN));

  LoggerContext context = new LoggerContext();
  Encoder<ILoggingEvent> encoder = new PatternLayoutEncoder();

  Appender<ILoggingEvent> appender = builder.build(context, encoder);

  assertEquals(NAME, builder.getName());

  assertTrue(appender instanceof ConsoleAppender);
  assertEquals(encoder, ((ConsoleAppender<ILoggingEvent>) appender).getEncoder());

  assertNotNull(appender);
  assertEquals(NAME, appender.getName());
  Filter<ILoggingEvent> filter = appender.getCopyOfAttachedFiltersList().get(0);
  assertTrue(filter instanceof MinMaxFilter);
  assertEquals(Level.INFO, ((MinMaxFilter) filter).getMin());
  assertEquals(Level.WARN, ((MinMaxFilter) filter).getMax());
}
 
Example #3
Source File: KonkerLoggerBasicConfigurator.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
public static void configure(KonkerLoggerContext lc) {
    StatusManager sm = lc.getStatusManager();
    if(sm != null) {
        sm.add(new InfoStatus("Setting up default configuration.", lc));
    }

    ConsoleAppender ca = new ConsoleAppender();
    ca.setContext(lc);
    ca.setName("console");
    PatternLayoutEncoder pl = new PatternLayoutEncoder();
    pl.setContext(lc);
    pl.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
    pl.start();
    ca.setEncoder(pl);
    ca.start();
    KonkerLogger rootLogger = lc.getLogger("ROOT");
    rootLogger.addAppender(ca);
}
 
Example #4
Source File: StartupAppender.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
public void logToConsole()
{
    Context context = getContext();
    ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();
    consoleAppender.setContext(context);
    PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder();
    patternLayoutEncoder.setContext(context);

    // added MDC variable 'qpid.log.prefix' for test purposes
    patternLayoutEncoder.setPattern("%X{qpid.log.prefix}%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
    patternLayoutEncoder.start();

    consoleAppender.addFilter(new Filter<ILoggingEvent>()
    {
        @Override
        public FilterReply decide(final ILoggingEvent event)
        {
            return event.getLevel().isGreaterOrEqual(_consoleAppenderAcceptLogLevel) ? FilterReply.ACCEPT : FilterReply.DENY;
        }
    });

    consoleAppender.setEncoder(patternLayoutEncoder);
    consoleAppender.start();
    replayAccumulatedEvents(consoleAppender);
    consoleAppender.stop();
}
 
Example #5
Source File: BrokerConsoleLoggerImpl.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Override
protected Appender<ILoggingEvent> createAppenderInstance(Context context)
{
    ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();

    final PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setPattern(getLayout());
    encoder.setContext(context);
    encoder.start();

    if (_consoleStreamTarget == ConsoleStreamTarget.STDERR)
    {
        consoleAppender.setTarget("System.err");
    }
    consoleAppender.setEncoder(encoder);

    return consoleAppender;
}
 
Example #6
Source File: MaruLoggerFactory.java    From MMDownloader with Apache License 2.0 6 votes vote down vote up
/**
 * 개행 없이 메시지 자체만 출력하는 프린트용 Logger 를 가져온다.
 *
 * @return 출력용 Logger 객체
 */
public static Logger getPrintLogger() {
	if (printLogger != null) {
		return printLogger;
	}

	LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
	PatternLayoutEncoder encoder = getEncoder(loggerContext, "%msg");

	String loggerName = "printLogger";
	ConsoleAppender consoleAppender = getConsoleAppender(loggerContext, encoder);

	printLogger = loggerContext.getLogger(loggerName);
	printLogger.addAppender(consoleAppender);
	printLogger.setAdditive(false);

	return printLogger;
}
 
Example #7
Source File: LogbackLogConfigurator.java    From butterfly with MIT License 6 votes vote down vote up
@Override
    public void setVerboseMode(boolean verboseMode) {
        this.verboseMode = verboseMode;

        if (verboseMode) {
            PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder();
            patternLayoutEncoder.setPattern("[%d{HH:mm:ss.SSS}] [%highlight(%level)] %msg%n");
            patternLayoutEncoder.setContext(loggerContext);
            patternLayoutEncoder.start();

            Appender<ILoggingEvent> consoleAppender = new ConsoleAppender();
            ((OutputStreamAppender) consoleAppender).setEncoder(patternLayoutEncoder);
            consoleAppender.setContext(loggerContext);
            consoleAppender.start();

            loggerContext.getLogger("com.paypal.butterfly.cli").detachAppender("CONSOLE");
            loggerContext.getLogger("ROOT").addAppender(consoleAppender);
//        } else {
            // TODO
        }
    }
 
Example #8
Source File: LogbackLoggingConfigurer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void doFailSafeConfiguration() {
    // Not really fail-safe, just less likely to fail
    final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.reset();
    Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
    rootLogger.setLevel(Level.INFO);

    ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
    rootLogger.addAppender(appender);
    appender.setContext(context);
    appender.setTarget("System.err");

    PatternLayout layout = new PatternLayout();
    appender.setLayout(layout);
    layout.setPattern("%msg%n%ex");
    layout.setContext(context);

    layout.start();
    appender.start();
}
 
Example #9
Source File: LogbackLoggingConfigurer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void doFailSafeConfiguration() {
    // Not really fail-safe, just less likely to fail
    final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.reset();
    Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
    rootLogger.setLevel(Level.INFO);

    ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
    rootLogger.addAppender(appender);
    appender.setContext(context);
    appender.setTarget("System.err");

    PatternLayout layout = new PatternLayout();
    appender.setLayout(layout);
    layout.setPattern("%msg%n%ex");
    layout.setContext(context);

    layout.start();
    appender.start();
}
 
Example #10
Source File: LogAppender.java    From nuls-v2 with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static Appender<ILoggingEvent> createConsoleAppender(Level level){
    ConsoleAppender appender = new ConsoleAppender();
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    appender.setContext(context);
    //这里设置级别过滤器
    LogFilter levelController = new LogFilter();
    ThresholdFilter levelFilter = levelController.getThresholdFilter(level);
    levelFilter.start();
    appender.addFilter(levelFilter);

    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    //设置上下文,每个logger都关联到logger上下文,默认上下文名称为default。
    //但可以使用<contextName>设置成其他名字,用于区分不同应用程序的记录。一旦设置,不能修改。
    encoder.setContext(context);
    //设置格式
    encoder.setPattern("%d %p [%t] - %msg%n");
    encoder.start();
    //加入下面两个节点
    appender.setEncoder(encoder);
    appender.start();
    return appender;
}
 
Example #11
Source File: LocalMainCommand.java    From terracotta-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
  Logger rootLogger = (Logger) LoggerFactory.getLogger(ROOT_LOGGER_NAME);

  if (verbose) {
    ConsoleAppender<ILoggingEvent> appender = (ConsoleAppender<ILoggingEvent>) rootLogger.getAppender("STDOUT");
    PatternLayoutEncoder ple = new PatternLayoutEncoder();
    ple.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %c{1}:%L - %msg%n");
    ple.setContext(appender.getContext());
    ple.start();

    appender.setEncoder(ple);
    rootLogger.setLevel(Level.TRACE);
    rootLogger.getLoggerContext().getLoggerList().forEach(logger -> logger.setLevel(Level.TRACE));
  }
}
 
Example #12
Source File: LogbackFactory.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
public static ConsoleAppender<ILoggingEvent> buildConsoleAppender(LoggingConfiguration.ConsoleConfiguration console,
                                                                  LoggerContext context,
                                                                  String logFormat) {
    final LogFormatter formatter = new LogFormatter(context, console.getTimeZone());
    if (logFormat != null) {
        formatter.setPattern(logFormat);
    }
    formatter.start();

    final ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
    appender.setContext(context);
    appender.setLayout(formatter);
    addThresholdFilter(appender, console.getThreshold());
    appender.start();

    return appender;
}
 
Example #13
Source File: StructuredLogging.java    From flo with Apache License 2.0 6 votes vote down vote up
public static void configureStructuredLogging(Level level) {
  final Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);

  final LoggerContext context = rootLogger.getLoggerContext();
  context.reset();

  final StructuredLoggingEncoder encoder = new StructuredLoggingEncoder();
  encoder.start();

  final ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
  appender.setTarget("System.err");
  appender.setName("stderr");
  appender.setEncoder(encoder);
  appender.setContext(context);
  appender.start();

  rootLogger.addAppender(appender);
  rootLogger.setLevel(fromLocationAwareLoggerInteger(level.toInt()));

  SLF4JBridgeHandler.install();
}
 
Example #14
Source File: LogbackLoggingConfigurer.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void doFailSafeConfiguration() {
    // Not really fail-safe, just less likely to fail
    final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.reset();
    Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
    rootLogger.setLevel(Level.INFO);

    ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
    rootLogger.addAppender(appender);
    appender.setContext(context);
    appender.setTarget("System.err");

    PatternLayout layout = new PatternLayout();
    appender.setLayout(layout);
    layout.setPattern("%msg%n%ex");
    layout.setContext(context);

    layout.start();
    appender.start();
}
 
Example #15
Source File: LogbackLoggingConfigurer.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void doFailSafeConfiguration() {
    // Not really fail-safe, just less likely to fail
    final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.reset();
    Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
    rootLogger.setLevel(Level.INFO);

    ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
    rootLogger.addAppender(appender);
    appender.setContext(context);
    appender.setTarget("System.err");

    PatternLayout layout = new PatternLayout();
    appender.setLayout(layout);
    layout.setPattern("%msg%n%ex");
    layout.setContext(context);

    layout.start();
    appender.start();
}
 
Example #16
Source File: LogbackFactory.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
public static ConsoleAppender<ILoggingEvent> buildConsoleAppender(LoggingConfiguration.ConsoleConfiguration console,
                                                                  LoggerContext context,
                                                                  String logFormat) {
    final LogFormatter formatter = new LogFormatter(context, console.getTimeZone());
    if (logFormat != null) {
        formatter.setPattern(logFormat);
    }
    formatter.start();

    final ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
    appender.setContext(context);
    appender.setLayout(formatter);
    addThresholdFilter(appender, console.getThreshold());
    appender.start();

    return appender;
}
 
Example #17
Source File: LogbackLogManager.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
private void configureConsole(LoggingConfig.ConsoleConfig consoleConfig, Logger rootLogger) {
    if (consoleConfig.isEnabled()) {
        ConsoleAppender<ILoggingEvent> logConsoleAppender = new ConsoleAppender<>();
        logConsoleAppender.setContext(context);
        switch (consoleConfig.getOutput()) {
            case STDOUT:
                logConsoleAppender.setTarget("System.out");
                break;
            case STDERR:
                logConsoleAppender.setTarget("System.err");
                break;
            default:
                logConsoleAppender.setTarget("System.out");
                break;
        }
        logConsoleAppender.setEncoder(buildEncoder(consoleConfig, DEFAULT_CONSOLE_PATTERN));
        logConsoleAppender.start();
        rootLogger.addAppender(logConsoleAppender);
    }
}
 
Example #18
Source File: LoggingConfigurator.java    From logging-java with Apache License 2.0 6 votes vote down vote up
/**
 * Configure logging with the LogstashEncoder library.
 * (https://github.com/logstash/logstash-logback-encoder)
 *
 * An appender is configured to send the log messages to stdout. It is expected something like
 * a Docker container will capture these logs for further processing.
 *
 */
public static void configureLogstashEncoderDefaults(final Level level) {
  final Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
  final LoggerContext context = rootLogger.getLoggerContext();

  context.reset();

  final CustomLogstashEncoder encoder = new CustomLogstashEncoder().setupStackdriver();
  encoder.setContext(context);
  encoder.start();

  final ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
  appender.setTarget("System.out");
  appender.setName("stdout");
  appender.setEncoder(encoder);
  appender.setContext(context);
  appender.start();

  rootLogger.addAppender(appender);
  rootLogger.setLevel(level.logbackLevel);

  UncaughtExceptionLogger.setDefaultUncaughtExceptionHandler();
}
 
Example #19
Source File: LoggingConfigurator.java    From logging-java with Apache License 2.0 6 votes vote down vote up
/**
 * Create a stderr appender.
 *
 * @param context The logger context to use.
 * @return An appender writing to stderr.
 */
private static Appender<ILoggingEvent> getStdErrAppender(final LoggerContext context,
                                                         final ReplaceNewLines replaceNewLines) {

  // Setup format
  final PatternLayoutEncoder encoder = new PatternLayoutEncoder();
  encoder.setContext(context);
  encoder.setPattern(
      "%date{HH:mm:ss.SSS} %property{ident}[%property{pid}]: %-5level [%thread] %logger{0}: "
          + ReplaceNewLines.getMsgPattern(replaceNewLines) + "%n");
  encoder.setCharset(Charsets.UTF_8);
  encoder.start();

  // Setup stderr appender
  final ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
  appender.setTarget("System.err");
  appender.setName("stderr");
  appender.setEncoder(encoder);
  appender.setContext(context);
  appender.start();

  return appender;
}
 
Example #20
Source File: LoggingConfiguratorTest.java    From logging-java with Apache License 2.0 5 votes vote down vote up
private void assertDefault(final String ident, final Level level) {
  final Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
  final ConsoleAppender<?> stderr = (ConsoleAppender<?>) rootLogger.getAppender("stderr");
  assertTrue(stderr.getEncoder() instanceof PatternLayoutEncoder);
  assertEquals(level, rootLogger.getLevel());
  final LoggerContext context = rootLogger.getLoggerContext();
  assertEquals(ident, context.getProperty("ident"));
}
 
Example #21
Source File: AgentOutputAppender.java    From gocd with Apache License 2.0 5 votes vote down vote up
void writeTo(Outstream target) {
    ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<>();
    appender.setTarget(target.target.getName());
    appender.setEncoder(LogHelper.encoder("%date{ISO8601} [" + target.marker + "] - %msg%n"));
    appender.start();
    appenders.add(appender);
}
 
Example #22
Source File: DefaultPluginLoggingService.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void initializeLoggerForPluginId(String pluginId) {
    if (alreadyInitialized(pluginId)) {
        return;
    }

    synchronized (pluginId.intern()) {
        if (alreadyInitialized(pluginId)) {
            return;
        }

        synchronized (appenderCreationLock) {
            FileAppender<ILoggingEvent> pluginAppender = getAppender(pluginId);

            ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(PLUGIN_LOGGER_PREFIX + "." + pluginId);
            logger.setAdditive(false);
            logger.setLevel(systemEnvironment.pluginLoggingLevel(pluginId));
            logger.addAppender(pluginAppender);

            if (systemEnvironment.consoleOutToStdout()) {
                ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();
                consoleAppender.setEncoder(LogHelper.encoder("%d{ISO8601} %5p [%t] %c{1}:%L [plugin-" + pluginId + "] - %m%n"));
                logger.setAdditive(false);
                logger.setLevel(systemEnvironment.pluginLoggingLevel(pluginId));
                consoleAppender.start();
                logger.addAppender(consoleAppender);
            }

            loggingServiceLogger.debug("Plugin with ID: " + pluginId + " will log to: " + pluginAppender.rawFileProperty());
        }
    }
}
 
Example #23
Source File: LoggerUtil.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
private static ConsoleAppender<ILoggingEvent> createConsoleAppender(final LoggerContext loggerContext) {
    final PatternLayoutEncoder ple = new PatternLayoutEncoder();
    ple.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{10} - %msg%n");
    ple.setContext(loggerContext);
    ple.start();

    final ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();
    consoleAppender.setContext(loggerContext);
    consoleAppender.setEncoder(ple);
    consoleAppender.setName("STDOUT");
    consoleAppender.start();
    return consoleAppender;
}
 
Example #24
Source File: LoggerUtil.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
private static void setLogLevel(final ConsoleAppender<ILoggingEvent> consoleAppender,
        final Level level, final String clazz) {
    final ch.qos.logback.classic.Logger protocolLogger
            = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(clazz);
    protocolLogger.addAppender(consoleAppender);
    protocolLogger.setLevel(level);
    protocolLogger.setAdditive(false);
}
 
Example #25
Source File: CombinatorialMaterializerTest.java    From tasmo with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void logger() {

    Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    LoggerContext loggerContext = rootLogger.getLoggerContext();
    loggerContext.reset();

    if (verbose) {

        PatternLayoutEncoder encoder = new PatternLayoutEncoder();
        encoder.setContext(loggerContext);
        encoder.setPattern("[%thread]: %message%n");
        encoder.start();

        ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<>();
        appender.setContext(loggerContext);
        appender.setEncoder(encoder);
        appender.start();

        rootLogger.addAppender(appender);

        ((Logger) LoggerFactory.getLogger("com.jivesoftware.os.tasmo")).setLevel(Level.TRACE);
        ((Logger) LoggerFactory.getLogger("com.jivesoftware.os.tasmo.lib.concur.ConcurrencyAndExistanceCommitChange")).setLevel(Level.TRACE);
        ((Logger) LoggerFactory.getLogger("com.jivesoftware.os.tasmo.reference.lib.ReferenceStore")).setLevel(Level.TRACE);
        ((Logger) LoggerFactory.getLogger("com.jivesoftware.os.tasmo.view.reader.service.writer.WriteToViewValueStore")).setLevel(Level.TRACE);
    } else {

        rootLogger.setLevel(Level.OFF);
    }
}
 
Example #26
Source File: Configuration.java    From ShootOFF with GNU General Public License v3.0 5 votes vote down vote up
private static void setLogConsoleAppender(Logger rootLogger, LoggerContext loggerContext) {
	final PatternLayoutEncoder ple = new PatternLayoutEncoder();

	ple.setPattern("%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n");
	ple.setContext(loggerContext);
	ple.start();
	final ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();
	consoleAppender.setEncoder(ple);
	consoleAppender.setContext(loggerContext);
	consoleAppender.start();

	rootLogger.detachAndStopAllAppenders();
	rootLogger.setAdditive(false);
	rootLogger.addAppender(consoleAppender);
}
 
Example #27
Source File: BaleenLoggerBuilderTest.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Test
public void testAbstractAndConsoleMultipleFilters() {
  BaleenConsoleLoggerBuilder builder =
      new BaleenConsoleLoggerBuilder(
          NAME,
          BaleenLogging.DEFAULT_PATTERN,
          Arrays.asList(
              new MinMaxFilter(Level.INFO, Level.ERROR),
              new MinMaxFilter(Level.INFO, Level.WARN)));

  LoggerContext context = new LoggerContext();
  Encoder<ILoggingEvent> encoder = new PatternLayoutEncoder();

  Appender<ILoggingEvent> appender = builder.build(context, encoder);

  assertEquals(NAME, builder.getName());

  assertTrue(appender instanceof ConsoleAppender);
  assertEquals(encoder, ((ConsoleAppender<ILoggingEvent>) appender).getEncoder());

  assertNotNull(appender);
  assertEquals(NAME, appender.getName());
  assertEquals(2, appender.getCopyOfAttachedFiltersList().size());
  Filter<ILoggingEvent> filter = appender.getCopyOfAttachedFiltersList().get(0);
  assertTrue(filter instanceof MinMaxFilter);
  assertEquals(Level.INFO, ((MinMaxFilter) filter).getMin());
  assertEquals(Level.ERROR, ((MinMaxFilter) filter).getMax());

  filter = appender.getCopyOfAttachedFiltersList().get(1);
  assertTrue(filter instanceof MinMaxFilter);
  assertEquals(Level.INFO, ((MinMaxFilter) filter).getMin());
  assertEquals(Level.WARN, ((MinMaxFilter) filter).getMax());

  // TODO: Test that both filters are being applied
}
 
Example #28
Source File: DefaultLogbackReInitializer.java    From sofa-common-tools with Apache License 2.0 5 votes vote down vote up
@Override
public void reInitialize(final SpaceId spaceId, LoggerContext loggerContext,
                         final Properties properties, URL confFile) {
    if (isAlreadyReInitialized(loggerContext)) {
        return;
    }
    stopAndReset(loggerContext);
    loggerContext.getTurboFilterList().remove(DefaultLogbackFilterGenerator.FILTER);
    markAsReInitialized(loggerContext);
    initProperties(loggerContext, properties);
    if (isConsoleAppenderOpen(spaceId.getSpaceName(), properties)) {
        final ConsoleAppender appender = consoleAppender(loggerContext, properties);
        loggerContext.addTurboFilter(new TurboFilter() {
            @Override
            public FilterReply decide(Marker marker, Logger logger, Level level, String format,
                                      Object[] params, Throwable t) {
                if (!logger.isAttached(appender)) {
                    logger.detachAndStopAllAppenders();
                    logger.setLevel(getConsoleLevel(spaceId.getSpaceName(), properties));
                    logger.addAppender(appender);
                }
                return FilterReply.NEUTRAL;
            }
        });
    } else {
        try {
            new ContextInitializer(loggerContext).configureByResource(confFile);
        } catch (JoranException e) {
            throw new IllegalStateException("Logback loggerSpaceFactory re-build error", e);
        }
    }

}
 
Example #29
Source File: SpacedLogbackSystem.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
private Appender<ILoggingEvent> consoleAppender() {
    ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<>();
    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    String logPattern = this.patterns.getProperty("logging.pattern.console", FILE_LOG_PATTERN);
    encoder.setPattern(OptionHelper.substVars(logPattern, context));
    encoder.setCharset(DEFAULT_CHARSET);
    appender.setEncoder(encoder);
    start(encoder);
    appender("console", appender);
    return appender;
}
 
Example #30
Source File: LoggingConfiguration.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
private void addJsonConsoleAppender(LoggerContext context) {
    log.info("Initializing Console logging");
    
    // More documentation is available at: https://github.com/logstash/logstash-logback-encoder
    ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();
    consoleAppender.setContext(context);
    consoleAppender.setEncoder(compositeJsonEncoder(context));
    consoleAppender.setName(CONSOLE_APPENDER_NAME);
    consoleAppender.start();

    context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME).detachAppender(CONSOLE_APPENDER_NAME);
    context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME).addAppender(consoleAppender);
}