Java Code Examples for ch.qos.logback.classic.encoder.PatternLayoutEncoder#setPattern()

The following examples show how to use ch.qos.logback.classic.encoder.PatternLayoutEncoder#setPattern() . 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: Utils.java    From jlineup with Apache License 2.0 6 votes vote down vote up
public static void logToFile(String workingDir) {
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    PatternLayoutEncoder ple = new PatternLayoutEncoder();

    ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
    ple.setContext(lc);
    ple.start();
    FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
    fileAppender.setName(JLINEUP_FILE_APPENDER);
    fileAppender.setFile(workingDir + "/jlineup.log");
    fileAppender.setEncoder(ple);
    fileAppender.setContext(lc);
    fileAppender.start();

    ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
    logger.addAppender(fileAppender);
    logger.setLevel(Level.DEBUG);
}
 
Example 2
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 3
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 4
Source File: CRLFConverterTest.java    From owasp-security-logging with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
	PatternLayout.defaultConverterMap.put("crlf",
			CRLFConverter.class.getName());
	// layout = new PatternLayout();

	encoder = new PatternLayoutEncoder();
	encoder.setContext(loggerContext);
	encoder.setPattern("%-4relative [%thread] %-5level %logger{35} - %crlf(%msg)%n");
	encoder.start();

	// Layout layout = new PatternLayout();
	// layout.setEncoder(encoder);

	mockAppender.setContext(loggerContext);
	mockAppender.setEncoder(encoder);
	mockAppender.start();

	LOGGER = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
	LOGGER.addAppender(mockAppender);
}
 
Example 5
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 6
Source File: ContainerLogger.java    From skywalking with Apache License 2.0 6 votes vote down vote up
public ContainerLogger(final Path logDirectory, final String container) {

        final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        final PatternLayoutEncoder encoder = new PatternLayoutEncoder();

        encoder.setPattern("%d{HH:mm:ss.SSS} %-5level %logger{36}.%M - %msg%n");
        encoder.setContext(context);
        encoder.start();

        final FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
        fileAppender.setFile(logDirectory.resolve(container).toAbsolutePath().toString());
        fileAppender.setEncoder(encoder);
        fileAppender.setContext(context);
        fileAppender.start();

        final ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(container);
        logger.addAppender(fileAppender);
        logger.setLevel(Level.DEBUG);
        logger.setAdditive(false);

        this.delegate = logger;
    }
 
Example 7
Source File: DynamicLogbackLogger.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
protected Appender buildAppender(String name, String fileName, String pattern) {
    RollingFileAppender appender = new RollingFileAppender();
    appender.setContext(loggerContext);
    appender.setName(name);
    appender.setAppend(true);
    appender.setFile(new File(getLogPath(), fileName).getAbsolutePath());

    TimeBasedRollingPolicy rolling = new TimeBasedRollingPolicy();
    rolling.setContext(loggerContext);
    rolling.setParent(appender);
    rolling.setFileNamePattern(new File(getLogPath(), fileName).getAbsolutePath() + ".%d{yyyy-MM-dd}");
    rolling.start();
    appender.setRollingPolicy(rolling);

    PatternLayoutEncoder layout = new PatternLayoutEncoder();
    layout.setContext(loggerContext);
    layout.setPattern(pattern);
    layout.setCharset(Charset.forName(getEncoding()));
    layout.start();
    appender.setEncoder(layout);
    // 启动
    appender.start();
    return appender;
}
 
Example 8
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 9
Source File: LogbackContainer.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
/**
 * Initializer logback
 *
 * @param file       log file
 * @param level      log level
 * @param maxHistory max history
 */
