2016-12-30 84 views
1

我做了一个简单的类,并尝试使用Logger类方法打印日志消息,并使用FileAppender将日志消息附加到文件中。 但是,日志不会打印在文件中。使用log4j时没有得到预期的输出

任何人都可以指导我如何使用我制作的程序在文件中打印这些日志。 我用在类路径的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

你有log4j.properties或log4j.xml文件在你的类路径附加器为您的类和包? – SMA

+0

不,我没有使用.properties或xml,但我用一个简单的java类来拥有appender和布局对象。 – user6389648

回答

2

的log4j:警告没有附加目的地可以为记录器(客户端)中找到。 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 

,因为你尝试登录之前该文件的appender被添加到配置你有这个问题。如何在没有任何appender的情况下登录?

测井作业之前,所以拉升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

只需我创建了一些Util类s来初始化日志配置;

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."); 
} 
相关问题