Logging your Maven project with Logback

How do you trace your app?  Well, simple standard output is enough for simple applications.   What if, however, you'd want layered commeting/tracing?  Supposing, say, you do not want lengthy trace info for regular use of your app?  The error reports certainly should be distinguished from debugging info.

Logback is a nice package that does the work.  Your app will emit any sort of messages, with proper labels (error, warning, info, debug, trace).  Load the library by editing pom.xml file.

 
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.2</version>
        </dependency>


The log file should be specified in logback.xml file.  The file should be under src/main/resources.

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

    <timestamp key="time" datePattern="yyyy-MM-dd_HHmmss" />

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>log/log-${time}.log</file>
        <encoder>
            <charset>UTF-8</charset>
            <pattern>%-7([%level]) %m%n</pattern>
        </encoder>

    </appender>

    <root>
        <appender-ref ref="FILE" />
    </root>
 </configuration>


Just by calling those functions, the output will be labeled accordingly.  Add the following code in your Java code:

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

 Logger log = LoggerFactory.getLogger(this.getClass());
 ...

 log.error();
 log.warn();
 log.info();
 log.debug();
 log.trace();

Alternatively, if the Logger is static then the Logger can be called from your main().
     
 static public Logger log = LoggerFactory.getLogger(<YOUR CLASS>.class);


EditProperties is a GUI component for editing Properties values that uses Logback logging system.

Comments

Popular posts from this blog

TreeEditor: Customizing Drag and Drop

Spring Tool Suite