The following 3 posts offer answers for how to use an intermediate logging helper and still get the underlying logger to report from the method of a client to that logging helper (rather than reporting the logging helper method as the source):
Java Logging: show the source line number of the caller (not the logging helper method)
Calling log4j's log methods indirectly (from a helper method)
Printing the "source" class in a log statement with a log4j wrapper
But the seem to only offer answers for Log4j 1.2, which offers the now-defunct:
Category.log(String callerFQCN, Priority level, Object message, Throwable t).
There does not seem to be an obvious equivalent for Logger in the log4J 2.5 API.
Can anybody offer an answer compatible with direct use of Log4J 2.x ?
If you are building a new system, stick with Webel's answer.
If you have an existing system you are migrating to log4j2, you should still probably run the generate methods (but I include a minimal working class below), and you can add this function which provides the old 1.2 callerFQCN way of doing things (sort of):
Then, from your existing log-wrapping classes, you can do something like this:
I happened to delete a bunch of other generated functions I am not using, since I planned to do a simple shim for a poorly designed (custom) logging system. I deleted a bunch of create() methods I didn't plan to use. So here is a working class (the parts worth sharing):
I should note that I consider this a shim--it's something to get you by, but I would strongly recommend continuing to move away from the old logging system once you have the shim in place. This will let you do more incremental code changes without having to accomplish a full migration right away.
For Log4j2 the answer is provided completely by the use of logger wrappers as described in the Log4j2 manual under Example Usage of a Generated Logger Wrapper. One can simply generate (using the org.apache.logging.log4j.core.tools.Generate$ExtendedLogger tools illustrated there) a logger wrapper with a single STUB level, and then adapt that to create custom logging methods mimicking the use of the logIfEnabled(FQCN, LEVEL, Marker, message, Throwable) - possibly ignoring the STUB level and using the regular ones - then if desired, deleting or commenting out the STUB level and its methods). For this purpose the FormattedMessage can be helpful.
Example:
Then adapt the generated class (most support methods omitted):
Then in a client class it will now log "on behalf" of that client correctly via the logger's helper methods, in this case the formatting example echo(name,value):
Simple PatternLayout:
Output:
Once you've got the hang of using logger.logIfEnabled(FQCN,...) with the FQCN (which log4j searches for in the stack trace) you may wish to delete or comment out the stub(..) methods and STUB level if you don't use an additional level.