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

The following examples show how to use ch.qos.logback.classic.encoder.PatternLayoutEncoder#setCharset() . 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: 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 2
Source File: DynamicLogbackLogger.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
protected Appender buildDailyMaxRollingAppender(String name, String fileName, String pattern, int maxBackupIndex) {
    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.setFileNamePattern(new File(getLogPath(), fileName).getAbsolutePath() + ".%d{yyyy-MM-dd-HH}");
    rolling.setMaxHistory(maxBackupIndex);
    rolling.setParent(appender);
    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 3
Source File: DynamicLogbackLogger.java    From tddl with Apache License 2.0 6 votes vote down vote up
private Appender buildAppender(String name, String fileName, String pattern) {
    RollingFileAppender appender = new RollingFileAppender();
    appender.setName(name);
    appender.setAppend(true);
    appender.setFile(new File(getLogPath(), fileName).getAbsolutePath());

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

    PatternLayoutEncoder layout = new PatternLayoutEncoder();
    layout.setPattern(pattern);
    layout.setCharset(Charset.forName(getEncoding()));
    appender.setEncoder(layout);
    // 启动
    appender.start();
    return appender;
}
 
Example 4
Source File: DynamicLogbackLogger.java    From tddl with Apache License 2.0 6 votes vote down vote up
private Appender buildDailyMaxRollingAppender(String name, String fileName, String pattern, int maxBackupIndex) {
    RollingFileAppender appender = new RollingFileAppender();
    appender.setName(name);
    appender.setAppend(true);
    appender.setFile(new File(getLogPath(), fileName).getAbsolutePath());

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

    PatternLayoutEncoder layout = new PatternLayoutEncoder();
    layout.setPattern(pattern);
    layout.setCharset(Charset.forName(getEncoding()));
    appender.setEncoder(layout);
    // 启动
    appender.start();
    return appender;
}
 
Example 5
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 6
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 7
Source File: SpacedLogbackSystem.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
protected Appender<ILoggingEvent> fileAppender(Space space) {
    RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    String logPattern = this.patterns.getProperty("logging.pattern.file", FILE_LOG_PATTERN);
    encoder.setPattern(OptionHelper.substVars(logPattern, context));
    encoder.setCharset(DEFAULT_CHARSET);
    appender.setEncoder(encoder);
    start(encoder);

    // parse path and file
    // first consider spec.path, second, default_spec.path, third logging.path
    LogFile logFile = LogFile.get(patterns);
    Properties defaultProperties = new Properties();
    if (logFile != null) {
        logFile.applyTo(defaultProperties);
    }
    String path = space.getSpec().getPath() != null ? space.getSpec().getPath() :
            space.getDefaultSpec().getPath() != null ? space.getDefaultSpec().getPath() :
                    defaultProperties.contains(LoggingSystemProperties.LOG_PATH)
                            ? defaultProperties.getProperty(LoggingSystemProperties.LOG_PATH) :
                            DEFAULT_PATH;
    path = patterns.resolvePlaceholders(path);
    String file = space.getSpec().getFile() != null
            ? fileName(space.getSpec().getFile()) : fileName(space.getName());
    file = patterns.resolvePlaceholders(file);
    appender.setFile(path + "/" + file);
    setRollingPolicy(appender, space, path, file);

    //  threshold config
    ThresholdFilter thresholdFilter = new ThresholdFilter();
    if (space.getSpec().getThreshold() != null) {
        thresholdFilter.setLevel(space.getSpec().getThreshold());
        start(thresholdFilter);
        appender.addFilter(thresholdFilter);
    }

    appender("SPACE-" + space.getName(), appender);
    return appender;
}
 
Example 8
Source File: LogbackCapture.java    From emissary with Apache License 2.0 5 votes vote down vote up
private static Encoder<ILoggingEvent> buildEncoder(String layoutPattern) {
    if (layoutPattern == null)
        layoutPattern = "[%p] %m%n";
    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setPattern(layoutPattern);
    encoder.setCharset(Charset.forName("UTF-16"));
    encoder.setContext(ContextSelectorStaticBinder.getSingleton().getContextSelector().getDefaultLoggerContext());
    encoder.start();
    return encoder;
}
 
Example 9
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 10
Source File: BaleenLogging.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Configure logging based on a list of builders provided to it. Injects the configured logging to
 * replace the default UIMA loggers, and also sets up metrics on the logging.
 *
 * @param builders The builders to use to configure the logging
 */
public void configure(List<BaleenLoggerBuilder> builders) {
  // Install JUL to SLF4J handling (JUL is default for UIMA)
  SLF4JBridgeHandler.removeHandlersForRootLogger();
  SLF4JBridgeHandler.install();

  // Configure Logback
  LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
  Logger rootLogger = context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);

  // Install the level change propagator to reduce the impact of JUL logging
  context.addListener(new LevelChangePropagator());

  // Remove all the existing appenders
  rootLogger.detachAndStopAllAppenders();

  for (BaleenLoggerBuilder builder : builders) {
    PatternLayoutEncoder ple = new PatternLayoutEncoder();
    ple.setCharset(StandardCharsets.UTF_8);
    ple.setContext(context);
    ple.setPattern(builder.getPattern());
    ple.start();

    Appender<ILoggingEvent> appender = builder.build(context, ple);
    if (!appender.isStarted()) {
      appender.start();
    }

    rootLogger.addAppender(appender);
  }

  LOGGER.debug("Adding instrumented metrics for logging");
  // Add an instrumented appender so we get the information about logging
  // through metrics
  InstrumentedAppender instrumentedAppender =
      new InstrumentedAppender(MetricsFactory.getInstance().getRegistry());
  instrumentedAppender.setContext(context);
  instrumentedAppender.start();
  rootLogger.addAppender(instrumentedAppender);
}
 
