Java Code Examples for org.apache.logging.log4j.core.config.Configuration#addAppender()
The following examples show how to use
org.apache.logging.log4j.core.config.Configuration#addAppender() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Main.java From homework_tester with MIT License | 7 votes |
private static Logger configureLog4j() { LoggerContext context = (LoggerContext) LogManager.getContext(); Configuration config = context.getConfiguration(); PatternLayout layout = PatternLayout.createLayout("%m%n", null, null, Charset.defaultCharset(), false, false, null, null); Appender appender = ConsoleAppender.createAppender(layout, null, null, "CONSOLE_APPENDER", null, null); appender.start(); AppenderRef ref = AppenderRef.createAppenderRef("CONSOLE_APPENDER", null, null); AppenderRef[] refs = new AppenderRef[]{ref}; LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "CONSOLE_LOGGER", "com", refs, null, null, null); loggerConfig.addAppender(appender, null, null); config.addAppender(appender); config.addLogger("Main.class", loggerConfig); context.updateLoggers(config); return LogManager.getContext().getLogger("Main.class"); }
Example 2
Source File: S2STestService.java From Openfire with Apache License 2.0 | 6 votes |
String addAppender(final Writer writer) { final String name = "openfire-s2s-test-appender-" + StringUtils.randomString( 10 ); final LoggerContext context = LoggerContext.getContext(false); final Configuration config = context.getConfiguration(); final PatternLayout layout = PatternLayout.createDefaultLayout(config); final Appender appender = WriterAppender.createAppender(layout, null, writer, name, false, true); appender.start(); config.addAppender(appender); final Level level = null; final Filter filter = null; for (final LoggerConfig loggerConfig : config.getLoggers().values()) { loggerConfig.addAppender(appender, level, filter); } config.getRootLogger().addAppender(appender, level, filter); return name; }
Example 3
Source File: MyServiceUnitTest.java From tutorials with MIT License | 6 votes |
@Test public void testProgrammaticConfig() { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); PatternLayout layout = PatternLayout.newBuilder().withConfiguration(config).withPattern("%d{HH:mm:ss.SSS} %level %msg%n").build(); Appender appender = FileAppender.newBuilder().setConfiguration(config).withName("programmaticFileAppender").withLayout(layout).withFileName("java.log").build(); appender.start(); config.addAppender(appender); AppenderRef ref = AppenderRef.createAppenderRef("programmaticFileAppender", null, null); AppenderRef[] refs = new AppenderRef[] { ref }; LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "programmaticLogger", "true", refs, null, config, null); loggerConfig.addAppender(appender, null, null); config.addLogger("programmaticLogger", loggerConfig); ctx.updateLoggers(); Logger pLogger = LogManager.getLogger("programmaticLogger"); pLogger.info("Programmatic Logger Message"); }
Example 4
Source File: OutputStreamAppenderTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
/** * Validates that the code pattern we use to add an appender on the fly * works with a basic appender that is not the new OutputStream appender or * new Writer appender. */ @Test public void testUpdatePatternWithFileAppender() { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); // @formatter:off final Appender appender = FileAppender.newBuilder() .setFileName("target/" + getClass().getName() + ".log") .setAppend(false) .setName("File") .setIgnoreExceptions(false) .setBufferedIo(false) .setBufferSize(4000) .setConfiguration(config) .build(); // @formatter:on appender.start(); config.addAppender(appender); ConfigurationTestUtils.updateLoggers(appender, config); LogManager.getLogger().error("FOO MSG"); }
Example 5
Source File: ESLoggerConfigFactory.java From core-ng-project with Apache License 2.0 | 6 votes |
public static void configureLogger() { LoggerContext context = (LoggerContext) LogManager.getContext(false); Configuration config = context.getConfiguration(); Map<String, ESLogger> loggers = Maps.newConcurrentHashMap(); Appender appender = new AbstractAppender("", null, null) { @Override public void append(LogEvent event) { String name = event.getLoggerName(); ESLogger logger = loggers.computeIfAbsent(name, key -> new ESLogger(key, null, (LoggerImpl) LoggerFactory.getLogger(key))); logger.log(event.getLevel(), event.getMarker(), event.getMessage(), event.getThrown()); } }; appender.start(); config.addAppender(appender); var loggerConfig = new LoggerConfig("", Level.INFO, false); // only enable info and higher level loggerConfig.addAppender(appender, null, null); config.addLogger("", loggerConfig); context.updateLoggers(); }
Example 6
Source File: Main.java From homework_tester with MIT License | 6 votes |
private static Logger configureLog4j() { LoggerContext context = (LoggerContext) LogManager.getContext(); Configuration config = context.getConfiguration(); PatternLayout layout = PatternLayout.createLayout("%m%n", null, null, Charset.defaultCharset(), false, false, null, null); Appender appender = ConsoleAppender.createAppender(layout, null, null, "CONSOLE_APPENDER", null, null); appender.start(); AppenderRef ref = AppenderRef.createAppenderRef("CONSOLE_APPENDER", null, null); AppenderRef[] refs = new AppenderRef[]{ref}; LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "CONSOLE_LOGGER", "com", refs, null, null, null); loggerConfig.addAppender(appender, null, null); config.addAppender(appender); config.addLogger("Main.class", loggerConfig); context.updateLoggers(config); return LogManager.getContext().getLogger("Main.class"); }
Example 7
Source File: WriterAppenderTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
private void addAppender(final Writer writer, final String writerName) { final LoggerContext context = LoggerContext.getContext(false); final Configuration config = context.getConfiguration(); final PatternLayout layout = PatternLayout.createDefaultLayout(config); final Appender appender = WriterAppender.createAppender(layout, null, writer, writerName, false, true); appender.start(); config.addAppender(appender); ConfigurationTestUtils.updateLoggers(appender, config); }
Example 8
Source File: LogUtil.java From fix-orchestra with Apache License 2.0 | 5 votes |
public static Logger initializeDefaultLogger(Level level, Class<?> clazz) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); final ConsoleAppender appender = ConsoleAppender.newBuilder().setName("Console").build(); config.addAppender(appender); final AppenderRef ref = AppenderRef.createAppenderRef("Console", level, null); final AppenderRef[] refs = new AppenderRef[] {ref}; final LoggerConfig loggerConfig = LoggerConfig.createLogger(true, level, clazz.getName(), null, refs, null, config, null); config.addLogger(clazz.getName(), loggerConfig); ctx.updateLoggers(); return LogManager.getLogger(clazz); }
Example 9
Source File: JavaInstanceRunnable.java From pulsar with Apache License 2.0 | 5 votes |
private void addLogTopicHandler() { if (logAppender == null) return; LoggerContext context = LoggerContext.getContext(false); Configuration config = context.getConfiguration(); config.addAppender(logAppender); for (final LoggerConfig loggerConfig : config.getLoggers().values()) { loggerConfig.addAppender(logAppender, null, null); } config.getRootLogger().addAppender(logAppender, null, null); }
Example 10
Source File: OutputStreamAppenderTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
/** * Tests that you can add an output stream appender dynamically. */ private void addAppender(final OutputStream outputStream, final String outputStreamName) { final LoggerContext context = LoggerContext.getContext(false); final Configuration config = context.getConfiguration(); final PatternLayout layout = PatternLayout.createDefaultLayout(config); final Appender appender = OutputStreamAppender.createAppender(layout, null, outputStream, outputStreamName, false, true); appender.start(); config.addAppender(appender); ConfigurationTestUtils.updateLoggers(appender, config); }
Example 11
Source File: TestLogStrategy.java From JVoiceXML with GNU Lesser General Public License v2.1 | 5 votes |
/** * Initialize this test. */ @BeforeClass public static void init() { final LoggerContext context = LoggerContext.getContext(false); final Configuration config = context.getConfiguration(); final Appender appender = new TestAppender(); appender.start(); config.addAppender(appender); final Level level = null; final Filter filter = null; for (final LoggerConfig loggerConfig : config.getLoggers().values()) { loggerConfig.addAppender(appender, level, filter); } config.getRootLogger().addAppender(appender, level, filter); }
Example 12
Source File: SimpleDiagnosticsAppender.java From samza with Apache License 2.0 | 5 votes |
private void attachAppenderToLoggers(Appender appender) { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); // ensure appender is attached only once per JVM (regardless of #containers) if (config.getRootLogger().getAppenders().get(SimpleDiagnosticsAppender.class.getName()) == null) { System.out.println("Attaching diagnostics appender to root logger"); appender.start(); config.addAppender(appender); for (final LoggerConfig loggerConfig : config.getLoggers().values()) { loggerConfig.addAppender(appender, null, null); } } }
Example 13
Source File: Log4JController.java From GreenSummer with GNU Lesser General Public License v2.1 | 5 votes |
private void initInMemoryAppender() { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); synchronized (ctx) { inMemoryAppenderImpl = null; final Configuration config = ctx.getConfiguration(); Optional<Appender> baseAppender = ctx.getConfiguration().getAppenders().values().stream().findFirst(); if (baseAppender.isPresent()) { inMemoryAppenderImpl = InMemoryAppenderImpl.createAppender("InMemoryAppenderImplAppender", baseAppender.get().getLayout(), config.getFilter(), 200); inMemoryAppenderImpl.start(); config.addAppender(inMemoryAppenderImpl); } } }
Example 14
Source File: Log4J2Logger.java From ignite with Apache License 2.0 | 5 votes |
/** * Creates console appender with some reasonable default logging settings. * * @return Logger with auto configured console appender. */ public Logger createConsoleLogger() { // from http://logging.apache.org/log4j/2.x/manual/customconfig.html final LoggerContext ctx = impl.getContext(); final Configuration cfg = ctx.getConfiguration(); PatternLayout.Builder builder = PatternLayout.newBuilder() .withPattern("%d{ISO8601}][%-5p][%t][%c{1}] %m%n") .withCharset(Charset.defaultCharset()) .withAlwaysWriteExceptions(false) .withNoConsoleNoAnsi(false); PatternLayout layout = builder.build(); ConsoleAppender.Builder consoleAppenderBuilder = ConsoleAppender.newBuilder() .withName(CONSOLE_APPENDER) .withLayout(layout); ConsoleAppender consoleApp = consoleAppenderBuilder.build(); consoleApp.start(); cfg.addAppender(consoleApp); cfg.getRootLogger().addAppender(consoleApp, Level.TRACE, null); ctx.updateLoggers(cfg); return ctx.getRootLogger(); }
Example 15
Source File: LogFactory.java From chronus with Apache License 2.0 | 5 votes |
private Appender getAppender(String clKey, Configuration config, Appender appenderCfg) { Appender appender = null; if (appenderCfg instanceof RollingFileAppender) { RollingFileAppender rollingFileAppender = (RollingFileAppender) appenderCfg; appender = RollingFileAppender.newBuilder() .setConfiguration(config) .withName(clKey) .withFileName(rollingFileAppender.getFileName()) .withFilePattern(rollingFileAppender.getFilePattern()) .withLayout(rollingFileAppender.getLayout()) .withFilter(rollingFileAppender.getFilter()) .withPolicy(rollingFileAppender.getTriggeringPolicy()) .withStrategy(rollingFileAppender.getManager().getRolloverStrategy()) .build(); } else if (appenderCfg instanceof FileAppender) { FileAppender fileAppender = (FileAppender) appenderCfg; appender = FileAppender.newBuilder() .setConfiguration(config) .withName(appenderCfg.getName()) .withFileName(fileAppender.getFileName()) .withLayout(fileAppender.getLayout()) .withFilter(fileAppender.getFilter()) .build(); } else { LogManager.getLogger(LogFactory.class).warn("unsupported appender type ,appender type not in(RollingFileAppender,ConsoleAppender,FileAppender)", appenderCfg.getClass()); } if (appender != null) { config.addAppender(appender); } return appender; }
Example 16
Source File: LogFactory.java From chronus with Apache License 2.0 | 5 votes |
private Appender getAppender(LogConfig abyLogConfig, Configuration config, Appender appenderCfg) { Appender appender = null; if (appenderCfg instanceof RollingFileAppender) { RollingFileAppender rollingFileAppender = (RollingFileAppender) appenderCfg; appender = RollingFileAppender.newBuilder() .setConfiguration(config) .withName(appenderCfg.getName().replace(abyLogConfig.getAppenderNameKey(), abyLogConfig.getName())) .withFileName(rollingFileAppender.getFileName().replaceAll(abyLogConfig.getFileNameKey(), abyLogConfig.getFileName())) .withFilePattern(rollingFileAppender.getFilePattern().replaceAll(abyLogConfig.getFileNameKey(), abyLogConfig.getFileName())) .withLayout(rollingFileAppender.getLayout()) .withFilter(rollingFileAppender.getFilter()) .withPolicy(rollingFileAppender.getTriggeringPolicy()) .withStrategy(rollingFileAppender.getManager().getRolloverStrategy()) .build(); } else if (appenderCfg instanceof FileAppender) { FileAppender fileAppender = (FileAppender) appenderCfg; appender = FileAppender.newBuilder() .setConfiguration(config) .withName(appenderCfg.getName().replace(abyLogConfig.getAppenderNameKey(), abyLogConfig.getName())) .withFileName(fileAppender.getFileName().replaceAll(abyLogConfig.getFileNameKey(), abyLogConfig.getFileName())) .withLayout(fileAppender.getLayout()) .withFilter(fileAppender.getFilter()) .build(); } else { LogManager.getLogger(LogFactory.class).warn("unsupported appender type ,appender type not in(RollingFileAppender,ConsoleAppender,FileAppender)", appenderCfg.getClass()); } if (appender != null) { if (!appender.isStarted()) { appender.start(); } config.addAppender(appender); } return appender; }
Example 17
Source File: LoggerLoader.java From Zebra with Apache License 2.0 | 4 votes |
@SuppressWarnings({ "rawtypes", "unchecked" }) public static synchronized void init() { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); Layout layout = PatternLayout.newBuilder().withPattern("%d{yyyy-MM-dd HH:mm:ss}:%p %t %c - %m%n") .withConfiguration(config).withRegexReplacement(null).withCharset(null).withAlwaysWriteExceptions(true) .withNoConsoleNoAnsi(false).withHeader(null).withFooter(null).build(); // file info Filter fileInfoFilter = ThresholdFilter.createFilter(Level.ERROR, Result.DENY, Result.ACCEPT); Appender fileInfoAppender = RollingFileAppender.createAppender(LOG_ROOT + "/zebra.log", LOG_ROOT + "/zebra.log.%d{yyyy-MM-dd}.gz", "true", "FileInfo", "true", "4000", "true", TimeBasedTriggeringPolicy.createPolicy("1", "true"), ZebraRolloverStrategy.createStrategy("30", "1", null, Deflater.DEFAULT_COMPRESSION + "", config), layout, fileInfoFilter, "false", null, null, config); config.addAppender(fileInfoAppender); fileInfoAppender.start(); AppenderRef fileInfoRef = AppenderRef.createAppenderRef("FileInfo", null, fileInfoFilter); // console error Appender consoleErrorAppender = ConsoleAppender.createAppender(layout, null, "SYSTEM_ERR", "ConsoleError", "false", "false"); config.addAppender(consoleErrorAppender); consoleErrorAppender.start(); // console info Filter consoleWarnFilter = ThresholdFilter.createFilter(Level.ERROR, Result.DENY, Result.NEUTRAL); Appender consoleWarnAppender = ConsoleAppender.createAppender(layout, consoleWarnFilter, "SYSTEM_OUT", "ConsoleWarn", "false", "false"); config.addAppender(consoleWarnAppender); consoleWarnAppender.start(); AppenderRef consoleWarnAppenderRef = AppenderRef.createAppenderRef("ConsoleWarn", Level.WARN, consoleWarnFilter); AppenderRef consoleErrorAppenderRef = AppenderRef.createAppenderRef("ConsoleError", Level.WARN, null); AppenderRef[] refs = new AppenderRef[] { consoleErrorAppenderRef, consoleWarnAppenderRef, fileInfoRef }; LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "com.dianping.zebra", "true", refs, null, config, null); loggerConfig.addAppender(consoleErrorAppender, Level.ERROR, null); loggerConfig.addAppender(consoleWarnAppender, Level.INFO, null); loggerConfig.addAppender(fileInfoAppender, Level.INFO, null); config.addLogger("com.dianping.zebra", loggerConfig); ctx.updateLoggers(); context = ctx; }
Example 18
Source File: SmokeTestBase.java From log4j2-elasticsearch with Apache License 2.0 | 4 votes |
public final void createLoggerProgrammatically(Supplier<ElasticsearchAppender.Builder> appenderBuilder, Function<Configuration, AsyncLoggerConfigDelegate> delegateSupplier) { LoggerContext ctx = LoggerContext.getContext(false); final Configuration config = ctx.getConfiguration(); Appender appender = appenderBuilder.get().build(); appender.start(); AppenderRef ref = AppenderRef.createAppenderRef(DEFAULT_APPENDER_NAME, Level.INFO, null); AppenderRef[] refs = new AppenderRef[] {ref}; // set up disruptor forcefully ((LifeCycle)delegateSupplier.apply(config)).start(); AsyncLoggerConfig loggerConfig = (AsyncLoggerConfig) AsyncLoggerConfig.createLogger(false, Level.INFO, DEFAULT_LOGGER_NAME, "false", refs, null, config, null ); loggerConfig.addAppender(appender, Level.INFO, null); config.addAppender(appender); config.addLogger(DEFAULT_LOGGER_NAME, loggerConfig); }
Example 19
Source File: GelfLog4j2Init.java From xian with Apache License 2.0 | 4 votes |
/** * add the gelf-log4j2 appender into log4j2 context. */ private void addAppender() { final LoggerContext context = LoggerContext.getContext(false); final Configuration defaultConfig = context.getConfiguration(); String gelfInputUrl = EnvUtil.isLan() ? XianConfig.get("gelfInputLanUrl") : XianConfig.get("gelfInputInternetUrl"); System.out.println("gelfInputUrl=" + gelfInputUrl); int gelfInputPort = XianConfig.getIntValue("gelfInputPort"); if (StringUtil.isEmpty(gelfInputUrl) || gelfInputPort <= 0) { System.out.println("Gelf input url or port is not properly configured. No log will be sent to gelf logger server."); return; } final GelfLogAppender appender = /* WriterAppender.createAppender(layout, null, writer, writerName, false, true)*/ GelfLogAppender.createAppender( defaultConfig, "gelf", LevelRangeFilter.createFilter(Level.OFF, Level.INFO, Filter.Result.ACCEPT, null), new GelfLogField[]{ new GelfLogField("environment", EnvUtil.getEnv(), null, null), new GelfLogField("application", EnvUtil.getApplication(), null, null), new GelfLogField("pid", JavaPIDUtil.getProcessName(), null, null), new GelfLogField("nodeId", LocalNodeManager.LOCAL_NODE_ID, null, null), new GelfLogField("thread", null, null, PatternLayout.newBuilder().withAlwaysWriteExceptions(false).withPattern("%t").build()), new GelfLogField("logger", null, null, PatternLayout.newBuilder().withAlwaysWriteExceptions(false).withPattern("%c").build()), new GelfLogField("msgId", null, "msgId", null), }, null, null, gelfInputUrl, null, gelfInputPort + "", null, "false", null, null, "gelf-log4j2", "true",//only works when extractStackTrace is true null, null, null, true, "%p %m%n", MessageFormatEnum.json ); if (appender == null) throw new RuntimeException("gelf-log4j2 fails to initialize."); appender.start(); defaultConfig.addAppender(appender); updateLoggers(appender, defaultConfig); }
Example 20
Source File: ApsSystemUtils.java From entando-core with GNU Lesser General Public License v3.0 | 4 votes |
public void init() throws Exception { String active = (String) this.systemParams.get(INIT_PROP_LOG_ACTIVE_FILE_OUTPUT); if (StringUtils.isEmpty(active) || !active.equalsIgnoreCase("true")) { return; } String appenderName = "ENTANDO"; String conversionPattern = (String) this.systemParams.get("log4jConversionPattern"); if (StringUtils.isBlank(conversionPattern)) { conversionPattern = "%d{yyyy-MM-dd HH:mm:ss.SSS} - %-5p - %c - %m%n"; } String maxFileSize = (String) this.systemParams.get(INIT_PROP_LOG_FILE_SIZE); if (StringUtils.isBlank(maxFileSize)) { maxFileSize = "1MB"; //default size } else { long mega = new Long(maxFileSize) / KILOBYTE; maxFileSize = mega + "KB"; } String filePattern = (String) this.systemParams.get(INIT_PROP_LOG_FILE_PATTERN); String filename = (String) this.systemParams.get(INIT_PROP_LOG_NAME); int maxBackupIndex = Integer.parseInt((String) this.systemParams.get(INIT_PROP_LOG_FILES_COUNT)); String log4jLevelString = (String) this.systemParams.get(INIT_PROP_LOG_LEVEL); if (StringUtils.isBlank(log4jLevelString)) { log4jLevelString = "INFO"; //default level } Configurator.setRootLevel(Level.getLevel(log4jLevelString)); LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); loggerContext.getRootLogger().setLevel(Level.getLevel(log4jLevelString)); Configurator.setAllLevels(loggerContext.getRootLogger().getName(), Level.getLevel(log4jLevelString)); Configuration configuration = loggerContext.getConfiguration(); RollingFileAppender fileAppender = (RollingFileAppender) configuration.getAppender(appenderName); if (null == fileAppender) { PathCondition[] pathConditions = new PathCondition[]{IfAccumulatedFileCount.createFileCountCondition(maxBackupIndex)}; String basePath = filePattern.substring(0, filePattern.lastIndexOf(File.separator)); DeleteAction deleteAction = DeleteAction.createDeleteAction(basePath, true, 1, false, null, pathConditions, null, configuration); SizeBasedTriggeringPolicy policy = SizeBasedTriggeringPolicy.createPolicy(maxFileSize); PatternLayout layout = PatternLayout.newBuilder().withPattern(conversionPattern).build(); DefaultRolloverStrategy strategy = DefaultRolloverStrategy.newBuilder() .withConfig(configuration).withMax(String.valueOf(maxBackupIndex)) .withCustomActions(new Action[]{deleteAction}).build(); fileAppender = RollingFileAppender.newBuilder() .withName(appenderName) .setConfiguration(configuration) .withLayout(layout) .withFileName(filename) .withFilePattern(filePattern) .withPolicy(policy) .withStrategy(strategy) .build(); configuration.addAppender(fileAppender); Configurator.setLevel(appenderName, Level.getLevel(log4jLevelString)); fileAppender.start(); } AsyncAppender async = (AsyncAppender) loggerContext.getRootLogger().getAppenders().get("async"); if (null == async) { AppenderRef ref = AppenderRef.createAppenderRef(appenderName, Level.getLevel(log4jLevelString), null); async = AsyncAppender.newBuilder().setName("async") .setConfiguration(configuration) .setAppenderRefs(new AppenderRef[]{ref}).build(); configuration.addAppender(async); loggerContext.getRootLogger().addAppender(async); async.start(); } loggerContext.updateLoggers(); }