org.apache.logging.log4j.core.config.Configuration Java Examples

The following examples show how to use org.apache.logging.log4j.core.config.Configuration. 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 vote down vote up
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: LoggerStringWriter.java    From servicetalk with Apache License 2.0 7 votes vote down vote up
private static StringWriter addWriterAppender(final LoggerContext context, Level level) {
    final Configuration config = context.getConfiguration();
    final StringWriter writer = new StringWriter();

    final Map.Entry<String, Appender> existing = config.getAppenders().entrySet().iterator().next();
    final WriterAppender writerAppender = WriterAppender.newBuilder()
            .setName(APPENDER_NAME)
            .setLayout(existing.getValue().getLayout())
            .setTarget(writer)
            .build();

    writerAppender.start();
    config.getRootLogger().addAppender(writerAppender, level, null);

    return writer;
}
 
Example #3
Source File: AsyncAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncProperties() throws Exception {
    LoggerContext loggerContext = configure("target/test-classes/log4j1-async.properties");
    Logger logger = LogManager.getLogger("test");
    logger.debug("This is a test of the root logger");
    Thread.sleep(50);
    Configuration configuration = loggerContext.getConfiguration();
    Map<String, Appender> appenders = configuration.getAppenders();
    ListAppender messageAppender = null;
    for (Map.Entry<String, Appender> entry : appenders.entrySet()) {
        if (entry.getKey().equals("list")) {
            messageAppender = (ListAppender) ((AppenderAdapter.Adapter) entry.getValue()).getAppender();
        }
    }
    assertNotNull("No Message Appender", messageAppender);
    List<String> messages = messageAppender.getMessages();
    assertTrue("No messages", messages != null && messages.size() > 0);
}
 
Example #4
Source File: Log4j2ConfigurationFactoryTest.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Test
void testSoutJsonTempJson() {
    Configuration configuration = getLogConfig(Map.of("log_format_sout", "json"));

    assertThat(configuration.getAppenders().values()).hasSize(2);
    Optional<ConsoleAppender> consoleAppender = configuration.getAppenders().values().stream()
        .filter(ConsoleAppender.class::isInstance)
        .map(ConsoleAppender.class::cast)
        .findAny();
    assertThat(consoleAppender).isNotEmpty();
    assertThat(consoleAppender.get().getLayout()).isInstanceOf(EcsLayout.class);

    Optional<RollingFileAppender> fileAppender = configuration.getAppenders().values().stream()
        .filter(RollingFileAppender.class::isInstance)
        .map(RollingFileAppender.class::cast)
        .findAny();
    assertThat(fileAppender).isNotEmpty();
    assertThat(fileAppender.get().getLayout()).isInstanceOf(EcsLayout.class);
}
 
Example #5
Source File: MyLogger.java    From Flashtool with GNU General Public License v3.0 6 votes vote down vote up
public static void setLevel(Level level) {
	LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
	Configuration config = ctx.getConfiguration();
	LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); 
	loggerConfig.setLevel(level);
	ctx.updateLoggers();
		if (level == Level.ERROR) {
			logger.error("<- This level is successfully initialized");
		}
		if (level == Level.WARN) {
			logger.warn("<- This level is successfully initialized");
		}
		if (level == Level.DEBUG) {
			logger.debug("<- This level is successfully initialized");
		}
		if (level == Level.INFO) {
			logger.info("<- This level is successfully initialized");
		}
}
 
Example #6
Source File: AppenderRefFailoverPolicyTest.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Test(expected = ConfigurationException.class)
public void throwsExceptionOnUnresolvedAppender() {

    // given
    Appender appender = mock(Appender.class);
    when(appender.isStarted()).thenReturn(true);
    Configuration configuration = mock(Configuration.class);
    String testAppenderRef = "testAppenderRef";
    when(configuration.getAppender(testAppenderRef)).thenReturn(null);

    FailoverPolicy<String> failoverPolicy = createTestFailoverPolicy(testAppenderRef, configuration);

    String failedMessage = "test failed message";

    // when
    failoverPolicy.deliver(failedMessage);

}
 
Example #7
Source File: MyServiceUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@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 #8
Source File: OutputStreamAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #9
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private void testDailyRollingFileAppender(final String configResource, final String name, final String filePattern) throws URISyntaxException {
	final Configuration configuration = getConfiguration(configResource);
	final Appender appender = configuration.getAppender(name);
	assertNotNull(appender);
	assertEquals(name, appender.getName());
	assertTrue(appender.getClass().getName(), appender instanceof RollingFileAppender);
	final RollingFileAppender rfa = (RollingFileAppender) appender;
	assertEquals("target/hadoop.log", rfa.getFileName());
	assertEquals(filePattern, rfa.getFilePattern());
	final TriggeringPolicy triggeringPolicy = rfa.getTriggeringPolicy();
	assertNotNull(triggeringPolicy);
	assertTrue(triggeringPolicy.getClass().getName(), triggeringPolicy instanceof CompositeTriggeringPolicy);
	final CompositeTriggeringPolicy ctp = (CompositeTriggeringPolicy) triggeringPolicy;
	final TriggeringPolicy[] triggeringPolicies = ctp.getTriggeringPolicies();
	assertEquals(1, triggeringPolicies.length);
	final TriggeringPolicy tp = triggeringPolicies[0];
	assertTrue(tp.getClass().getName(), tp instanceof TimeBasedTriggeringPolicy);
	final TimeBasedTriggeringPolicy tbtp = (TimeBasedTriggeringPolicy) tp;
	assertEquals(1, tbtp.getInterval());
	final RolloverStrategy rolloverStrategy = rfa.getManager().getRolloverStrategy();
	assertTrue(rolloverStrategy.getClass().getName(), rolloverStrategy instanceof DefaultRolloverStrategy);
	final DefaultRolloverStrategy drs = (DefaultRolloverStrategy) rolloverStrategy;
	assertEquals(Integer.MAX_VALUE, drs.getMaxIndex());
	configuration.start();
	configuration.stop();
}
 
Example #10
Source File: Main.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
private static void addFileAppender(String logFilename) throws IOException {
  File logFile = new File(logFilename);
  Object ctx = LogManager.getContext(false);
  if (ctx instanceof LoggerContext) {
    try (LoggerContext context = (LoggerContext) ctx) {
      Configuration configuration = context.getConfiguration();
      LoggerConfig loggerConfig = configuration.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
      FileAppender fileAppender =
          FileAppender.newBuilder()
              .setName("file")
              .setLayout(
                  PatternLayout.newBuilder()
                      .withPattern("[%d][%-5.-5p][%-14.-14c{1}:%4L] %-22.-22M - %m%n")
                      .build())
              .withFileName(logFile.getCanonicalPath())
              .build();
      configuration.addAppender(fileAppender);
      loggerConfig.addAppender(fileAppender, Level.ERROR, null);
      context.updateLoggers();
    }
  }
}
 
Example #11
Source File: AsyncAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private LoggerContext configure(String configLocation) throws Exception {
    File file = new File(configLocation);
    InputStream is = new FileInputStream(file);
    ConfigurationSource source = new ConfigurationSource(is, file);
    LoggerContextFactory factory = org.apache.logging.log4j.LogManager.getFactory();
    LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
    Configuration configuration;
    if (configLocation.endsWith(".xml")) {
        configuration = new XmlConfigurationFactory().getConfiguration(context, source);
    } else {
        configuration = new PropertiesConfigurationFactory().getConfiguration(context, source);
    }
    assertNotNull("No configuration created", configuration);
    Configurator.reconfigure(configuration);
    return context;
}
 
