logback日志pattern_Logback - 以编程方式设置日志文件名

I am using logback, and I am trying to set the log file name programmatically within my Java program (similar to Setting Logback Appender path programmatically), and I tried to adapt that solution as follows:

In logback-test.xml:

log/${log_file_name}.log

...

And then again in my Java program:

String logFileName = "" + System.currentTimeMillis(); // just for example

System.setProperty("log_file_name", logFileName);

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

ContextInitializer ci = new ContextInitializer(lc);

lc.reset();

try

{

// I prefer autoConfig() over JoranConfigurator.doConfigure() so I

// wouldn't need to find the file myself.

ci.autoConfig();

}

catch (JoranException e)

{

// StatusPrinter will try to log this

e.printStackTrace();

}

StatusPrinter.printInCaseOfErrorsOrWarnings(lc);

However the result is two logs, one full and named as I wanted, e.g., "1319041145343.log", and the other is empty and named "log_file_name_IS_UNDEFINED.log". How do I stop this other empty log file from being created?

解决方案

I believe the following to be closer to what you want.

import ch.qos.logback.classic.Logger;

import ch.qos.logback.classic.encoder.PatternLayoutEncoder;

import ch.qos.logback.core.FileAppender;

import ch.qos.logback.core.util.StatusPrinter;

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.LoggerContext;

public class Main {

public static void main(String[] args) {

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

FileAppender fileAppender = new FileAppender();

fileAppender.setContext(loggerContext);

fileAppender.setName("timestamp");

// set the file name

fileAppender.setFile("log/" + System.currentTimeMillis()+".log");

PatternLayoutEncoder encoder = new PatternLayoutEncoder();

encoder.setContext(loggerContext);

encoder.setPattern("%r %thread %level - %msg%n");

encoder.start();

fileAppender.setEncoder(encoder);

fileAppender.start();

// attach the rolling file appender to the logger of your choice

Logger logbackLogger = loggerContext.getLogger("Main");

logbackLogger.addAppender(fileAppender);

// OPTIONAL: print logback internal status messages

StatusPrinter.print(loggerContext);

// log something

logbackLogger.debug("hello");

}

}

If all you need is to add a timestamp of the log file name, logback already supports the timestamp element. Thus, you actually don't need any custom code at all.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值