0

I use following pattern [%file:%line] %msg%n to output file + number to my log.

I as well use a simple wrapper class, that I call L.java. Now it does not make sense to output [L.java:74] Message... to my log. Instead, I would like to output the calling file name and line number...

Is that somehow possible with log4j?

prom85
  • 16,896
  • 17
  • 122
  • 242
  • You will **probably** need to write your own logger that will get the calling method name. See [this](http://stackoverflow.com/a/2924426/1019491) thread for how to get the caller. – Hindol Jun 24 '15 at 06:32

1 Answers1

-1

The PatternLayout are slighty different between log4j 1.x and 2.x, and I do not know which version are you using, but I think you can't achieve this by configuration in neither versions.

You can achieve that programmatically (but this is going to affect your performance), I think in your L.java method you will have to use a method like:

private Logger logger = getYourLoggerAsYouAreCurrentlyDoing();
public enum LogLevel { INFO,DEBUG, ERROR, ETC }

void log(String msg, LogLevel level) {

    StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
    String callerClass = stackTraceElements[1].getClassName();
    String callerLine = "" + stackTraceElements[1].getLineNumber();
    String msg = callerClass + ":" + callerLine + "-" + msg;
    switch(LogLevel) {
        case INFO: logger.info(msg); break;
        case DEBUG: logger.debug(msg); break;
        //etc.
    }
}

And in case another method with the Throwable argument to log stacktraces.

alessiop86
  • 1,285
  • 2
  • 19
  • 38
  • that's the way I do it currently... I just switched to log4j to easily add a file log... And the above mentioned solution does work, but it is somehow restricting as it does not allow me to format my data the way I want, as the custom data can only be part of the `%msg`... – prom85 Jun 24 '15 at 06:51
  • As far as I know, to put dynamic data outside the msg you have to fork the log4j project – alessiop86 Jun 24 '15 at 07:57