我使用log4j获取异常消息

时间:2013-12-21 08:53:34

标签: java exception log4j

我正在使用log4j将错误记录到文件中,但是,当我运行程序时,我一直收到以下错误,虽然日志文件被创建并且错误记录在文件中,但只有当我退出时程序

错误

log4j:ERROR Could not read configuration file [log4j.properties].
java.io.FileNotFoundException: log4j.properties (No such file or directory)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:131)
    at java.io.FileInputStream.<init>(FileInputStream.java:87)
    at org.apache.log4j.PropertyConfigurator.doConfigure(PropertyConfigurator.java:372)
    at org.apache.log4j.PropertyConfigurator.configure(PropertyConfigurator.java:403)
    at javafxapplication4.JavaFXApplication4.init(JavaFXApplication4.java:227)
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:788)
    at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:56)
    at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:158)
    at java.lang.Thread.run(Thread.java:724)
log4j:ERROR Ignoring configuration file [log4j.properties].

代码:

PropertyConfigurator.configure("log4j.properties");
...
catch(SQLException e)
                {
                    System.out.println("Error on Database connection");
                    System.out.print(e.getMessage());
                    logger.error("Your log message", e);
                }

配置文件:

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.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=/log/example.log

log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1

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

enter image description here

2 个答案:

答案 0 :(得分:1)

那是因为在类路径中找不到log4j.properties文件,要么在classpath中包含它的文件夹,要么提供绝对路径。

答案 1 :(得分:0)

您甚至不需要设置log4j.properties文件。如果它位于根文件夹中,Log4j会自动找到它。