简体   繁体   中英

How to add dynamic metadata to a singleton SLF4J logger in Java?

This is a Java question.

I have around 100 static functions that use a slf4j logger. I want to add some metadata to standardise the logs - assume it's some kind of preamble that is a function of what processing is currently going on. How can I get the logger to print that metadata without going in to each of the static functions and changing them to explicitly add in the metadata.

eg


static Logger logger; ...
void mainProcessing() {
String file = "current_file.txt";
int line = 3;
...
func1();
func2();
...

}

void func1() {
...
logger.warn("some warning");
}

I'd like to see "WARN: File current_file.txt, line 3, msg: some warning" in the logs.

Any ideas?

(Prefer not to have to change each of the func1() functions obviously, if possible)

Thanks in advance.

You need to specify print format. However beware, that obtaining line number and/or file will greatly decrease your application performance. This is not C++, Logback will probably create a Throwable object for each line, to retrieve the stacktrace and extract the line number and file name.

Regarding line:

L / line Outputs the line number from where the logging request was issued.

Generating the line number information is not particularly fast. Thus, its use should be avoided unless execution speed is not an issue.

Regarding file:

F / file Outputs the file name of the Java source file where the logging request was issued.

Generating the file information is not particularly fast. Thus, its use should be avoided unless execution speed is not an issue.

http://logback.qos.ch/manual/layouts.html#file

Sample logback.xml configuration would be:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

  <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{"yy-MM-dd HH:mm:ss,SSS"}: %-5p %F:%L [%t] %c{0}: %M - %m%n</pattern>
    </encoder>
  </appender>

  <root level="INFO">
    <appender-ref ref="console" />
  </root>
</configuration>

Better to redesign your code , that messages are more verbose and not unique , containing the context and required data to debug it by a person that does not know the code very well (your future co-worker)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM