21

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

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

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

4

6 回答 6

36

首先阅读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 手册

于 2012-02-20T14:26:14.100 回答
4

使用log4j您可以很容易地记录异常:

try {
    ...
} catch(Exception e) {
    log.error("An exception! Oops!", e);
}
于 2012-02-20T14:18:07.740 回答
4

您可以将异常作为参数添加到 log4j 语句中,例如

catch(Exception e)
{
    logger.error("Unexpected error", e);
}

如果你有一个运行正常的文件附加程序,这将输出异常的完整堆栈跟踪。

于 2012-02-20T14:19:34.590 回答
3
try {
       System.setErr(new PrintStream(new FileOutputStream(System.getProperty("user.home")+"/error.log")));
} catch (FileNotFoundException ex) {
        ex.printStackTrace();
}

现在所有错误输出都写入此文件

于 2012-02-20T14:18:48.223 回答
1

看这个关于“文件附加器”的教程

请参阅官方 Log4j 简短介绍和“配置”部分。

您还可以搜索“RollingFileAppender”或“File appender”。

您将记录器配置为将其消息发送到附加程序。此附加程序可以将消息转发到控制台(stdin),转发到文件(FileAppender,RollingFileAppender ...)......

使用它来执行错误日志:

try{
    throw new Exception("bla bla bla...");
} catch( Exception e ){
     // log without stack trace
     mLogger.error("Your log message");

     // log with stack trace
     mLogger.error("Your log message", e);
}
于 2012-02-20T14:25:03.193 回答
0

您可以使用 log4j 依赖项记录数据。去这个链接

https://logging.apache.org/log4j/2.x/manual/configuration.html
Pom dependency ==>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.2</version>
</dependency>

Properties File eg ==>

status = error
dest = err
name = PropertiesConfig

property.filename = target/rolling/rollingtest.log

filter.threshold.type = ThresholdFilter
filter.threshold.level = debug

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %m%n
appender.console.filter.threshold.type = ThresholdFilter
appender.console.filter.threshold.level = error

appender.rolling.type = RollingFile
appender.rolling.name = RollingFile
appender.rolling.fileName = ${filename}
appender.rolling.filePattern = target/rolling2/test1-%d{MM-dd-yy-HH-mm-ss}- 
%i.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d %p %C{1.} [%t] %m%n
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 2
appender.rolling.policies.time.modulate = true
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=100MB
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = 5

logger.rolling.name = com.example.my.app //  Change this to your own package 
name otherwise will not work
logger.rolling.level = debug
logger.rolling.additivity = false
logger.rolling.appenderRef.rolling.ref = RollingFile

rootLogger.level = info
rootLogger.appenderRef.stdout.ref = STDOUT

Java code ==>
private static final Logger logger = 
LogManager.getLogger(MyClass.class.getName());
logger.info("Entering application.");
logger.trace("Entering application.");
logger.debug("Debugg application.");
logger.error("Did it again!");
于 2019-03-05T12:27:09.530 回答