将日志写入文件java.util.logging.Logger

时间:2015-07-15 05:20:40

标签: java logging appender

需要使用 util.logging.logger 日志写入文件的代码(配置文件)。它还应该将日志附加到同一项目的其他类中的文件中。

我知道如何在log4j中执行此操作,但我需要在util.logging.logger中使用它。请帮忙。

log4j文件

# Set root logger level to DEBUG and its only appender to Appender1.
log4j.rootLogger=info,dailyRoll,console

# Appender1 is set to be a ConsoleAppender.
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%-10d %-4r [%t] %-5p %c %x - %m%n

# Appender2 uses PatternLayout.
log4j.appender.fileAppender=org.apache.log4j.RollingFileAppender    
log4j.appender.fileAppender.file=/home/Application.log
log4j.appender.fileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.fileAppender.layout.ConversionPattern=%-10d %-4r [%t] %-5p %c %x - %m%n

# Appender3 uses PatternLayout.
log4j.appender.dailyRoll=org.apache.log4j.DailyRollingFileAppender
log4j.appender.dailyRoll.file=/home/cms/MyFiles/EJBJob/CMS_log/Application.log
log4j.appender.dailyRoll.DatePattern=.yyyy-MM-dd
log4j.appender.dailyRoll.Append=true
log4j.appender.dailyRoll.layout=org.apache.log4j.PatternLayout
log4j.appender.dailyRoll.layout.ConversionPattern=%-10d %-4r [%t] %-5p %c %x - %m%n

我需要在日志记录中使用类似于上面的配置文件 (log4j.appender.dailyRoll.file = /家庭/ CMS / MYFILES / EJBJob / CMS_log / Application.log)

2 个答案:

答案 0 :(得分:2)

尝试使用此代码:

import java.util.logging

// create an instance of Logger at the top of the file, as you would do with log4j
private static final Logger log = Logger.getLogger( ClassName.class.getName() );
FileHandler fh = new FileHandler("your_log.txt", true);   // true forces append mode
SimpleFormatter sf = new SimpleFormatter();
fh.setFormatter(sf);
log.addHandler(fh);

// java.util.logging has several logging levels from which to choose; here are two:
log.log( Level.FINE, "A FINE logging message goes here.");
log.log( Level.SEVERE, "A SEVERE logging message goes here.");

答案 1 :(得分:0)

我认为你正在寻找这个属性

java.util.logging.FileHandler.append
  

设置在找到现有日志文件时,FileHandler是否应附加到现有文件(true或false)。

请看看这个link