Last active
December 28, 2022 00:31
-
-
Save daanta-real/9fe753aba5307d8c98d8264dbae9d255 to your computer and use it in GitHub Desktop.
Logback custom appender - minimal example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package utils.logging; | |
import ch.qos.logback.classic.Logger; | |
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.AppenderBase; | |
import org.slf4j.LoggerFactory; | |
public class CustomAppender extends AppenderBase<ILoggingEvent> { | |
// 1. Fields | |
private final Logger rootLogger; | |
private final LoggerContext ctx; | |
private final PatternLayoutEncoder encoder; | |
// 2. Constructor | |
private CustomAppender() { | |
rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); | |
ctx = rootLogger.getLoggerContext(); | |
encoder = new PatternLayoutEncoder(); | |
} | |
// 3. Initializer | |
// Make an appender and register as a logger | |
public static void init() { | |
// 1. Making instance | |
CustomAppender instance = new CustomAppender(); | |
// 2. Encoder | |
instance.encoder.setContext(instance.ctx); | |
instance.encoder.setPattern("[%d{yyyy-MM-dd HH:mm:ss}][%thread] ☞ %msg%n"); | |
instance.encoder.start(); | |
// 3. Appender | |
instance.setContext(instance.ctx); | |
instance.start(); | |
// 4. Apply to log context | |
instance.rootLogger.addAppender(instance); | |
} | |
// 4. Append - main | |
@Override | |
protected void append(ILoggingEvent event) { | |
String msg = new String(encoder.encode(event)); | |
System.out.println("I got a new log message!: " + msg); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import lombok.extern.slf4j.Slf4j; | |
import utils.logging.CustomAppender; | |
@Slf4j | |
public class Main { | |
public static void main(String[] args) { | |
try { | |
// Logging start | |
CustomAppender.init(); | |
// Load all preferences | |
log.info("Logback custom appender has been applied!"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment