Friday 25 February 2022

Logback: programmatically configure an appender

Using addApender method, we can programmatically configure an appender.

 

Find the below working application.

 

AppenderDemo.java

package com.sample.app;

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.FileAppender;

public class AppenderDemo {

	public static void main(String[] args) {

		ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory
				.getLogger(HelloWorld.class);

		LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
		PatternLayoutEncoder ple = new PatternLayoutEncoder();

		ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
		ple.setContext(loggerContext);
		ple.start();
		FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
		fileAppender.setFile("/Users/Shared/logback/app.log");
		fileAppender.setEncoder(ple);
		fileAppender.setContext(loggerContext);
		fileAppender.start();

		logger.addAppender(fileAppender);
		logger.setAdditive(false);

		logger.trace("Trace message");
		logger.debug("Debug message");
		logger.info("Info message");
		logger.warn("Warning message");
		logger.error("Error message");

	}
}

 

Run above application, and open the file /Users/Shared/logback/app.log to see the log messages.

$cat app.log 
2022-02-20 12:35:30,219 DEBUG [main] c.s.a.HelloWorld [AppenderDemo.java:33] Debug message
2022-02-20 12:35:30,221 INFO [main] c.s.a.HelloWorld [AppenderDemo.java:34] Info message
2022-02-20 12:35:30,221 WARN [main] c.s.a.HelloWorld [AppenderDemo.java:35] Warning message
2022-02-20 12:35:30,221 ERROR [main] c.s.a.HelloWorld [AppenderDemo.java:36] Error message
$

 

When you rerun the application, you can observe that the log messages are appended to app.log file.

 


 

 

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment