[logback-user] programmatic configuration to log to file

Steve Prior sprior at geekster.com
Thu Jan 31 02:36:42 CET 2013


Based on some examples I cobbled together the following code to programmatically 
configure logback to write its output to a file (I don't like having config 
files around), but the output still goes to stdout in addition to the file.  Can 
anyone give me a clue how I can only have the output go to the specific file and 
not stdout?

Thanks
Steve

       LoggerContext loggerContext = (LoggerContext) 
LoggerFactory.getILoggerFactory();

       FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
       fileAppender.setContext(loggerContext);
       fileAppender.setFile(ConcurrencyExample.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();

       // attach the rolling file appender to the logger of your choice
       Logger logbackLogger = loggerContext.getLogger(ConcurrencyExample.class);
       logbackLogger.addAppender(fileAppender);

       // OPTIONAL: print logback internal status messages
       StatusPrinter.print(loggerContext);

       // log something
       logbackLogger.info("hello");


More information about the Logback-user mailing list