Example #12
Source File: CustomJsonLayout.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@PluginFactory
public static CustomJsonLayout createLayout(@PluginConfiguration final Configuration config,
    @PluginAttribute(value = "locationInfo", defaultBoolean = false) final boolean locationInfo,
    @PluginAttribute(value = "properties", defaultBoolean = false) final boolean properties,
    @PluginAttribute(value = "propertiesAsList", defaultBoolean = false) final boolean propertiesAsList,
    @PluginAttribute(value = "complete", defaultBoolean = false) final boolean complete,
    @PluginAttribute(value = "compact", defaultBoolean = false) final boolean compact,
    @PluginAttribute(value = "eventEol", defaultBoolean = false) final boolean eventEol,
    @PluginAttribute(value = "header", defaultString = DEFAULT_HEADER) final String headerPattern,
    @PluginAttribute(value = "footer", defaultString = DEFAULT_FOOTER) final String footerPattern,
    @PluginAttribute(value = "charset", defaultString = "UTF-8") final Charset charset,
    @PluginAttribute(value = "includeStacktrace", defaultBoolean = true) final boolean includeStacktrace,
    @PluginAttribute(value = "stacktraceAsString", defaultBoolean = false) final boolean stacktraceAsString,
    @PluginAttribute(value = "objectMessageAsJsonObject",
        defaultBoolean = false) final boolean objectMessageAsJsonObject) {
    final boolean encodeThreadContextAsList = properties && propertiesAsList;
    return new CustomJsonLayout(config, locationInfo, properties, encodeThreadContextAsList, complete, compact,
        eventEol, headerPattern, footerPattern, charset, includeStacktrace, stacktraceAsString,
        objectMessageAsJsonObject);
}
 
Example #13
Source File: EcsLayout.java    From ecs-logging-java with Apache License 2.0 6 votes vote down vote up
private EcsLayout(Configuration config, String serviceName, String eventDataset, boolean includeMarkers, KeyValuePair[] additionalFields, boolean includeOrigin, boolean stackTraceAsArray) {
    super(config, UTF_8, null, null);
    this.serviceName = serviceName;
    this.eventDataset = eventDataset;
    this.includeMarkers = includeMarkers;
    this.includeOrigin = includeOrigin;
    this.stackTraceAsArray = stackTraceAsArray;
    this.additionalFields = additionalFields;
    fieldValuePatternFormatter = new PatternFormatter[additionalFields.length][];
    for (int i = 0; i < additionalFields.length; i++) {
        KeyValuePair additionalField = additionalFields[i];
        if (additionalField.getValue().contains("%")) {
            fieldValuePatternFormatter[i] = PatternLayout.createPatternParser(config)
                    .parse(additionalField.getValue())
                    .toArray(new PatternFormatter[0]);
        }
    }
}
 
