gpt4 book ai didi

java - 配置 Log4J 每天写入新文件新日志文件

转载 作者:行者123 更新时间:2023-11-30 06:21:17 28 4
gpt4 key购买 nike

我有这个 Log4J 的基本配置:

Logger log = Logger.getLogger(LogMessages.class.getName());
BasicConfigurator.configure(); // Basic configuration for Log4J 1.x

ConsoleAppender console = new ConsoleAppender(); //create appender
//configure the appender
String PATTERN = "%d [%p|%c|%C{1}] %m%n";
console.setLayout(new PatternLayout(PATTERN));
console.setThreshold(Level.FATAL);
console.activateOptions();
//add appender to any Logger (here is root)
Logger.getRootLogger().addAppender(console);

FileAppender fa = new FileAppender();
fa.setName("FileLogger");
fa.setFile("log" + File.separator + "messages.log");
fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
fa.setThreshold(Level.DEBUG);
fa.setAppend(true);
fa.activateOptions();

//add appender to any Logger (here is root)
Logger.getRootLogger().addAppender(fa); //repeat with all other desired appenders

// BASIC TEST
log.info("Some message 1");
log.info("Some message 2");
log.info("Some message 3");
log.info("Some message 4");

如何配置 Log4J 每天创建一个新文件并将消息写入文件?

最佳答案

使用 org.apache.log4j.DailyRollingFileAppender 而不是 FileAppender

可以找到有关设置的详细信息here .

编辑

    PatternLayout layout = new PatternLayout();
String conversionPattern = "[%p] %d %c %M - %m%n";
layout.setConversionPattern(conversionPattern);

// creates daily rolling file appender
DailyRollingFileAppender rollingAppender = new DailyRollingFileAppender();
rollingAppender.setFile("app.log");
rollingAppender.setDatePattern("'.'yyyy-MM-dd");
rollingAppender.setLayout(layout);
rollingAppender.activateOptions();

// configures the root logger
Logger rootLogger = Logger.getRootLogger();
rootLogger.setLevel(Level.DEBUG);
rootLogger.addAppender(rollingAppender);

// creates a custom logger and log messages
Logger logger = Logger.getLogger(My.class);

logger.debug("this is a debug log message");
logger.info("this is a information log message");
logger.warn("this is a warning log message");

关于java - 配置 Log4J 每天写入新文件新日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20759747/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com