[logback-user] programmatic configuration to log to file

ceki ceki at qos.ch
Fri Feb 1 19:17:54 CET 2013


Hi Steve,

The code for programmatic configuration is good. You just need to reset 
the context before you configure. Add the following line after the 
definitionof the loggerContext variable.

   loggerContext.reset();

HTH,

-- 
Ceki
65% of statistics are made up on the spot

On 01.02.2013 19:01, Steve Prior wrote:
> On 2/1/2013 12:45 PM, Marshall Pierce wrote:
>> Is it the same output that is also showing up in the log file, or
>> other output? Can you provide a more complete code sample with file
>> output and stdout output?
>>
>> Marshall
>
> Here is the complete source code (no config files at all):
> package com.geekster.logbackDemo;
>
> import org.slf4j.LoggerFactory;
>
> import ch.qos.logback.classic.Logger;
> import ch.qos.logback.classic.LoggerContext;
> import ch.qos.logback.classic.PatternLayout;
> import ch.qos.logback.classic.spi.ILoggingEvent;
> import ch.qos.logback.core.FileAppender;
>
> public class Testcase {
>
>     public static void main(String[] args) {
>        LoggerContext loggerContext = (LoggerContext)
> LoggerFactory.getILoggerFactory();
>
>        FileAppender<ILoggingEvent> fileAppender = new
> FileAppender<ILoggingEvent>();
>        fileAppender.setContext(loggerContext);
>        fileAppender.setFile(Testcase.class.getSimpleName() + ".log");
>
>        PatternLayout pl = new PatternLayout();
>        pl.setPattern("%d %5p %t [%c:%L] %m%n)");
>        pl.setContext(loggerContext);
>        pl.start();
>        fileAppender.setLayout(pl);
>
>        fileAppender.start();
>
>        Logger logbackLogger = loggerContext.getLogger(Testcase.class);
>        logbackLogger.addAppender(fileAppender);
>
>        logbackLogger.info("this should only be in the logfile.");
>        System.out.println("this should only be at the console");
>     }
>
> }
>
> Here is what gets written to System.out:
> 12:57:07.496 [main] INFO  com.geekster.logbackDemo.Testcase - this
> should only be in the logfile.
> this should only be at the console
>
> Here is what gets written to Testcase.log:
> 2013-02-01 12:57:07,496  INFO main
> [com.geekster.logbackDemo.Testcase:31] this should only be in the logfile.
>
>
> So what I'm looking to do is to have the log entry "12:57:07.496 [main]
> INFO com.geekster.logbackDemo.Testcase - this should only be in the
> logfile." only appear in the logfile, but not at the console where I
> only expect "this should only be at the console" to be visible.
>
> Thanks for looking.
> Steve
>
>



More information about the Logback-user mailing list