private void doInitializer(String file, String level, int maxHistory) {
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
    rootLogger.detachAndStopAllAppenders();

    // appender
    RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<>();
    fileAppender.setContext(loggerContext);
    fileAppender.setName("application");
    fileAppender.setFile(file);
    fileAppender.setAppend(true);

    // policy
    TimeBasedRollingPolicy<ILoggingEvent> policy = new TimeBasedRollingPolicy<>();
    policy.setContext(loggerContext);
    policy.setMaxHistory(maxHistory);
    policy.setFileNamePattern(file + ".%d{yyyy-MM-dd}");
    policy.setParent(fileAppender);
    policy.start();
    fileAppender.setRollingPolicy(policy);

    // encoder
    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setContext(loggerContext);
    encoder.setPattern("%date [%thread] %-5level %logger (%file:%line\\) - %msg%n");
    encoder.start();
    fileAppender.setEncoder(encoder);

    fileAppender.start();

    rootLogger.addAppender(fileAppender);
    rootLogger.setLevel(Level.toLevel(level));
    rootLogger.setAdditive(false);
}
 
Example 10
Source File: SingularityRunnerBaseLogging.java    From Singularity with Apache License 2.0 5 votes vote down vote up
public FileAppender<ILoggingEvent> buildFileAppender(
  LoggerContext context,
  String file
) {
  FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
  fileAppender.setFile(file);
  fileAppender.setContext(context);
  fileAppender.setPrudent(true);

  PatternLayoutEncoder encoder = new PatternLayoutEncoder();
  encoder.setContext(context);
  encoder.setPattern(
    primaryConfiguration
      .getLoggingPattern()
      .orElse(
        baseConfiguration.getLoggingPattern().isPresent()
          ? baseConfiguration.getLoggingPattern().get()
          : JavaUtils.LOGBACK_LOGGING_PATTERN
      )
  );
  encoder.start();

  fileAppender.setEncoder(encoder);
  fileAppender.start();

  return fileAppender;
}
 
Example 11
Source File: LogbackContainer.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * Initializer logback
 * 
 * @param file
 * @param level
 * @param maxHistory
 */
private void doInitializer(String file, String level, int maxHistory) {
	LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
	Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
	rootLogger.detachAndStopAllAppenders();

	// appender
	RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<ILoggingEvent>();
	fileAppender.setContext(loggerContext);
	fileAppender.setName("application");
	fileAppender.setFile(file);
	fileAppender.setAppend(true);

	// policy
	TimeBasedRollingPolicy<ILoggingEvent> policy = new TimeBasedRollingPolicy<ILoggingEvent>();
	policy.setContext(loggerContext);
	policy.setMaxHistory(maxHistory);
	policy.setFileNamePattern(file + ".%d{yyyy-MM-dd}");
	policy.setParent(fileAppender);
	policy.start();
	fileAppender.setRollingPolicy(policy);

	// encoder
	PatternLayoutEncoder encoder = new PatternLayoutEncoder();
	encoder.setContext(loggerContext);
	encoder.setPattern("%date [%thread] %-5level %logger (%file:%line\\) - %msg%n");
	encoder.start();
	fileAppender.setEncoder(encoder);
	
	fileAppender.start();

	rootLogger.addAppender(fileAppender);
	rootLogger.setLevel(Level.toLevel(level));
	rootLogger.setAdditive(false);
}
 
Example 12
Source File: AccountImpl.java    From java-trader with Apache License 2.0 5 votes vote down vote up
/**
 * 创建Account Logger
 * @param separateLogger true 会为每个Account创建一个日志文件: TRADER_HOME/work/<TRADING_DAY>/accountId.log
 */
private void createAccountLogger() {
    if ( !simMode ) {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

        FileAppender fileAppender = new FileAppender();
        fileAppender.setContext(loggerContext);
        fileAppender.setName("timestamp");
        // set the file name
        File logFile = new File(tradingWorkDir, id+".log");
        fileAppender.setFile(logFile.getAbsolutePath());

        PatternLayoutEncoder encoder = new PatternLayoutEncoder();
        encoder.setContext(loggerContext);
        encoder.setPattern("%d [%thread] %-5level %logger{35} - %msg %n");
        encoder.start();

        fileAppender.setEncoder(encoder);
        fileAppender.start();

        // attach the rolling file appender to the logger of your choice
        loggerCategory = AccountImpl.class.getName()+"."+id;
        ch.qos.logback.classic.Logger packageLogger = loggerContext.getLogger(loggerCategory);
        packageLogger.addAppender(fileAppender);
        packageLogger.setAdditive(true); //保证每个Account数据, 在主的日志中也有一份

        logger = loggerContext.getLogger(loggerCategory+"."+AccountImpl.class.getSimpleName());
    } else {
        loggerCategory = AccountImpl.class.getName();
        logger = LoggerFactory.getLogger(AccountImpl.class);
    }
}
 
