如何将错误日志或异常写入java中的文件

2022-09-02 02:49:48

有没有办法将错误日志或异常写入java文件中。我已经通过Log4j。我用谷歌搜索了它,但找不到一个好的解决方案。我写了一个简单的代码

catch (Exception e) {
    PrintWriter pw = new PrintWriter(new FileOutputStream("Log"));     
    e.printStackTrace(pw);
} 

有没有其他方法可以记录错误或异常?任何机构都可以为我提供Log4j的示例吗?


答案 1

首先阅读log4j手册,很容易配置滚动日志文件。您不必执行任何显式文件操作。

#SET LEVEL of ROOT-LOGGER, you will like to have Debug in local, but in prod you may just want WARN and ABOVE. This setting is done here!
log4j.rootLogger=debug, stdout, R

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number. (basically, format of log)
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

# THIS IS WHERE YOU WILL HAVE ALL THE LOG WRITTEN
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=/var/log/applogs/example.log

# Maximum size of log file, usually we keep 10MB
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file, usually we keep 10
log4j.appender.R.MaxBackupIndex=1

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

其次,每当你发现异常时,都这样做

public class MyClass{

  private static Logger logger = Logger.getLogger(MyClass.class);

  public ReturnType myMethod(Param p, Param2 p2) {
    ....
    ....
    try {
      ..    
    } catch(MyException e) {
       logger.log("Exceptions happen!", e); //this will put all the details in log file configured earlier
    }
    ....
  }

  ....
}

值得一读的手册。更好的阅读 完整的log4j手册


答案 2

使用你可以很容易地记录例外:log4j

try {
    ...
} catch(Exception e) {
    log.error("An exception! Oops!", e);
}

推荐