【问题标题】:Not getting expected output while using log4j使用 log4j 时没有得到预期的输出
【发布时间】:2016-12-30 15:33:37
【问题描述】:

我创建了一个简单的类并尝试使用 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

【问题讨论】:

  • 您的类路径中是否有 log4j.properties 或 log4j.xml 以及您的类和包的附加程序?
  • 不,我没有使用 .properties 或 xml,但我使用了一个简单的 java 类来拥有 appender 和 layout 对象。

标签: java log4j


【解决方案1】:

log4j:WARN 找不到记录器(客户端)的附加程序。 log4j:警告 请正确初始化log4j系统。 log4j:警告

    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 的情况下登录?

所以在记录操作之前向上移动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");

【讨论】:

    【解决方案2】:

    我创建了一些 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.");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-06
      • 2020-09-01
      • 2017-01-30
      • 1970-01-01
      • 2019-09-16
      相关资源
      最近更新 更多