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

The following examples show how to use ch.qos.logback.classic.encoder.PatternLayoutEncoder#start() . 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: BaseTestCase.java    From AndroidMvc with Apache License 2.0 6 votes vote down vote up
private static 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 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(logcatAppender);

    root.setLevel(Level.ALL);
}
 
Example 2
Source File: LogUtil.java    From audiveris with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Add a specific appender meant for FILE.
 */
public static void addFileAppender ()
{
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(
            Logger.ROOT_LOGGER_NAME);
    FileAppender fileAppender = new FileAppender();
    PatternLayoutEncoder fileEncoder = new PatternLayoutEncoder();
    fileAppender.setName("FILE");
    fileAppender.setContext(loggerContext);
    fileAppender.setAppend(false);

    String now = new SimpleDateFormat("yyyyMMdd'T'HHmmss").format(new Date());
    Path logPath = WellKnowns.LOG_FOLDER.resolve(now + ".log").toAbsolutePath();
    fileAppender.setFile(logPath.toString());
    fileEncoder.setContext(loggerContext);
    fileEncoder.setPattern(
            "%date %-5level [%X{BOOK}%X{SHEET}] %25replace(%file){'\\.java$',''} %-4line | %msg%n%ex");
    fileEncoder.start();
    fileAppender.setEncoder(fileEncoder);
    fileAppender.start();
    root.addAppender(fileAppender);

    initMessage("LogUtil. Logging to " + logPath);
}
 
Example 3
Source File: MaskingConverterTest.java    From owasp-security-logging with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
	PatternLayout.defaultConverterMap.put("mask",
			MaskingConverter.class.getName());

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

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

	LOGGER.addAppender(mockAppender);
}
 