Example #14
Source File: LevelPatternSelector.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Deprecated, use {@link #newBuilder()} instead.
 * @param properties
 * @param defaultPattern
 * @param alwaysWriteExceptions
 * @param noConsoleNoAnsi
 * @param configuration
 * @return a new MarkerPatternSelector.
 * @deprecated Use {@link #newBuilder()} instead.
 */
@Deprecated
public static LevelPatternSelector createSelector(
        final PatternMatch[] properties,
        final String defaultPattern,
        final boolean alwaysWriteExceptions,
        final boolean noConsoleNoAnsi,
        final Configuration configuration) {
    final Builder builder = newBuilder();
    builder.setProperties(properties);
    builder.setDefaultPattern(defaultPattern);
    builder.setAlwaysWriteExceptions(alwaysWriteExceptions);
    builder.setNoConsoleNoAnsi(noConsoleNoAnsi);
    builder.setConfiguration(configuration);
    return builder.build();
}
 
Example #15
Source File: Main.java    From homework_tester with MIT License 6 votes vote down vote up
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 #16
Source File: TestLogLevelAnnotations.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Directly test the methods in the {@link LogLevel} annotation class
 */
@LogLevel("org.apache.solr.bogus_logger.MethodLogLevel=TRACE")
public void testWhiteBoxMethods() {
  final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
  final Configuration config = ctx.getConfiguration();

  final Map<String,Level> oldLevels = LogLevel.Configurer.setLevels(bogus_logger_prefix + "=TRACE");
  //
  assertEquals(oldLevels.toString(), 1, oldLevels.size());
  assertNull(oldLevels.get(bogus_logger_prefix));
  //
  assertEquals(Level.TRACE, config.getLoggerConfig(bogus_logger_prefix).getLevel());
  assertEquals(Level.TRACE, LogManager.getLogger(bogus_logger_prefix).getLevel());
  
  // restore (to 'unset' values)...
  LogLevel.Configurer.restoreLogLevels(oldLevels);
  assertEquals(bogus_logger_prefix
               + " should have had it's config unset; should now return the 'root' LoggerConfig",
               config.getRootLogger(),
               config.getLoggerConfig(bogus_logger_prefix));
  assertEquals(DEFAULT_LOG_LEVEL, LogManager.getLogger(bogus_logger_prefix).getLevel());
  
}
 
Example #17
Source File: CustomConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
public static Configuration addTestFixtures(final String name, final ConfigurationBuilder<BuiltConfiguration> builder) {
    builder.setConfigurationName(name);
    builder.setStatusLevel(Level.ERROR);
    builder.add(builder.newScriptFile("target/test-classes/scripts/filter.groovy").addIsWatched(true));
    builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.NEUTRAL)
            .addAttribute("level", Level.DEBUG));

    final AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
    appenderBuilder.add(builder.
            newLayout("PatternLayout").
            addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable"));
    appenderBuilder.add(builder.
            newFilter("MarkerFilter", Filter.Result.DENY, Filter.Result.NEUTRAL).
            addAttribute("marker", "FLOW"));
    builder.add(appenderBuilder);

    builder.add(builder.newLogger("org.apache.logging.log4j", Level.DEBUG, true).
                add(builder.newAppenderRef("Stdout")).
                addAttribute("additivity", false));
    builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef("Stdout")));

    builder.add(builder.newCustomLevel("Panic", 17));

    return builder.build();
}
 
Example #18
Source File: AppenderRefFailoverPolicyTest.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void resolvesAppenderRefOnlyOnce() {

    // given
    Appender appender = mock(Appender.class);
    when(appender.isStarted()).thenReturn(true);
    Configuration configuration = mock(Configuration.class);
    String testAppenderRef = "testAppenderRef";
    when(configuration.getAppender(testAppenderRef)).thenReturn(appender);

    FailoverPolicy<String> failoverPolicy = createTestFailoverPolicy(testAppenderRef, configuration);

    String failedMessage = "test failed message";

    // when
    failoverPolicy.deliver(failedMessage);
    failoverPolicy.deliver(failedMessage);

    // then
    verify(configuration, times(1)).getAppender(anyString());
    verify(appender, times(2)).append(any(LogEvent.class));
}
 
Example #19
Source File: LoggerNamePatternSelector.java    From TerminalConsoleAppender with MIT License 5 votes vote down vote up
/**
 * Constructs a new {@link LoggerNamePatternSelector}.
 *
 * @param defaultPattern The default pattern to use if no logger name matches
 * @param properties The pattern match rules to use
 * @param alwaysWriteExceptions Write exceptions even if pattern does not
 *     include exception conversion
 * @param disableAnsi If true, disable all ANSI escape codes
 * @param noConsoleNoAnsi If true and {@link System#console()} is null,
 *     disable ANSI escape codes
 * @param config The configuration
 */