Example 13
Source File: EnvCommand.java    From emissary with Apache License 2.0 5 votes vote down vote up
@Override
public void run(JCommander jc) {
    String endpoint = getScheme() + "://" + getHost() + ":" + getPort() + "/api/env";

    if (getBashable()) {
        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();
        setup();
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        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);

        // still gotta hide org.eclipse.jetty.util.log INFO
        ch.qos.logback.classic.Logger jettyUtilLogger = lc.getLogger("org.eclipse.jetty.util.log");
        jettyUtilLogger.setLevel(Level.WARN);

        // also add .sh to the endpoint
        endpoint = endpoint + ".sh";
        LOG.info("# generated from env command at {}", endpoint);
    } else {
        setup(); // go ahead an log it
    }
    EmissaryClient client = new EmissaryClient();
    LOG.info(client.send(new HttpGet(endpoint)).getContentString());
}
 
Example 14
Source File: EnhancedLogbackConfiguration.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
private Appender<ILoggingEvent> consoleAppender(LogbackConfigurator config) {
	ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
	PatternLayoutEncoder encoder = new PatternLayoutEncoder();
	String logPattern = this.logging.getProperty("pattern.console", CONSOLE_LOG_PATTERN);
	encoder.setPattern(OptionHelper.substVars(logPattern, config.getContext()));
	encoder.setCharset(UTF8);
	config.start(encoder);
	appender.setEncoder(encoder);
	config.appender("CONSOLE", appender);
	return appender;
}
 
Example 15
Source File: EnhancedLogbackConfiguration.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
private Appender<ILoggingEvent> fileAppender(LogbackConfigurator config, String logFile) {
	RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<ILoggingEvent>();
	PatternLayoutEncoder encoder = new PatternLayoutEncoder();
	String logPattern = this.logging.getProperty("pattern.file", FILE_LOG_PATTERN);
	encoder.setPattern(OptionHelper.substVars(logPattern, config.getContext()));
	appender.setEncoder(encoder);
	config.start(encoder);
	appender.setFile(logFile);
	setRollingPolicy(appender, config, logFile);
	setMaxFileSize(appender, config);
	config.appender("FILE", appender);
	return appender;
}
 
Example 16
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 17
Source File: KafkaAppenderIT.java    From logback-kafka-appender with Apache License 2.0 4 votes vote down vote up
@Before
public void beforeLogSystemInit() throws IOException, InterruptedException {

    kafka = TestKafka.createTestKafka(1,1,1);

    loggerContext = new LoggerContext();
    loggerContext.putProperty("brokers.list", kafka.getBrokerList());
    loggerContext.getStatusManager().add(new StatusListener() {
        @Override
        public void addStatusEvent(Status status) {
            if (status.getEffectiveLevel() > Status.INFO) {
                System.err.println(status.toString());
                if (status.getThrowable() != null) {
                    collector.addError(status.getThrowable());
                } else {
                    collector.addError(new RuntimeException("StatusManager reported warning: "+status.toString()));
                }
            } else {
                System.out.println(status.toString());
            }
        }
    });
    loggerContext.putProperty("HOSTNAME","localhost");

    unit = new KafkaAppender<>();
    final PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder();
    patternLayoutEncoder.setPattern("%msg");
    patternLayoutEncoder.setContext(loggerContext);
    patternLayoutEncoder.setCharset(Charset.forName("UTF-8"));
    patternLayoutEncoder.start();
    unit.setEncoder(patternLayoutEncoder);
    unit.setTopic("logs");
    unit.setName("TestKafkaAppender");
    unit.setContext(loggerContext);
    unit.setKeyingStrategy(new NoKeyKeyingStrategy());
    unit.setDeliveryStrategy(new AsynchronousDeliveryStrategy());
    unit.addAppender(fallbackAppender);
    unit.addProducerConfigValue(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.getBrokerList());
    unit.addProducerConfigValue(ProducerConfig.ACKS_CONFIG, "1");
    unit.addProducerConfigValue(ProducerConfig.MAX_BLOCK_MS_CONFIG, "2000");
    unit.addProducerConfigValue(ProducerConfig.LINGER_MS_CONFIG, "100");
    unit.setPartition(0);
    unit.setDeliveryStrategy(new AsynchronousDeliveryStrategy());
    unit.addAppender(new AppenderBase<ILoggingEvent>() {
        @Override
        protected void append(ILoggingEvent eventObject) {
            fallbackLoggingEvents.add(eventObject);
        }
    });
}
 
