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

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);

}

Is there any other way to log the errors or exception? can any body provide me wwith sample example of 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

}

....

}

....

}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值