如何在所有类中访问log4j属性?

时间:2013-11-21 08:55:03

标签: java log4j

我在我的应用程序中使用log4j。现在我已经创建了属性文件。如何在所有Java类中访问此属性文件。有人可以解释一下吗?

# Root logger option
log4j.rootLogger=INFO, file, stdout
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=${rootPath}WEB-INF/logs/MyLog.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

3 个答案:

答案 0 :(得分:0)

import org.apache.log4j.Logger;

import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class log4jExample{
  /* Get actual class name to be printed on */
  static Logger log = Logger.getLogger(
                      log4jExample.class.getName());

  public static void main(String[] args)
                throws IOException,SQLException{

     log.debug("Hello this is an debug message");
     log.info("Hello this is an info message");
  }
}

答案 1 :(得分:0)

如果您尚未添加

,请尝试将其添加到您的web.xml
    <context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>./conf/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<!-- Refresh log4j configuration every 5 minutes. -->
<param-value>300000</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

答案 2 :(得分:0)

检查catalina.log是否有任何错误。确保正确初始化log4j。如果你有multilpe log4j jar文件(一个在你的上下文中,另一个在tomcat / lib中),它可能没有正确初始化。尝试删除重复的罐子