I am new to logback, I want configure logback programmatically. Currently I am using static configuration like below:
<configuration>
<appender name="KIWI" class="ch.qos.logback.classic.net.SyslogAppender">
<syslogHost>localhost:8080</syslogHost>
<facility>LOCAL0</facility>
<suffixPattern>%thread: %-5level %logger{36} - %msg%n</suffixPattern>
</appender>
<logger name="com.javacodegeeks.examples.logbacksyslogexample.message.kiwi" level="INFO">
<appender-ref ref="KIWI" />
</logger>
</configuration>
Is it possible to set the syslogHost dynamically?
Yes it is possible to configure logback programmatically, you need to extend ContextAwareBase and implement Configurator, like code below
public class MyLogbackConfigurer extends ContextAwareBase implements Configurator {
@Override
public void configure(LoggerContext lc) {
addInfo("Setting up default configuration.");
ConsoleAppender<ILoggingEvent> ca = new ConsoleAppender<ILoggingEvent>();
ca.setContext(lc);
ca.setName("console");
LayoutWrappingEncoder<ILoggingEvent> encoder = new LayoutWrappingEncoder<ILoggingEvent>();
encoder.setContext(lc);
// same as
// PatternLayout layout = new PatternLayout();
// layout.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
TTLLLayout layout = new TTLLLayout();
layout.setContext(lc);
layout.start();
encoder.setLayout(layout);
ca.setEncoder(encoder);
ca.start();
FileAppender f=new FileAppender();
f.setEncoder(encoder);
f.setLayout(layout);
f.setContext(lc);
f.setFile("log.log");
f.setAppend(true);
f.setName("logFile");
f.start();
Logger rootLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME);
rootLogger.addAppender(ca);
rootLogger.addAppender(f);
Logger springLogger = lc.getLogger("org.springframework");
springLogger.setLevel(Level.WARN);
}
}
and you will need to create a file under src/main/resources/META-INF/services/ch.qos.logback.classic.spi.Configurator which will have the class name of your configurer. Here is my example and for the config.
I did not use SyslogAppender before but you can change the example I gave and you can use System.getProperty("proName") or System.getenv("envName")
Before start implementing everything from scratch, have you tried to change xml like below ?
<syslogHost>${SYSLOG}</syslogHost>
And run the jar like this "java -jar yourjarpath.jar -DSYSLOG=localhost:8080" this way you will not need to write that configure class detailed doc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With