Java Code Examples for org.apache.logging.log4j.core.Appender#start()
The following examples show how to use
org.apache.logging.log4j.core.Appender#start() .
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: OpenCensusLog4jLogCorrelationTest.java From opencensus-java with Apache License 2.0 | 7 votes |
private static String logWithSpanAndLog4jConfiguration( String log4jPattern, SpanContext spanContext, Function<Logger, Void> loggingFunction) { StringWriter output = new StringWriter(); StringLayout layout = PatternLayout.newBuilder().withPattern(log4jPattern).build(); Appender appender = WriterAppender.newBuilder() .setTarget(output) .setLayout(layout) .setName("TestAppender") .build(); ((LoggerContext) LogManager.getContext(false)).updateLoggers(); appender.start(); logger.addAppender(appender); logger.setLevel(Level.ALL); try { logWithSpan(spanContext, loggingFunction, logger); return output.toString(); } finally { logger.removeAppender(appender); } }
Example 2
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 3
Source File: LoggerLoader.java From syncope with Apache License 2.0 | 6 votes |
public static void addAppenderToContext( final LoggerContext ctx, final AuditAppender auditAppender, final LoggerConfig eventLogConf) { Appender targetAppender = ctx.getConfiguration().getAppender(auditAppender.getTargetAppenderName()); if (targetAppender == null) { targetAppender = auditAppender.getTargetAppender(); } targetAppender.start(); ctx.getConfiguration().addAppender(targetAppender); Optional<RewriteAppender> rewriteAppender = auditAppender.getRewriteAppender(); if (rewriteAppender.isPresent()) { rewriteAppender.get().start(); eventLogConf.addAppender(rewriteAppender.get(), Level.DEBUG, null); } else { eventLogConf.addAppender(targetAppender, Level.DEBUG, null); } }
Example 4
Source File: AppenderSet.java From logging-log4j2 with Apache License 2.0 | 6 votes |
public Appender createAppender(final String actualAppenderName, final String sourceAppenderName) { final Node node = nodeMap.get(actualAppenderName); if (node == null) { LOGGER.error("No node named {} in {}", actualAppenderName, this); return null; } node.getAttributes().put("name", sourceAppenderName); if (node.getType().getElementName().equals(Appender.ELEMENT_TYPE)) { final Node appNode = new Node(node); configuration.createConfiguration(appNode, null); if (appNode.getObject() instanceof Appender) { final Appender app = appNode.getObject(); app.start(); return app; } LOGGER.error("Unable to create Appender of type " + node.getName()); return null; } LOGGER.error("No Appender was configured for name {} " + actualAppenderName); return null; }
Example 5
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 6
Source File: Log4j2LoggingHelper.java From herd with Apache License 2.0 | 6 votes |
@Override public StringWriter addLoggingWriterAppender(String appenderName) { // Get the configuration final LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); final Configuration configuration = loggerContext.getConfiguration(); // Create a string writer as part of the appender so logging will be written to it. StringWriter stringWriter = new StringWriter(); // Create and start the appender with the string writer. Appender appender = WriterAppender.createAppender(null, null, stringWriter, appenderName, false, true); appender.start(); // Add the appender to the root logger. configuration.getRootLogger().addAppender(appender, null, null); // Return the string writer. return stringWriter; }
Example 7
Source File: CustomConfiguration.java From logging-log4j2 with Apache License 2.0 | 6 votes |
/** * Constructor to create the default configuration. */ public CustomConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) { super(loggerContext, source); setName(CONFIG_NAME); final Layout<? extends Serializable> layout = PatternLayout.newBuilder() .setPattern(DEFAULT_PATTERN) .setConfiguration(this) .build(); final Appender appender = ConsoleAppender.createDefaultAppenderForLayout(layout); appender.start(); addAppender(appender); final LoggerConfig root = getRootLogger(); root.addAppender(appender, null, null); final String levelName = PropertiesUtil.getProperties().getStringProperty(DEFAULT_LEVEL); final Level level = levelName != null && Level.valueOf(levelName) != null ? Level.valueOf(levelName) : Level.ERROR; root.setLevel(level); }
Example 8
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 9
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 10
Source File: SpectatorAppender.java From spectator with Apache License 2.0 | 5 votes |
/** * Add the spectator appender to the root logger. This method is intended to be called once * as part of the applications initialization process. * * @param registry * Spectator registry to use for the appender. * @param name * Name for the appender. * @param ignoreExceptions * If set to true then the stack trace metrics are disabled. */ public static void addToRootLogger( Registry registry, String name, boolean ignoreExceptions) { final Appender appender = new SpectatorAppender( registry, name, null, null, ignoreExceptions, Property.EMPTY_ARRAY); appender.start(); LoggerContext context = (LoggerContext) LogManager.getContext(false); Configuration config = context.getConfiguration(); addToRootLogger(appender); config.addListener(reconfigurable -> addToRootLogger(appender)); }
Example 11
Source File: ActorLogger.java From actor4j-core with Apache License 2.0 | 5 votes |
private ActorLogger() { loggerContext = (LoggerContext) LogManager.getContext(LogManager.class.getClassLoader(), false); Configuration config = loggerContext.getConfiguration(); Appender systemConsoleAppender = ConsoleAppender.newBuilder() .setName(SYSTEM_CONSOLE_APPENDER_NAME) .setLayout(PatternLayout.newBuilder().withPattern(LAYOUT_CONSOLE_SYSTEM).build()) .setConfiguration(config) .build(); systemConsoleAppender.start(); AppenderRef[] systemAppenderRefs = new AppenderRef[]{AppenderRef.createAppenderRef(SYSTEM_CONSOLE_APPENDER_NAME, null, null)}; systemLoggerConfig = LoggerConfig.createLogger(false, Level.DEBUG, SYSTEM_LOGGER_NAME, "true", systemAppenderRefs, null, config, null); systemLoggerConfig.addAppender(systemConsoleAppender, null, null); Appender userConsoleAppender = ConsoleAppender.newBuilder() .setName(USER_CONSOLE_APPENDER_NAME) .setLayout(PatternLayout.newBuilder().withPattern(LAYOUT_CONSOLE_USER).build()) .setConfiguration(config) .build(); userConsoleAppender.start(); AppenderRef[] userAppenderRefs = new AppenderRef[]{AppenderRef.createAppenderRef(USER_CONSOLE_APPENDER_NAME, null, null)}; userLoggerConfig = LoggerConfig.createLogger(false, Level.DEBUG, USER_LOGGER_NAME, "true", userAppenderRefs, null, config, null); userLoggerConfig.addAppender(userConsoleAppender, null, null); config.addAppender(systemConsoleAppender); config.addAppender(userConsoleAppender); config.addLogger(SYSTEM_LOGGER_NAME, systemLoggerConfig); config.addLogger(USER_LOGGER_NAME, userLoggerConfig); loggerContext.updateLoggers(config); }
Example 12
Source File: LogUtil.java From ldbc_graphalytics with Apache License 2.0 | 5 votes |
public static void appendFileLogger(Level level, String name, Path filePath) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); Layout layout = PatternLayout.createLayout("%d{HH:mm} [%-5p] %msg%n", null, config, null, null, true, false, null, null); Appender appender = FileAppender.createAppender(filePath.toFile().getAbsolutePath(), "true", "false", name, "true", "false", "false", "8192", layout, null, "false", null, config); appender.start(); config.getRootLogger().addAppender(appender, level, null); ctx.updateLoggers(); }
Example 13
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 14
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 15
Source File: AbstractConfiguration.java From logging-log4j2 with Apache License 2.0 | 5 votes |
/** * Start the configuration. */ @Override public void start() { // Preserve the prior behavior of initializing during start if not initialized. if (getState().equals(State.INITIALIZING)) { initialize(); } LOGGER.debug("Starting configuration {}", this); this.setStarting(); if (watchManager.getIntervalSeconds() >= 0) { watchManager.start(); } if (hasAsyncLoggers()) { asyncLoggerConfigDisruptor.start(); } final Set<LoggerConfig> alreadyStarted = new HashSet<>(); for (final LoggerConfig logger : loggerConfigs.values()) { logger.start(); alreadyStarted.add(logger); } for (final Appender appender : appenders.values()) { appender.start(); } if (!alreadyStarted.contains(root)) { // LOG4J2-392 root.start(); // LOG4J2-336 } super.start(); LOGGER.debug("Started configuration {} OK.", this); }
Example 16
Source File: TransferTest.java From logging-log4j-audit with Apache License 2.0 | 5 votes |
private AbstractConfiguration setUpFailingAppender() { Logger auditLogger = (Logger) LogManager.getContext(false).getLogger("AuditLogger"); AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration(); Appender appender = AlwaysFailAppender.createAppender(failingAppenderName); appender.start(); config.addLoggerAppender(auditLogger, appender); return config; }
Example 17
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 18
Source File: CLogOut.java From TweetwallFX with MIT License | 4 votes |
private CLogOut() { final ByteArrayOutputStream stdStream = new ByteArrayOutputStream() { @Override public synchronized void flush() throws IOException { String theString = toString("UTF-8"); /* OK: Establishing connection. Twitter Stream consumer-1[Establishing connection] Connection established. Receiving status stream. Twitter Stream consumer-1[Receiving stream] *Received:{...} Twitter Stream consumer-1[Disposing thread] */ /* WRONG: Establishing connection. Twitter Stream consumer-1[Establishing connection] Exceeded connection limit for user 420 Waiting for 10000 milliseconds Twitter Stream consumer-1[Disposing thread] */ Platform.runLater(() -> { if (theString.startsWith("Establishing connection")) { message.set("Establishing connection...\n Please, wait a few seconds"); } else if (theString.startsWith("Receiving status stream")) { message.set("Receiving tweets!! \n Press stop button to stop the search"); } else if (theString.startsWith("Exceeded connection limit")) { message.set("Exceeded connection limit..."); } else if (theString.startsWith("Waiting for ")) { message.set(theString + " or press stop button to stop the search"); } else if (theString.contains("Disposing thread")) { message.set("The search has finished"); } }); System.out.print("***** " + theString); reset(); } }; LoggerContext context = LoggerContext.getContext(false); Configuration config = context.getConfiguration(); PatternLayout layout = PatternLayout.newBuilder().withConfiguration(config).withPattern("%m%n").build(); Appender appender = WriterAppender.newBuilder().setLayout(layout).setTarget(new OutputStreamWriter(stdStream, StandardCharsets.UTF_8)).build(); appender.start(); config.addAppender(appender); updateLoggers(appender, config); }
Example 19
Source File: JiraLog4j2_2134Test.java From logging-log4j2 with Apache License 2.0 | 4 votes |
@SuppressWarnings("deprecation") @Test public void testRefreshDeprecatedApis() { Logger log = LogManager.getLogger(this.getClass()); final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); PatternLayout layout = PatternLayout.newBuilder() .setPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN) .setPatternSelector(null) .setConfiguration(config) .setRegexReplacement(null) .setCharset(null) .setAlwaysWriteExceptions(false) .setNoConsoleNoAnsi(false) .setHeader(null) .setFooter(null) .build(); // @formatter:off Appender appender = FileAppender.newBuilder() .setFileName("target/test.log") .setAppend(false) .setLocking(false) .setName("File") .setImmediateFlush(true) .setIgnoreExceptions(false) .setBufferedIo(false) .setBufferSize(4000) .setLayout(layout) .setAdvertise(false) .setConfiguration(config) .build(); // @formatter:on appender.start(); config.addAppender(appender); AppenderRef ref = AppenderRef.createAppenderRef("File", null, null); AppenderRef[] refs = new AppenderRef[] { ref }; LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "testlog4j2refresh", "true", refs, null, config, null); loggerConfig.addAppender(appender, null, null); config.addLogger("testlog4j2refresh", loggerConfig); ctx.stop(); ctx.start(config); log.error("Info message"); }
Example 20
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); }