Suzan Cioc
Suzan Cioc

Reputation: 30097

How to print current class name with logback?

The following config

<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} %C{0}: %msg%n</pattern>
        </encoder>
    </appender>

    <root level="debug">
        <appender-ref ref="STDOUT" />
    </root>

</configuration>

and the following code

package tests;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Runner {

    private static final Logger log = LoggerFactory.getLogger(Runner.class);



    public static void main(String[] args) {

        new Runner().new Parent().hello();
        new Runner().new Child().hello();
    }

    public class Parent {

        public void hello() {
            log.info("Hello from " + getClass().getSimpleName());
        }
    }

    public class Child extends Parent{

    }
}

outputs

20:42:13.811 Runner$Parent: Hello from Parent
20:42:13.814 Runner$Parent: Hello from Child

which means that %C{0} outputs something different, than this.getClass().getSimpleName().

Is it possible to output the same as latter with logback pattern?

Upvotes: 4

Views: 8324

Answers (2)

Manish Maheshwari
Manish Maheshwari

Reputation: 4134

In logback config file, use a conversion specifier: %class{0} to output the class name. Example:

<pattern>%d %-5level %class{0}: %msg%n</pattern>

Else, try using the Logger simple name by %logger{0}, and use a desired logger for each class.

Upvotes: 7

Dave
Dave

Reputation: 888

the layout configuration page from logback has this stated:

%C

or

%class

from: Layouts

Upvotes: 4

Related Questions