Manjabes
Manjabes

Reputation: 1904

SLF4J parameterized logging using varargs method

I must be stupid or something, but I seem not to be able to use the varargs-utilizing parameterized logging methods of SLF4J. An example:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoggingTest {

    @Test
    public void loggingTest() {
        Logger logger = LoggerFactory.getLogger(this.getClass());
        int x = 0xdeadbeef;
        long y = 0xdeadbeef;
    
        try {
            throw new Exception("This is a mighty exception!");
        } catch(Exception e) {
            logger.error("I wanna log {} and {} and {} with backtrace", x, y, 3, e);
        }
    }
}

On the logging method, eclipse produces such a warning:

The method error(String, Object, Object) in the type Logger is not applicable for the arguments (String, int, long, int, Exception)

and fails to compile.

However, if I change the logging call to:

logger.error("I wanna log {} and {} and {} with backtrace", new Object[]{x, y, 3, e});

It compiles and runs as expected (logging 3 "variables" and the exception stack trace).

The library versions are: slf4j-api-1.7.5.jar, slf4j-log4j12-1.7.5.jar and log4j-1.2.14.jar, if it makes any difference.

If anybody would point out the shortcomings of my thinking abilities, it'd be very much appreciated!

Upvotes: 18

Views: 23333

Answers (1)

ZachOfAllTrades
ZachOfAllTrades

Reputation: 1103

I did some additional investigation, and the only way to get a compile error for

logger.error("I wanna log {} and {} and {} with backtrace", x, y, 3, e);

and not for

logger.error("I wanna log {} and {} and {} with backtrace", new Object[]{x, y, 3, e});

is to use a version of the SLF4J API prior to 1.7 (in which support for varargs was introduced). You probably need to dig into your classpath (or server runtime?) to find where the following statement fails to be true:

The library versions are: slf4j-api-1.7.5.jar, slf4j-log4j12-1.7.5.jar and log4j-1.2.14.jar, if it makes any difference.

(because it certainly makes precisely the difference that you have observed)

Upvotes: 30

Related Questions