Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send java.util.logging to log4j2?

I'm working on a project that uses the NetBeans Platform. Under the hood, NetBeans uses the java.util.logging framework.

I would like to intercept these log calls by binding java.util.logging to log4j2. Is this possible?

Previous questions have been asked that are similar, but were specific to log4j and not log4j2!

like image 491
bblincoe Avatar asked Feb 14 '14 13:02

bblincoe


People also ask

Does Java Util logging use Log4j?

The JDK Logging Adapter is a custom implementation of java. util. logging. LogManager that uses Log4j.

What is Java Util logging?

Logging is used to store exceptions, information, and warnings as messages that occur during the execution of a program. Logging helps a programmer in the debugging process of a program. Java provides logging facility in the java. util. logging package.


2 Answers

UPDATE 2014/9/12: From version 2.1, Log4j 2 contain a JUL bridge that does not require SLF4J.

No custom code is required. Two things:

  1. put the following jars in the classpath: log4j-api-2.x, log4j-core-2.x and log4j-jul-2.x.

  2. set the system property java.util.logging.manager to org.apache.logging.log4j.jul.LogManager before any calls are made to LogManager or Logger

The Log4J2 FAQ page shows the dependencies visually: http://logging.apache.org/log4j/2.x/faq.html#which_jars

like image 150
Remko Popma Avatar answered Oct 03 '22 06:10

Remko Popma


I've found a solution:

The NetBeans Platform names logger after the org.netbeans.* namespace. To route NetBeans log calls, I simply created a Handler and registered it with the org.netbeans logger:

public class CustomHandler extends Handler
{
    @Override
    public void publish(LogRecord record)
    {
        // Re-direct log calls here (e.g. send record to Log4j2 logger).
    }

    @Override
    public void flush() 
    {
    }

    @Override
    public void close() throws SecurityException
    {
    }
}

Be sure to register the new Handler and disable parent loggers if necessary:

Logger logger = Logger.getLogger("org.netbeans");
logger.addHandler(new CustomerHandler());
logger.setUseParentHandlers(false);
like image 42
bblincoe Avatar answered Oct 03 '22 05:10

bblincoe