I would need a custom appender for log4j2 that I programmatically plug in (I do not want to alter log4j2.xml, as I need that appender to be used by default). For custom appender, there seems to be an answer How to Create a Custom Appender in log4j2?, but how I can add appender at run-ti,e?
            Asked
            
        
        
            Active
            
        
            Viewed 1,077 times
        
    1 Answers
1
            
            
        Basically you need to instantiate the appender and after it plug it into desired log. In this example I am using ConsoleAppender and rootLogger 
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
ConsoleAppender consoleAppender = ConsoleAppender.
              createDefaultAppenderForLayout(PatternLayout.createDefaultLayout());
consoleAppender.start(); // this is optional
config.addAppender(consoleAppender);  // this is optional
ctx.getRootLogger().addAppender(consoleAppender);
ctx.updateLoggers();
 
    
    
        Anton Balaniuc
        
- 10,889
- 1
- 35
- 53
