How do I configure log4j to send log events to jav

2019-02-26 10:51发布

I am familiar with the java.util.logging (JUL) framework, I use it extensively. Recently, I started using a library that does its logging through log4j. When I start my application I now get the following printed on the console:

log4j:WARN No appenders could be found for logger (com.example.thirdparty.Library).
log4j:WARN Please initialize the log4j system properly.

It appears that log4j has a solution for this: JULAppender which will send everything logged with log4j to the logging framework that I use.

I can't find any examples that show me how to configure log4j to use this appender.

2条回答
祖国的老花朵
2楼-- · 2019-02-26 11:26

The implementation of JULAppender (which, btw, is available for download here), is very old now (from 2008), and targets JDK 1.4 and log4j version 1.2.15.

If you work with log4j version 2.0 (and above), an easy solution would be to have all messages logged with log4j's SLF4J appender, which, in turn, is set to use java.util.logging as its underlying implementation.

If you use maven simply include the following in your <dependencies> paragraph:

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-to-slf4j</artifactId>
    <version>2.0</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-jdk14</artifactId>
    <version>1.7.7</version>
</dependency>

If you don't use maven add the following 3 jars to your classpath (in addition to log4j-api-2.0.jar):

查看更多
Summer. ? 凉城
3楼-- · 2019-02-26 11:32

The standard way of configuring log4j is to create log4j.xml in the root of the classpath. Here are contents of that file configured for JULAppender:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="jul" class="org.apache.log4j.JulAppender"> 
        <layout class="org.apache.log4j.PatternLayout"> 
            <param name="ConversionPattern" value="%d %-5p %c - %m%n "/> 
        </layout> 
    </appender> 
    <root> 
        <priority value="all" /> 
        <appender-ref ref="jul" /> 
    </root>  
</log4j:configuration>
查看更多
登录 后发表回答