如何在java中将log4j添加到Web应用程序中

时间:2016-02-27 04:05:03

标签: java maven glassfish log4j

我正在尝试将log4j添加到我的Web应用程序以记录服务器和客户端之间的交换,因此我在pom.xml中添加了依赖项:

  <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

我创建了log4j.proporties:

  # Root logger option
  log4j.rootLogger=INFO, file

  # Direct log messages to a log file
  log4j.appender.file=org.apache.log4j.RollingFileAppender

  #Redirect to Tomcat logs folder
  #log4j.appender.file.File=${catalina.home}/logs/logging.log

   log4j.appender.file.File=C:\\test.log
   log4j.appender.file.MaxFileSize=10MB
   log4j.appender.file.MaxBackupIndex=10
   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%

以下是我的代码:

  static final Logger logger = Logger.getLogger(hellologger.class); 
public static void main(String[] args) {  
 String log4JPropertyFile = "C:\\Users\\xxxx\\Desktop\\log4j.properties";
Properties p = new Properties();

   try {
       p.load(new FileInputStream(log4JPropertyFile));
       PropertyConfigurator.configure(p);
      logger.info("Wow! I'm configured!");
    } catch (IOException e) {


     }
    }

但最后我收到了这个错误:

   Infos:   org.osgi.framework.BundleException: Unresolved constraint in bundle com.mycompany.webclient [329]: Unable to resolve 329.7: missing requirement [329.7] osgi.wiring.package; (&(osgi.wiring.package=org.apache.log4j)(version>=1.2.0)(!(version>=2.0.0)))
at org.apache.felix.framework.Felix.resolveBundleRevision(Felix.java:3974)
at org.apache.felix.framework.Felix.startBundle(Felix.java:2037)
at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:955)
at org.apache.felix.fileinstall.internal.DirectoryWatcher.process(DirectoryWatcher.java:1175)
at org.apache.felix.fileinstall.internal.DirectoryWatcher.process(DirectoryWatcher.java:1153)
at org.apache.felix.fileinstall.internal.DirectoryWatcher.processAllBundles(DirectoryWatcher.java:1146)
at org.apache.felix.fileinstall.internal.DirectoryWatcher.process(DirectoryWatcher.java:456)
at org.apache.felix.fileinstall.internal.DirectoryWatcher.run(DirectoryWatcher.java:263)

任何想法如何解决这个问题?!!!!

1 个答案:

答案 0 :(得分:0)

您可以浏览log4j上的this教程。

正确解释了属性文件和pom.xml文件。

生成的日志如下:

2014-07-02 20:52:39 DEBUG HelloExample:19 - This is debug : mkyong
2014-07-02 20:52:39 INFO  HelloExample:23 - This is info : mkyong
2014-07-02 20:52:39 WARN  HelloExample:26 - This is warn : mkyong
2014-07-02 20:52:39 ERROR HelloExample:27 - This is error : mkyong
2014-07-02 20:52:39 FATAL HelloExample:28 - This is fatal : mkyong