Logging from a library


I sometimes create libraries with less overhead than the e.g. a grails plugin.

Applying the same logging as grails is done with these steps:

  • add dependencies
  • add configuration files for testing

build.gradle:

dependencies {
    compile 'ch.qos.logback:logback-core:1.2.3'
    compile 'ch.qos.logback:logback-classic:1.2.3'
    compile 'org.grails:grails-logging:4.0.1'
}

Then create the src/test/resources directory:

In this case I configured test logging with logback-test.xml. For some reason I could not make logback-test.groovy work.

<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{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%15.15thread] %-50.50(%logger{35}.%M) %4.4line - %msg%n</pattern>
        </encoder>
    </appender>

    <logger name="no.prpr" level="TRACE" additivity="false">
        <appender-ref ref="STDOUT" />
    </logger>
    <logger name="org.hibernate.orm.deprecation" level="ERROR" additivity="false" />

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

The test could look like:

@Slf4j
class UserToTenantSpec extends Specification {

    void 'Test valid username'() {
        when:
        String tenant = UserToTenant.getTenant('abc00')
        then:
        tenant == 'abc'
    }

}