Example 18
Source File: AionLoggerFactory.java    From aion with MIT License 4 votes vote down vote up
private static List<Appender<ILoggingEvent>> constructAppenders(
        boolean shouldLogToFile, String _logDirectory) {
    List<Appender<ILoggingEvent>> appenders = new ArrayList<>();

    String logDirectory = DEFAULT_LOG_DIR;
    if (_logDirectory != null && !_logDirectory.trim().isEmpty()) logDirectory = _logDirectory;

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

    ConsoleAppender<ILoggingEvent> consoleSync = new ConsoleAppender<>();
    consoleSync.setContext(context);
    consoleSync.setName("consoleSyncAppender"); // for logger debugging
    consoleSync.setEncoder(encoder);
    consoleSync.start();

    AsyncAppender consoleAsync = new AsyncAppender();
    consoleAsync.setContext(context);
    consoleAsync.setName("consoleAsyncAppender"); // for logger debugging
    consoleAsync.addAppender(consoleSync);

    consoleAsync.setIncludeCallerData(ASYNC_LOGGER_INCLUDE_CALLER_DATA);
    consoleAsync.setNeverBlock(ASYNC_LOGGER_NEVER_BLOCK);
    consoleAsync.setMaxFlushTime(ASYNC_LOGGER_MAX_FLUSH_TIME_MS);
    consoleAsync.setDiscardingThreshold(ASYNC_LOGGER_DISCARDING_THRESHOLD);
    consoleAsync.setQueueSize(ASYNC_LOGGER_QUEUE_SIZE);
    consoleAsync.start();

    appenders.add(consoleAsync);
    if (!shouldLogToFile) return appenders;

    RollingFileAppender<ILoggingEvent> fileSync = new RollingFileAppender<>();

    SizeBasedTriggeringPolicy<ILoggingEvent> tp = new SizeBasedTriggeringPolicy<>();
    tp.setContext(context);
    tp.start();

    SizeAndTimeBasedRollingPolicy rp = new SizeAndTimeBasedRollingPolicy();
    rp.setContext(context);
    // roll-over each day
    // notice that we don't use the OS-agnostic File.separator here since logback is converts
    // the FileNamePattern
    // to a unix-style path using ch.qos.logback.core.rolling.helper.FileFilterUtil.slashify
    FileNamePattern fnp =
            new FileNamePattern(
                    logDirectory + "/%d{yyyy/MM, aux}/aion.%d{yyyy-MM-dd}.%i.log", context);
    rp.setFileNamePattern(fnp.getPattern());
    // max rollover file size = 100MB
    rp.setMaxFileSize(FileSize.valueOf("100mb"));
    rp.setParent(fileSync);
    rp.start();

    fileSync.setName("fileSyncAppender"); // for logger debugging
    fileSync.setContext(context);
    fileSync.setTriggeringPolicy(tp);
    fileSync.setRollingPolicy(rp);
    fileSync.setFile(logDirectory + File.separator + DEFAULT_LOG_FILE_CURRENT);
    fileSync.setEncoder(encoder);
    fileSync.setAppend(true);
    fileSync.start();

    AsyncAppender fileAsync = new AsyncAppender();
    fileAsync.setContext(context);
    fileAsync.setName("fileAsyncAppender"); // for logger debugging
    fileAsync.addAppender(fileSync);

    fileAsync.setIncludeCallerData(ASYNC_LOGGER_INCLUDE_CALLER_DATA);
    fileAsync.setNeverBlock(ASYNC_LOGGER_NEVER_BLOCK);
    fileAsync.setMaxFlushTime(ASYNC_LOGGER_MAX_FLUSH_TIME_MS);
    fileAsync.setDiscardingThreshold(ASYNC_LOGGER_DISCARDING_THRESHOLD);
    fileAsync.setQueueSize(ASYNC_LOGGER_QUEUE_SIZE);
    fileAsync.start();

    appenders.add(fileAsync);
    return appenders;
}
 
