I have been trying to configure appender programatically, but not getting success so far. i just want to configure appender without file so that it can send logs to console or file.
String PATTERN = "%d [%p|%c|%C{1}] %m%n";
PatternLayout layout = PatternLayout.createLayout(PATTERN, null, null,
null, null, null);
ConsoleAppender console = ConsoleAppender.createAppender(layout, null,
null, "console", "true", "true"); // create appender
AppenderRef appender = AppenderRef.createAppenderRef("console",
"DEBUG", null);
logger = (Logger) LogManager.getLogger(InitLogger.class);
LoggerContext context = logger.getContext();
BaseConfiguration configuration =(BaseConfiguration) context.getConfiguration();
configuration.addAppender(console);
logger.addAppender(configuration.getAppender("console"));
Enumeration appenders = logger. getAllAppenders(); . . . fileBackupIndex = rollingFileAppender. getMaxBackupIndex();
Log4j2 ConsoleAppender ConfigurationThe target poperty specifies the target of the logging messages i.e. SYSTEM_OUT or SYSTEM_ERR . The follow attribute tells whether the appender should honor the reassignments of System. out or System. err made after the logging configuration has been initialized.
Here is the simplest way to do this:
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.config.AbstractConfiguration;
import org.apache.logging.log4j.core.config.AppenderRef;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.layout.PatternLayout;
public class Main {
public static void main(String[] args) {
configure();
Logger logger = LogManager.getLogger("com.company");
logger.trace("Hello Word!");
}
public static void configure() {
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration();
ConsoleAppender appender = ConsoleAppender.createDefaultAppenderForLayout(PatternLayout.createDefaultLayout());
appender.start();
config.addAppender(appender);
AppenderRef[] refs = new AppenderRef[] { AppenderRef.createAppenderRef(appender.getName(), null, null) };
LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.ALL, LogManager.ROOT_LOGGER_NAME, "true", refs, null, config, null);
loggerConfig.addAppender(appender, null, null);
config.addLogger(LogManager.ROOT_LOGGER_NAME, loggerConfig);
ctx.updateLoggers();
}
}
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