protected LoggerNamePatternSelector(String defaultPattern, PatternMatch[] properties,
        boolean alwaysWriteExceptions, boolean disableAnsi, boolean noConsoleNoAnsi, Configuration config) {
    PatternParser parser = PatternLayout.createPatternParser(config);
    PatternFormatter[] emptyFormatters = new PatternFormatter[0];
    this.defaultFormatters = parser.parse(defaultPattern, alwaysWriteExceptions, disableAnsi, noConsoleNoAnsi)
            .toArray(emptyFormatters);
    for (PatternMatch property : properties) {
        PatternFormatter[] formatters = parser.parse(property.getPattern(), alwaysWriteExceptions, disableAnsi, noConsoleNoAnsi)
                .toArray(emptyFormatters);
        for (String name : property.getKey().split(",")) {
            this.formatters.add(new LoggerNameSelector(name, formatters));
        }
    }
}
 
Example #20
Source File: MonitoringModule.java    From curiostack with MIT License 5 votes vote down vote up
private static void configureLogMetrics() {
  InstrumentedAppender appender = InstrumentedAppender.createAppender("PROMETHEUS");
  appender.start();
  LoggerContext context = (LoggerContext) LogManager.getContext(false);
  Configuration config = context.getConfiguration();
  config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).addAppender(appender, null, null);
  context.updateLoggers(config);
}
 
Example #21
Source File: LogConfiguration.java    From wekaDeeplearning4j with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Apply the logging configuration.
 */
public void apply() {
  LoggerContext context = getLoggerContext();
  Configuration config = context.getConfiguration();
  ConfigurationSource configSource = config.getConfigurationSource();
  String packageHomeDir = WekaPackageManager.getPackageHome().getPath();
  if (ConfigurationSource.NULL_SOURCE.equals(configSource)) {
    // Use log4j2.xml shipped with the package ...
    URI uri = Paths.get(packageHomeDir, "wekaDeeplearning4j", "src", "main", "resources",
        "log4j2.xml").toUri();
    context.setConfigLocation(uri);
    log.info("Logging configuration loaded from source: {}", uri.toString());
  }

  String fileAppenderName = "fileAppender";
  if (!context.getRootLogger().getAppenders().containsKey(fileAppenderName)) {
    // Get console appender layout
    Appender consoleAppender = context.getLogger(log.getName()).getAppenders().get("Console");
    Layout<? extends Serializable> layout = consoleAppender.getLayout();

    // Add file appender
    String filePath = resolveLogFilePath();
    FileAppender.Builder appenderBuilder = new FileAppender.Builder();
    appenderBuilder.withFileName(filePath);
    appenderBuilder.withAppend(append);
    appenderBuilder.withName(fileAppenderName);
    appenderBuilder.withLayout(layout);
    FileAppender appender = appenderBuilder.build();
    appender.start();
    context.getRootLogger().addAppender(appender);
  }
}
 
Example #22
Source File: Log4j2LoggerAdapter.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void setLevel(Level level) {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
    loggerConfig.setLevel(toLog4jLevel(level));
    ctx.updateLoggers();
}
 
Example #23
Source File: SyslogAppender.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"resource", "unchecked"})
@Override
public SyslogAppender build() {
    final Protocol protocol = getProtocol();
    final SslConfiguration sslConfiguration = getSslConfiguration();
    final boolean useTlsMessageFormat = sslConfiguration != null || protocol == Protocol.SSL;
    final Configuration configuration = getConfiguration();
    Layout<? extends Serializable> layout = getLayout();
    if (layout == null) {
        layout = RFC5424.equalsIgnoreCase(format)
                ? Rfc5424Layout.createLayout(facility, id, enterpriseNumber, includeMdc, mdcId, mdcPrefix,
                        eventPrefix, newLine, escapeNL, appName, msgId, excludes, includes, required,
                        exceptionPattern, useTlsMessageFormat, loggerFields, configuration)
                :
                // @formatter:off
                SyslogLayout.newBuilder()
                    .setFacility(facility)
                    .setIncludeNewLine(newLine)
                    .setEscapeNL(escapeNL)
                    .setCharset(charsetName)
                    .build();
                // @formatter:off
    }
    final String name = getName();
    if (name == null) {
        LOGGER.error("No name provided for SyslogAppender");
        return null;
    }
    final AbstractSocketManager manager = createSocketManager(name, protocol, getHost(), getPort(), getConnectTimeoutMillis(),
            sslConfiguration, getReconnectDelayMillis(), getImmediateFail(), layout, Constants.ENCODER_BYTE_BUFFER_SIZE, null);

    return new SyslogAppender(name, layout, getFilter(), isIgnoreExceptions(), isImmediateFlush(), manager,
            getAdvertise() ? configuration.getAdvertiser() : null);
}
 
