14
votes

In my example, I have the following code:

package com.example.somepackage;

public class Example {
    public static void main(String[] args) {
        org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(Example.class);
        logger.info("Example message.");
    }
}

I want it to output to the console like this minimal example:

com.example.somepackage.Example.main Example message.

The only thing I need is either:

  • a pattern to put into the logback.xml file or
  • instructions on further code I need to add to my example code scenario

If extra code is used instead of a XML configuration pattern, please also provide information on how to pair these two, so one can still use patterns for time, log level, etc. in addition to the method name being printed out.

2

2 Answers

32
votes

I think you're looking for the %M pattern. See the Logback docs for all patterns that you could use. Note, however, that these docs also say:

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

0
votes

This is a sample appender that logs method name and line number:

 <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>%d{HH:mm:ss.SSS} %green([%thread]) %highlight(%-5level) (%logger{50}.%M\(%line\)) - (%msg%n)
            </pattern>
        </encoder>
  </appender>