Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to trigger a stacktrace whenever a particular logger is used?

I'm currently trying to track down the source of some lazy loading calls in hibernate, and the easiest way to do so would be to turn on hibernate SQL logging whenever the lazy loading is going to occur and then ideally trigger a stack trace output whenever the logger is used. Right now I'm using Hibernate 3.5.2 which uses SLF4j and using Log4j as my logging implementation.

I suppose I could use AOP to surround every logging call and check if its a call to the SQL logger, but this seems kind of heavy handed and I wanted to know if there was a simpler approach that I was missing before I went down that road.

like image 364
Jherico Avatar asked Jul 01 '10 23:07

Jherico


People also ask

Should stack traces be logged?

Therefore, you should log a stacktrace if, and only if, and always if, the exception indicates a bug in the program. However, that does not always indicate that a method you write should catch and log the exception.

How do you print StackTrace in logs?

The function printStackTrace() of the Exception class can take one parameter, either a PrintStream or a PrintWriter. Thus, it is possible, using a StringWriter, to print the stack trace into a String: StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e. printStackTrace(pw);

What causes stack trace?

Usually, a stack trace is shown when an Exception is not handled correctly in code. (An exception is what a runtime environment uses to tell you that there's an error in your code.) This may be one of the built-in Exception types, or a custom Exception created by a program or a library.

What is exception StackTrace?

A trace of the method calls is called a stack trace. The stack trace listing provides a way to follow the call stack to the line number in the method where the exception occurs. The StackTrace property returns the frames of the call stack that originate at the location where the exception was thrown.


1 Answers

You can extend one of the log4j appenders and then use that in your log4j.xml.

public class StackPrintingFileAppender extends FileAppender {
    protected void subAppend(LoggingEvent event) {
        new Exception().printStackTrace(new PrintWriter(qw));
        super.subAppend();
    }
}

and then in log4j.xml:

<appender name="logger" class="StackPrintingFileAppender">
    ...
</appender>
like image 101
krock Avatar answered Oct 11 '22 07:10

krock