Example #24
Source File: AbstractCustomConfigurationFactoryTemplate.java    From xian with Apache License 2.0 5 votes vote down vote up
private Configuration createConfiguration(final String name, ConfigurationBuilder<BuiltConfiguration> builder) {
    builder.setConfigurationName(name);
    builder.setStatusLevel(Level.ERROR);
    builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.NEUTRAL).addAttribute("level", level()));
    if (isConsoleAppenderEnabled()) {
        AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
        appenderBuilder.add(builder.newLayout("PatternLayout").addAttribute("pattern", "%d [%t] %-5level: %msg [%c][%X{msgId}]%n%throwable"));
        appenderBuilder.add(builder.newFilter("MarkerFilter", Filter.Result.DENY, Filter.Result.NEUTRAL).addAttribute("marker", "FLOW"));
        builder.add(appenderBuilder);
    }
    builder.add(builder.newLogger("org.apache.logging.log4j", Level.DEBUG).add(builder.newAppenderRef("Stdout")).addAttribute("additivity", false));
    builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef("Stdout")));
    return builder.build();
}
 
Example #25
Source File: HighlightErrorConverter.java    From TerminalConsoleAppender with MIT License 5 votes vote down vote up
/**
 * Gets a new instance of the {@link HighlightErrorConverter} with the
 * specified options.
 *
 * @param config The current configuration
 * @param options The pattern options
 * @return The new instance
 */
public static @Nullable HighlightErrorConverter newInstance(Configuration config, String[] options) {
    if (options.length != 1) {
        LOGGER.error("Incorrect number of options on highlightError. Expected 1 received " + options.length);
        return null;
    }
    if (options[0] == null) {
        LOGGER.error("No pattern supplied on highlightError");
        return null;
    }

    PatternParser parser = PatternLayout.createPatternParser(config);
    List<PatternFormatter> formatters = parser.parse(options[0]);
    return new HighlightErrorConverter(formatters);
}
 
Example #26
Source File: Rfc5424Layout.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Create the RFC 5424 Layout.
 *
 * @param facility The Facility is used to try to classify the message.
 * @param id The default structured data id to use when formatting according to RFC 5424.
 * @param enterpriseNumber The IANA enterprise number.
 * @param includeMDC Indicates whether data from the ThreadContextMap will be included in the RFC 5424 Syslog
 *            record. Defaults to "true:.
 * @param mdcId The id to use for the MDC Structured Data Element.
 * @param mdcPrefix The prefix to add to MDC key names.
 * @param eventPrefix The prefix to add to event key names.
 * @param newLine If true, a newline will be appended to the end of the syslog record. The default is false.
 * @param escapeNL String that should be used to replace newlines within the message text.
 * @param appName The value to use as the APP-NAME in the RFC 5424 syslog record.
 * @param msgId The default value to be used in the MSGID field of RFC 5424 syslog records.
 * @param excludes A comma separated list of MDC keys that should be excluded from the LogEvent.
 * @param includes A comma separated list of MDC keys that should be included in the FlumeEvent.
 * @param required A comma separated list of MDC keys that must be present in the MDC.
 * @param exceptionPattern The pattern for formatting exceptions.
 * @param useTlsMessageFormat If true the message will be formatted according to RFC 5425.
 * @param loggerFields Container for the KeyValuePairs containing the patterns
 * @param config The Configuration. Some Converters require access to the Interpolator.
 * @return An Rfc5424Layout.
 */