Example 19
Source File: MvcApp.java    From AndroidMvc with Apache License 2.0 4 votes vote down vote up
private void configureLogbackDirectly() {
    // reset the default context (which may already have been initialized)
    // since we want to reconfigure it
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    lc.reset();

    // setup FileAppender
    PatternLayoutEncoder encoder1 = new PatternLayoutEncoder();
    encoder1.setContext(lc);
    encoder1.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
    encoder1.start();

    FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
    fileAppender.setContext(lc);
    fileAppender.setFile(this.getFileStreamPath("app.log").getAbsolutePath());
    fileAppender.setEncoder(encoder1);
    fileAppender.start();

    // setup LogcatAppender
    PatternLayoutEncoder encoder2 = new PatternLayoutEncoder();
    encoder2.setContext(lc);
    encoder2.setPattern("[%thread] %msg%n");
    encoder2.start();

    LogcatAppender logcatAppender = new LogcatAppender();
    logcatAppender.setContext(lc);
    logcatAppender.setEncoder(encoder2);
    logcatAppender.start();

    // backup the newly created appenders to the root logger;
    // qualify Logger to disambiguate from org.slf4j.Logger
    ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    root.addAppender(fileAppender);
    root.addAppender(logcatAppender);

    if (BuildConfig.DEBUG) {
        root.setLevel(Level.ALL);
    } else {
        root.setLevel(Level.INFO);
    }
}
 
Example 20
Source File: OfframpConsole.java    From data-highway with Apache License 2.0 4 votes vote down vote up
/**
 * Helper function to configure where message and CLI output is directed as well as configure logging
 * This should be called first to ensure correct output of message and cli logging into the desired stream.
 */
private void configureOutput() {
  try {
    if (flipOutput) {
      PrintStream tmp = msgout;
      msgout = cliout;
      cliout = tmp;
    }

    // change output format from json to yaml
    if (format == Format.YAML) {
      mapper = new YAMLMapper();
    }

    // retrieve the ch.qos.logback.classic.LoggerContext
    LoggerContext logCtx = (LoggerContext) org.slf4j.LoggerFactory.getILoggerFactory();

    PatternLayoutEncoder logEncoder = new PatternLayoutEncoder();
    logEncoder.setContext(logCtx);
    logEncoder.setPattern("%d{HH:mm:ss.SSS} - %-5level %logger{35} - %msg%n");
    logEncoder.start();

    OutputStreamAppender logConsoleAppender = new OutputStreamAppender();
    logConsoleAppender.setContext(logCtx);
    logConsoleAppender.setOutputStream(cliout);
    logConsoleAppender.setName("console");
    logConsoleAppender.setEncoder(logEncoder);
    logConsoleAppender.start();

    Logger rootLogger = logCtx.getLogger("root");
    rootLogger.detachAndStopAllAppenders();
    rootLogger.setLevel(Level.WARN);
    rootLogger.addAppender(logConsoleAppender);

    Logger roadLogger = logCtx.getLogger("com.hotels.road");
    roadLogger.setLevel(Level.WARN);

    Logger clientLogger = logCtx.getLogger("com.hotels.road.offramp.client");
    clientLogger.setLevel(debug ? Level.DEBUG : Level.INFO);

    Logger cliLogger = logCtx.getLogger("com.hotels.road.tool.cli");
    cliLogger.setLevel(debug ? Level.DEBUG : Level.INFO);
  } catch (Exception e) {
    System.err.println("Error configuring the message and cli output:");
    e.printStackTrace();
    System.exit(Error.OUTPUT_CONFIGURATION.code);
  }
}