Example 4
Source File: LoggingConfig.java    From mirror with Apache License 2.0 6 votes vote down vote up
public synchronized static void enableLogFile() {
  init();

  LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

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

  FileAppender<ILoggingEvent> file = new FileAppender<>();
  file.setContext(context);
  file.setAppend(true);
  file.setFile("mirror.log");
  file.setEncoder(encoder);
  file.start();
  getRootLogger().addAppender(file);
}
 
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: LogbackConfig.java    From g4proxy with Apache License 2.0 6 votes vote down vote up
private static void configLog() {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.reset();

    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setPattern("g4Proxy-%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
    encoder.setContext(context);
    encoder.start();


    LogcatAppender logcatAppender = new LogcatAppender();
    logcatAppender.setContext(context);
    logcatAppender.setEncoder(encoder);
    logcatAppender.setName("logcat1");
    logcatAppender.start();

    Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    root.setLevel(Level.INFO);
    root.addAppender(logcatAppender);

}
 
Example 7
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 8
Source File: LogUtil.java    From obevo with Apache License 2.0 5 votes vote down vote up
private FileAppender<ILoggingEvent> createAppender(String logFilePath) {
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    PatternLayoutEncoder ple = new PatternLayoutEncoder();

    ple.setPattern("[%p] %c{1} [%t] %d{[M-dd HH:mm:ss]} - %m%n");
    ple.setContext(lc);
    ple.start();
    FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
    fileAppender.setFile(logFilePath);
    fileAppender.setEncoder(ple);
    fileAppender.setContext(lc);
    fileAppender.start();

    return fileAppender;
}
 
Example 9
Source File: MaruLoggerFactory.java    From MMDownloader with Apache License 2.0 5 votes vote down vote up
private static PatternLayoutEncoder getEncoder(LoggerContext loggerContext, String pattern) {
	PatternLayoutEncoder encoder = new PatternLayoutEncoder();
	encoder.setContext(loggerContext);
	encoder.setPattern(pattern);
	encoder.start();
	return encoder;
}
 
Example 10
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 11
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 12
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 13
Source File: JarBimServer.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Add a file appender to every logger we can find (the loggers should already have been configured via logback.xml)
 * 
 * @throws IOException
 */
private void fixLogging(BimServerConfig config) throws IOException {
	Path logFolder = config.getHomeDir().resolve("logs");
	if (!Files.isDirectory(logFolder)) {
		Files.createDirectories(logFolder);
	}
	Path file = logFolder.resolve("bimserver.log");

	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<ILoggingEvent>();
	String filename = file.toAbsolutePath().toString();

	if (lc instanceof LoggerContext) {
	    if (!lc.isStarted()) {
	    	lc.start();
	    }
	}
	
	System.out.println("Logging to " + filename);
	
	fileAppender.setFile(filename);
	fileAppender.setEncoder(ple);
	fileAppender.setContext(lc);
	fileAppender.start();

	for (ch.qos.logback.classic.Logger log : lc.getLoggerList()) {
		if (log.getLevel() != null) {
			log.addAppender(fileAppender);
		}
	}
}
 
Example 14
Source File: LogUtils.java    From konduit-serving with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the appenders for command line.
 */
public static void setAppendersForCommandLine() {
    Logger rootLogger = (Logger) LoggerFactory.getLogger(ROOT_LOGGER);

    LoggerContext context = (LoggerContext) org.slf4j.LoggerFactory.getILoggerFactory();

    rootLogger.detachAndStopAllAppenders();

    ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();

    PatternLayoutEncoder consolePatternLayoutEncoder = new PatternLayoutEncoder();
    consolePatternLayoutEncoder.setPattern("%msg%n");
    consolePatternLayoutEncoder.setContext(context);
    consolePatternLayoutEncoder.start();

    consoleAppender.setEncoder(consolePatternLayoutEncoder);
    consoleAppender.start();

    rootLogger.addAppender(consoleAppender);

    ((Logger) LoggerFactory.getLogger("uk.org.lidalia")).setLevel(Level.ERROR);
    ((Logger) LoggerFactory.getLogger("org.nd4j")).setLevel(Level.ERROR);
    ((Logger) LoggerFactory.getLogger("org")).setLevel(Level.ERROR);
    ((Logger) LoggerFactory.getLogger("io")).setLevel(Level.ERROR);

    ((Logger) LoggerFactory.getLogger("ai")).setLevel(Level.INFO);
}
 
Example 15
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 16
Source File: ITestUtils.java    From pom-manipulation-ext with Apache License 2.0 4 votes vote down vote up
/**
 * Run pom-manipulation-cli via run() with java params (-D arguments) in workingDir directory.
 *
 * @param args - List of additional command line arguments
 * @param params - Map of String keys and String values representing -D arguments
 * @param workingDir - Working directory in which you want the cli to be run.
 * @return Exit value
 */
static Integer runCli( List<String> args, Map<String, String> params, String workingDir )
{
    ArrayList<String> arguments = new ArrayList<>( args );
    Collections.addAll( arguments, toJavaParams( params ).split( "\\s+" ) );
    boolean argsContainsFile = false;
    for ( String s : args)
    {
        if ( s.startsWith( "--file" ) )
        {
            argsContainsFile = true;
            break;
        }
    }
    if ( ! argsContainsFile )
    {
        arguments.add( "--log=" + workingDir + File.separator + "build.log" );
        arguments.add( "--file=" + workingDir + File.separator + "pom.xml" );
    }
    logger.info( "Invoking CLI with {} ", arguments );
    Cli cli = new Cli();
    int result = cli.run( arguments.toArray( new String[0] ) );

    // Close unirest client down to prevent any hanging.
    // Unirest.shutdown();

    // This is a bit of a hack. The CLI, if log-to-file is enabled resets the logging. As we don't fork and run
    // in the same process this means we need to reset it back again. The benefit of not forking is a simpler test
    // harness and it saves time when running the tests.
    final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger( org.slf4j.Logger.ROOT_LOGGER_NAME );

    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    loggerContext.reset();

    PatternLayoutEncoder ple = new PatternLayoutEncoder();
    ple.setPattern( "[%t] %level %logger{32} - %msg%n" );
    ple.setContext( loggerContext );
    ple.start();

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

    root.addAppender( consoleAppender );
    root.setLevel( Level.DEBUG );

    return result;
}
 
Example 17
Source File: BitherApplication.java    From bither-android with Apache License 2.0 4 votes vote down vote up
private void initLogging() {
    final File logDir = getLogDir();
    final File logFile = new File(logDir, "bitherj.log");
    final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    final PatternLayoutEncoder filePattern = new PatternLayoutEncoder();
    filePattern.setContext(context);
    filePattern.setPattern("%d{HH:mm:ss.SSS} [%thread] %logger{0} - %msg%n");
    filePattern.start();

    final RollingFileAppender<ILoggingEvent> fileAppender = new
            RollingFileAppender<ILoggingEvent>();
    fileAppender.setContext(context);
    fileAppender.setFile(logFile.getAbsolutePath());

    final TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new
            TimeBasedRollingPolicy<ILoggingEvent>();
    rollingPolicy.setContext(context);
    rollingPolicy.setParent(fileAppender);
    rollingPolicy.setFileNamePattern(logDir.getAbsolutePath() + "/bitherj.%d.log.gz");
    rollingPolicy.setMaxHistory(7);
    rollingPolicy.start();

    fileAppender.setEncoder(filePattern);
    fileAppender.setRollingPolicy(rollingPolicy);
    fileAppender.start();

    final PatternLayoutEncoder logcatTagPattern = new PatternLayoutEncoder();
    logcatTagPattern.setContext(context);
    logcatTagPattern.setPattern("%logger{0}");
    logcatTagPattern.start();

    final PatternLayoutEncoder logcatPattern = new PatternLayoutEncoder();
    logcatPattern.setContext(context);
    logcatPattern.setPattern("[%thread] %msg%n");
    logcatPattern.start();

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

    final ch.qos.logback.classic.Logger log = context.getLogger(Logger.ROOT_LOGGER_NAME);
    log.addAppender(fileAppender);
    log.addAppender(logcatAppender);
    log.setLevel(Level.INFO);
}
 
Example 18
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 19
Source File: AthenaAuditLoggerConfiguration.java    From cerberus with Apache License 2.0 4 votes vote down vote up
@Autowired
public AthenaAuditLoggerConfiguration(
    @Value("${cerberus.audit.athena.log.path:#{null}}") String logPath,
    AuditLogsS3TimeBasedRollingPolicy<ILoggingEvent> auditLogsS3TimeBasedRollingPolicy) {

  if (StringUtils.isBlank(logPath)) {
    logPath = "";
  } else if (!logPath.endsWith("/")) {
    logPath += "/";
    FilenameUtils.getPath(
        logPath); // this shouldn't be necessary because the path is provided by Spring config,
    // but extra safety
  }
  this.auditLogsS3TimeBasedRollingPolicy = auditLogsS3TimeBasedRollingPolicy;

  LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
  PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder();
  patternLayoutEncoder.setPattern(MESSAGE_PATTERN);
  patternLayoutEncoder.setContext(loggerContext);
  patternLayoutEncoder.start();

  String hostname;
  try {
    hostname =
        System.getenv("HOSTNAME") != null
            ? System.getenv("HOSTNAME")
            : InetAddress.getLocalHost().getHostName();
  } catch (UnknownHostException e) {
    throw new RuntimeException("Unable to find host name");
  }

  FiveMinuteRollingFileAppender<ILoggingEvent> fiveMinuteRollingFileAppender =
      new FiveMinuteRollingFileAppender<>();
  fiveMinuteRollingFileAppender.setName(ATHENA_LOG_APPENDER_NAME);
  fiveMinuteRollingFileAppender.setContext(loggerContext);
  fiveMinuteRollingFileAppender.setFile(logPath + hostname + "-audit.log");
  fiveMinuteRollingFileAppender.setEncoder(patternLayoutEncoder);

  this.auditLogsS3TimeBasedRollingPolicy.setContext(loggerContext);
  this.auditLogsS3TimeBasedRollingPolicy.setFileNamePattern(
      logPath + hostname + "-audit.%d{yyyy-MM-dd_HH-mm, UTC}.log.gz");
  this.auditLogsS3TimeBasedRollingPolicy.setMaxHistory(100);
  this.auditLogsS3TimeBasedRollingPolicy.setParent(fiveMinuteRollingFileAppender);
  this.auditLogsS3TimeBasedRollingPolicy.setTotalSizeCap(FileSize.valueOf("10gb"));

  fiveMinuteRollingFileAppender.setTriggeringPolicy(this.auditLogsS3TimeBasedRollingPolicy);
  fiveMinuteRollingFileAppender.setRollingPolicy(this.auditLogsS3TimeBasedRollingPolicy);

  this.auditLogsS3TimeBasedRollingPolicy.start();
  fiveMinuteRollingFileAppender.start();

  var logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ATHENA_AUDIT_LOGGER_NAME);
  logger.addAppender(fiveMinuteRollingFileAppender);
  logger.setLevel(Level.INFO);
  logger.setAdditive(false);
  athenaAuditLogger = logger;
}
 
