The numerous (sigh...) logging frameworks for Java all do a nice job of showing the line number of the source file name for the method that created the log message:
log.info("hey");
[INFO] [Foo:413] hey
But if have a helper method in between, the actual caller will be the helper method, and that is not too informative.
log_info("hey");
[INFO] [LoggingSupport:123] hey
Is there a way to tell the logging system to remove one frame from the callstack when figuring out the source location to print?
I suppose that this is implementation specific; what I need is Log4J via Commons Logging, but I am interested to hear about other options.
Maybe you can implement the log helper function using the stack trace element, get the line numbers, and bypass the frames with method with some specific annotations, like,
Thus, if the helper function is nested, or there are more utilized helper functions, just mark the SkipFrame annotation on all of them and you will get the correct source line number what you really wanted.
Alternative answer.
It is possible to ask log4j to exclude the helper class by using the method
Category.log(String callerFQCN, Priority level, Object message, Throwable t)
and specifying the helper class as 'callerFQCN'.
For example here is a class using a helper:
and the code of the helper:
The first method will output your expected result.
When using this method, Log4j will work as usual, avoiding calculating the stack trace if it is not required.
Please note that giving the line number is something very costly, either for what you get naturally from Log4j or the following. You have to accept that cost...
You could use the following APIs:
Updated:
You would have to calculate it yourself. So:
Depending how you prefer your loggers, your helper method may:
Comes out that there is a very simple solution, just add FQCN (The wrapper class' fully qualified class name) to your logger helper:
In Your working class you just do:
Adding details to KLE answer. (sorry, noob user, don't know better way than creating a separate answer )
Instead of sticking the line number to the message, you can put it in the MDC context. See org.apache.log4j.MDC
For example:
That allows users to use mylineNumber in their log4j configuration file
Note: that allows the user to control where and how the line number appears in the message. However, since getting the stacktrace is very costly, you still need to find a way to switch off the feature.
If you have your own logging utility methods, you could add linenumber and filename to the logging argument list and take the cpp route. i.e. Preprocess you source to replace tags like _ LINE _ and _ FILE _ before you do the compile. As an added bonus this would not take nerly as much resources as figuring out at runtime.