@PluginFactory
public static Rfc5424Layout createLayout(
        // @formatter:off
        @PluginAttribute(defaultString = "LOCAL0") final Facility facility,
        @PluginAttribute final String id,
        @PluginAttribute(defaultInt = DEFAULT_ENTERPRISE_NUMBER) final int enterpriseNumber,
        @PluginAttribute(defaultBoolean = true) final boolean includeMDC,
        @PluginAttribute(defaultString = DEFAULT_MDCID) final String mdcId,
        @PluginAttribute final String mdcPrefix,
        @PluginAttribute final String eventPrefix,
        @PluginAttribute final boolean newLine,
        @PluginAttribute("newLineEscape") final String escapeNL,
        @PluginAttribute final String appName,
        @PluginAttribute("messageId") final String msgId,
        @PluginAttribute("mdcExcludes") final String excludes,
        @PluginAttribute("mdcIncludes") String includes,
        @PluginAttribute("mdcRequired") final String required,
        @PluginAttribute final String exceptionPattern,
        // RFC 5425
        @PluginAttribute final boolean useTlsMessageFormat,
        @PluginElement final LoggerFields[] loggerFields,
        @PluginConfiguration final Configuration config) {
    // @formatter:on
    if (includes != null && excludes != null) {
        LOGGER.error("mdcIncludes and mdcExcludes are mutually exclusive. Includes wil be ignored");
        includes = null;
    }

    return new Rfc5424Layout(config, facility, id, enterpriseNumber, includeMDC, newLine, escapeNL, mdcId,
            mdcPrefix, eventPrefix, appName, msgId, excludes, includes, required, StandardCharsets.UTF_8,
            exceptionPattern, useTlsMessageFormat, loggerFields);
}
 
Example #27
Source File: AuditLoggerTest.java    From logging-log4j-audit with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setupClass() throws Exception {
    catalogReader = new StringCatalogReader();
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    for (Map.Entry<String, Appender> entry : config.getAppenders().entrySet()) {
        if (entry.getKey().equals("List")) {
            app = (ListAppender) entry.getValue();
            break;
        }
    }
    assertNotNull("No Appender", app);
}
 
Example #28
Source File: AsyncLoggerContext.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void maybeStartHelper(final Configuration config) {
    // If no log4j configuration was found, there are no loggers
    // and there is no point in starting the disruptor (which takes up
    // significant memory and starts a thread).
    if (config instanceof DefaultConfiguration) {
        StatusLogger.getLogger().debug("[{}] Not starting Disruptor for DefaultConfiguration.", getName());
    } else {
        loggerDisruptor.start();
    }
}
 
Example #29
Source File: LogUtil.java    From ldbc_graphalytics with Apache License 2.0 5 votes vote down vote up
public static void appendSimplifiedConsoleLogger(Level level) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    Layout layout = PatternLayout.createLayout("%msg%n", null, config, null, null, true, false, null, null);
    Appender appender = ConsoleAppender.createAppender(layout, null, ConsoleAppender.Target.SYSTEM_OUT, "stdout", true, true);
    appender.start();

    config.getRootLogger().addAppender(appender, level, null);
    ctx.updateLoggers();
}
 
Example #30
Source File: Log4JController.java    From GreenSummer with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Unset.
 *
 * @param name
 *        the name
 * @return the response entity
 */
@RequestMapping(value = "unset/{name}/", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET,
    headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<LogResponse> unset(@PathVariable("name")
final String name) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    synchronized (ctx) {
        final Configuration config = ctx.getConfiguration();
        config.removeLogger(name);
        ctx.updateLoggers();
    }
    return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK);
}