[logback-user] Configure Logback programmatically

Endre Stølsvik java at stolsvik.com
Mon Mar 5 00:10:50 CET 2012


Yes, you can - the whole thing is very much programmatically accessible.

But, if the one thing you want is to specify the filename to parse, I found
that the better way was to do as follows:

        System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY,
<filename>);

Do that *before* you access any loggers or logging context, as that
triggers the configuration. After that, I personally do something along the
lines of..:

        // Getting the LoggerContext, which will trigger the default log
config, using the CONFIG_FILE_PROPERTY
        LoggerContext lc;
        try {
            lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        }
        catch (ClassCastException cce) {
            throw new CannotStartupException("Apparently SLF4J is not
backed by Logback."
                    + " This is a requirement, thus an internal fault.",
cce);
        }


        // Set the name of the LoggerContext
        lc.setName("SomeName");

        // Fetch this class's Logger
        log = LoggerFactory.getLogger(LogSetupClass.class);

            // ?: Check if we have warnings or errors in configuration.
            StatusChecker sc = new StatusChecker(lc);
            if (sc.getHighestLevel(0) >= ErrorStatus.WARN) {
                // -> Yes, there are warnings or errors
                // Whine hard about this.
                System.out.println();
                String msg = "****WARNING****: THERE ARE WARNINGS OR ERRORS
IN THE LOGGING CONFIGURATION, READ STATUS BELOW CAREFULLY!!";
                System.out.println(msg);
                // Sleeping to let standard out flush.
                sleep(150);
                System.err.println(msg);
                // Sleeping to let standard error flush.
                sleep(150);
                System.out.println();
            }

            // Print the entire configuration setup ("historical" in that
it shows how we got to this..)
            StatusPrinter.print(lc);




Kind regards,
Endre.

On Sun, Mar 4, 2012 at 20:54, Alex Glass <alexander.glass at gmail.com> wrote:

> Simple question,
>
> How do you configure logback programmatically like we can do in Log4j with
> DOMConfigurator.configure?  I'd like to pass in a filename and have it load
> my configuration.
>
> Thanks,
> Alex
>
> _______________________________________________
> Logback-user mailing list
> Logback-user at qos.ch
> http://mailman.qos.ch/mailman/listinfo/logback-user
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.qos.ch/pipermail/logback-user/attachments/20120305/05efaedb/attachment.html>


More information about the Logback-user mailing list