-1

I am implementing an application with the Jsch library from JCraft, which is a Java implementation for ssh.

This library has a Logger interface which describes a log function as following

public void log(int level, String message);

Is there any way to implement it with something like this?

public void log(int level, String message)
{
    StackTraceElement trace = getTrace();
    LOGGER.log( trace, level, message);
}
  • See also https://stackoverflow.com/questions/42534564/java-how-to-log-where-my-function-was-called-from – Raedwald Apr 16 '19 at 09:24

3 Answers3

0

From the current thread you can query the entire stacktrace, and leaving the current position [0] out, you have the call site of the log occurrence.

public void log(int level, String message) {
    StackTraceElement trace = Thread.currentThread().getStackTrace()[1]; // Or 2?
    LOGGER.log(trace, level, message);
}

As nowadays exceptions often are chained (thrown furthers as cause), I am not sure whether a single stack trace element suffices.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • I know the mechanism of StackTraceElement. I dont know how to pass the information on some logging framework, for example on SLF4J as Raedwald proposed. – Stathis Alexopoulos Apr 16 '19 at 07:27
0

If getTrace() is suppose to return the call site of the logger statement you can create a new Throwable and convert a stack trace to a string or choose a single frame and convert that to a string. Once you have the string representation of the trace you can concatenate that to the message string and send that to the target logging framework.

If your logging framework supports Mapped Diagnostic Context you can pass the throwable object or stacktrace element itself to the logging framework. If you are using JUL you simply have to use Logger::logp method to pass the call site information.

jmehrens
  • 10,580
  • 1
  • 38
  • 47
-2

Instead of passing the stacktrace, you can pass the exception and have the logging framework print the stacktrace. This is possible through the SLF4J Logger interface and logging frameworks such as logback that conform to it.

Raedwald
  • 46,613
  • 43
  • 151
  • 237