Redirect java.util.logging to log4j

2.9k Views Asked by At

I'm using an external JAR library that creates a log file every time is used:

   private void initLogger() {
        try {
            boolean var1 = true;
            FileHandler var2 = new FileHandler("lib.log", 4096000, 1, var1);
            var2.setFormatter(new SimpleFormatter());
            this.logger = Logger.getLogger("POS");
            this.logger.addHandler(var2);
        } catch (IOException var3) {
            var3.printStackTrace();
        }
    }

This, create the files lib.log , lib.log.lck, etc...

The problem is that my App is using log4j(from maven xml):

<!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

What I want is simple, I want to redirect all the calls of that lib log to my logger.

I've tried using jul-to-slf4j :

https://www.slf4j.org/legacy.html

<!-- https://mvnrepository.com/artifact/org.slf4j/jul-to-slf4j -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jul-to-slf4j</artifactId>
    <version>1.7.25</version>
</dependency>

With this configuration (console + daily file):

# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1, RollingAppender
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%-5p] %d %c - %m%n

log4j.appender.RollingAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RollingAppender.File=pos.log
log4j.appender.RollingAppender.DatePattern='.'yyyy-MM-dd
log4j.appender.RollingAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.RollingAppender.layout.ConversionPattern=[%-5p] %d %c - %m%n

And then put this code at the beginning:

    LogManager.getLogManager().reset();
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
    Logger.getLogger("POS").setLevel(FINEST);

With this, the file is created (lib.log) but it's empty. And the output doesn't go to pos.log ( the one configured in log4j).

What I'm missing? Thanks!

1

There are 1 best solutions below

0
On

You did not include slf4j-log4j12 in your project (more).

Maybe Log4j JDK Logging Adapter is better solution.