我有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以每天创建新文件并将消息写入文件?
答案 0 :(得分:5)
使用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");