Example 20
Source File: Logger.java    From metrics_publish_java with MIT License 4 votes vote down vote up
/**
 * Initialize Logback
 */
private static void initLogback() {
    // reset logger context
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.reset();
    
    // shared console appender
    ConsoleAppender.setContext(context);
    ConsoleAppender.setTarget("System.out");
    
    PatternLayoutEncoder consoleEncoder = new PatternLayoutEncoder();
    consoleEncoder.setContext(context);
    consoleEncoder.setPattern(LogPattern);
    consoleEncoder.start();
    ConsoleAppender.setEncoder(consoleEncoder);
    ConsoleAppender.start();
    
    // rolling file
    String logFile = getFilePath() + File.separatorChar + getFileName();
    FileAppender.setContext(context);
    FileAppender.setFile(logFile);
    
    // log pattern
    PatternLayoutEncoder fileEncoder = new PatternLayoutEncoder();
    fileEncoder.setContext(context);
    fileEncoder.setPattern(LogPattern);
    fileEncoder.start();
    FileAppender.setEncoder(fileEncoder);
    
    // rolling policy
    FixedWindowRollingPolicy rollingPolicy = new FixedWindowRollingPolicy();
    rollingPolicy.setContext(context);
    rollingPolicy.setParent(FileAppender);
    rollingPolicy.setFileNamePattern(logFile + "%i.zip");
    rollingPolicy.setMinIndex(1);
    rollingPolicy.setMaxIndex(1);
    rollingPolicy.start();
    
    // file max size - if fileLimit is 0, set max file size to maximum allowed
    long fileLimit = getFileLimitInKBytes() != 0 ? getFileLimitInKBytes() * 1024 : Long.MAX_VALUE;
    SizeBasedTriggeringPolicy<ILoggingEvent> triggeringPolicy = new SizeBasedTriggeringPolicy<ILoggingEvent>(String.valueOf(fileLimit));
    triggeringPolicy.start();
    
    FileAppender.setRollingPolicy(rollingPolicy);
    FileAppender.setTriggeringPolicy(triggeringPolicy);
    FileAppender.start();
}