Example 11
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 12
Source File: FlickrUploader.java    From flickr-uploader with GNU General Public License v2.0 4 votes vote down vote up
private static void initLogs() {
    Logger logbackLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
    LoggerContext lc = logbackLogger.getLoggerContext();

    Logger rootLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME);
    rootLogger.detachAndStopAllAppenders();

    TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new TimeBasedRollingPolicy<ILoggingEvent>();
    rollingPolicy.setMaxHistory(3);
    SizeAndTimeBasedFNATP<ILoggingEvent> sizeAndTimeBasedFNATP = new SizeAndTimeBasedFNATP<ILoggingEvent>();
    sizeAndTimeBasedFNATP.setMaxFileSize("2MB");
    rollingPolicy.setTimeBasedFileNamingAndTriggeringPolicy(sizeAndTimeBasedFNATP);
    rollingPolicy.setFileNamePattern(context.getFilesDir().getPath() + "/logs/old/flickruploader.%d{yyyy-MM-dd}.%i.log");
    rollingPolicy.setContext(lc);

    RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<ILoggingEvent>();
    fileAppender.setContext(lc);
    fileAppender.setFile(getLogFilePath());
    fileAppender.setRollingPolicy(rollingPolicy);
    fileAppender.setTriggeringPolicy(rollingPolicy);
    rollingPolicy.setParent(fileAppender);

    PatternLayoutEncoder pl = new PatternLayoutEncoder();
    pl.setContext(lc);
    pl.setCharset(Charset.defaultCharset());
    pl.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %class{0}.%method:%L > %msg%n");
    pl.setImmediateFlush(false);
    pl.start();

    fileAppender.setEncoder(pl);
    fileAppender.setName("file");

    rollingPolicy.start();
    fileAppender.start();

    if (Config.isDebug()) {
        final PatternLayoutEncoder logcatTagPattern = new PatternLayoutEncoder();
        logcatTagPattern.setContext(lc);
        logcatTagPattern.setPattern("%class{0}");
        logcatTagPattern.start();

        final PatternLayoutEncoder logcatPattern = new PatternLayoutEncoder();
        logcatPattern.setContext(lc);
        logcatPattern.setPattern("[%thread] %method:%L > %msg%n");
        logcatPattern.start();

        final LogcatAppender logcatAppender = new LogcatAppender();
        logcatAppender.setContext(lc);
        logcatAppender.setTagEncoder(logcatTagPattern);
        logcatAppender.setEncoder(logcatPattern);
        logcatAppender.start();

        rootLogger.addAppender(logcatAppender);
    }

    rootLogger.addAppender(fileAppender);

}