jacek99/structlog4j

Wrong logger name when used with Log4j 2 as SLF4J backend

solsson opened this issue · 8 comments

I experimented with different backens, and noticed that with org.apache.logging.log4j.log4j-slf4j-impl the logged class name is com.github.structlog4j.SLoggerFactory instead of the actual class that created the logger. If I switch to logback or slf4j-simple I get the proper logger name again.

This was in Eclipse, Log4j version 2.10.0, and I tend to initialize loggers this way:

private final ILogger log = SLoggerFactory.getLogger(this.getClass());

Interesting. I will try to look at it today and get back to you.

I looked at the code and we are doing the right thing in SLogger

SLogger(String name) {
    slfjLogger = LoggerFactory.getLogger(name);
}

SLogger(Class<?> source) {
    slfjLogger = LoggerFactory.getLogger(source);

The actual SFL4J logger is created correctly passing in the source class you sent to us :-/

I suspect this is some log4j bug, maybe via reflection they try to get the name of the actual logger on a class or something. The fact it works perfectly with logback AND slf4j-simple indicates the issue the issue is somewhere on the log4j side.

Will try over the weekend to set up a test project with log4j and try to figure out what they do. At least maybe we can have a more meaningful ticket to raise with them.

Ok. It sounds like you could confirm that this happens. I agree it sounds like an oddity with log4j-slf4j-impl. Logback gets the right names too.

Hey @solsson,
I guess this is happening because u use this.class. The slf4j manual page states that one should use (chapter Typical usage patterns):

public class Wombat {
    final Logger logger = LoggerFactory.getLogger(Wombat.class);
}

Notice the explicit classname Wombat in the call to getLogger(). Can you try this out? Maybe this helps.

Yes, sorry, did not have a chance to look at this week due to other duties...let me know if the suggestion above helps.

@CodeLionX Good, I got curious if I had been wrong all the time assuming that Wombat.class == this.getClass(), so I set up a repo to try to reproduce this issue. I failed :) I also failed to spot any difference with this.getClass() which means I'll continue to use it to avoid confusions caused by careless copy paste.

I probably need to try with all the dependencies of the project where I stumbled upon this oddity, but until then I'll close this issue.

Thanks for figuring out! I wasn't sure about Wombat.class == this.getClass() as well. But I thought they had a reason to write their manual like that...

Yep, every logging lib is very consistent about that. I always thought it's because they recommend loggers to be declared static. I do so occasionally, for classes that are instantiated a lot.