如何在Java中将错误日志或异常写入文件 [英] How to write error log or exception into file in java

查看:1410
本文介绍了如何在Java中将错误日志或异常写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以将错误日志或异常写入Java文件中.我已经通过Log4j.我用谷歌搜索,但是努力找到了一个很好的解决方案.我写了一个简单的代码

Is there any way to write error log or exception into a file in java. i have gone through Log4j. I googled about it but diidnt find a good solution. I have written a simple code

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

还有其他方法可以记录错误或异常吗?谁能为我提供Log4j的示例示例?

Is there any other way to log the errors or exception? can any body provide me wwith sample example of Log4j?

推荐答案

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

First read log4j Manual, it's easy to configure a rolling log file. You do not have to do any explicit file operations.

#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

第二,每当您遇到异常时,都要做这样的事情

Second, whenever you catch an exception, do like this

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手册

It worth reading the manual. Even better read Complete log4j Manual

这篇关于如何在Java中将错误日志或异常写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