Tips to add logback.xml File into Class path

Sometimes it becomes very painful that your logback.xml file is not recognized by project. There are different reasons for this:

  1. logback.xml is not present in src/main/resources folder of your project. If it’s a maven/gradle project, always keep this file in the specified folder ‘src/main/resources
  2. Execute follwoing code into your main class and observe the output
// This line should return the path of this file if found otherwise you will see 'null' on console
System.out.println(getClass().getClassLoader().getResource("logback.xml"));

// These lines will also print that if your file has been found in the class path of the project
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
// print logback's internal status
StatusPrinter.print(lc);

logback.xml

<configuration>
<appender name="SIFT" class="ch.qos.logback.classic.sift.SiftingAppender">
<discriminator>
<key>testMethodName</key>
<defaultValue>unknown</defaultValue>
</discriminator>
<sift>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>build/reports/%d{yyyyMMdd}/separateLogsTestCases/${testMethodName}.log
</fileNamePattern>
</rollingPolicy>
<append>false</append>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d [%4F:%t:%L] - %m%n</pattern>
</encoder>
</appender>
</sift>
</appender>

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>

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

</configuration>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s