Logback is wonderful (Part 2)

My second post about Logback presents a truly wonderful feature: it can reconfigure itself automatically when the configuration file changes. This means that your application do not have to be restarted when you modify logback.xml.

The following configuration file demonstrates how to use this feature:

<configuration debug="true" scan="true" scanPeriod="5 seconds">

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

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

</configuration>

If the value of the scan attribute on the configuration element is true, Logback will scan for changes in the configuration file periodically.

The value of the scanPeriod attribute on the configuration element determines how often Logback will look for changes in the configuration. Values can be specified in units of milliseconds, seconds, minutes or hours. For example, the following are all valid values for the scanPeriod attribute: 1500 milliseconds, 1 second, 0.5 minute, 2 hours, 1 day.

Each time the configuration file changes the logging system will automatically re-configure itself accordingly.

To play with this handy feature download this project. (Building the project requires Apache Maven.) Run the my.Main class that will bring up a window in which the logback.xml file can be edited. The program writes log messages to the console in an infinite loop using a timer.

Modify and save the configuration to see the effects immediately. For example, change the content of the level element to OFF in line 5 to completely disable logging on the console. To log messages at or above the WARN level use the value WARN instead.

Toy example that demonstrates automatic re-configuration


Logback is wonderful, isn’t it?

Advertisements
Tagged

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: