我创建了一个简单的类,并尝试使用Logger类方法打印日志消息,并使用FileAppender将日志消息附加到文件中。 但是日志不会打印在文件中。
任何人都可以指导我如何使用我制作的程序在文件中打印这些日志。 我在类路径中使用了log4j-1.2.17 Api:
以下程序的代码:
public class Client {
static Logger l=Logger.getLogger(Client.class.getName());
public static void main(String[] args) {
Layout l1=new SimpleLayout();
Appender a;
try{
a=new FileAppender(l1,"my.txt",true);
l.debug("Hello Jc");
l.info("Hello Jc");
l.fatal("This is not the error message");
l.addAppender(a);
}
catch(Exception e){
}
System.out.println("your logic executed Successfully");
// TODO Auto-generated method stub
}
输出:
log4j:WARN No appenders could be found for logger (Client).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
your logic executed Successfully
文件中的预期输出:
DEBUG Hello Jc
INFO Hello Jc
FATAL This is not the error message
答案 0 :(得分:2)
log4j:WARN找不到记录器(客户端)的appender。 log4j的:WARN 请正确初始化log4j系统。的log4j:WARN
a = new FileAppender(l1,"my.txt",true);
l.debug("Hello Jc");
l.info("Hello Jc");
l.fatal("This is not the error message");
l.addAppender(a); // too late
您遇到此问题是因为您尝试在将文件追加程序添加到配置之前进行记录。如何在没有任何助手的情况下登录?
所以在记录操作之前向上移动l.addAppender(a)
:
a = new FileAppender(l1,"my.txt",true);
l.addAppender(a); // appender is added, you can log
l.debug("Hello Jc");
l.info("Hello Jc");
l.fatal("This is not the error message");
答案 1 :(得分:1)
我已经创建了一些Util类来初始化日志配置;
public static void initLogger() {
try {
String filePath = "D:/my.log";
PatternLayout layout = new PatternLayout("%-5p %d %m%n");
RollingFileAppender appender = new RollingFileAppender(layout, filePath);
appender.setName("log");
appender.setMaxFileSize("10MB");
appender.activateOptions();
Logger.getRootLogger().addAppender(appender);
} catch (IOException e) {
e.printStackTrace();
}
}
然后我调用此方法并成功写入文件;
public static void main(String[] args) {
LoggerUtil.initLogger();
Logger accessLog = Logger.getLogger("log");
accessLog.info("This is info message.");
accessLog.warn("This is warn message.");
accessLog.error("This is error message.");
accessLog.fatal("This is fatal message.");
}