Java Code Examples for org.apache.logging.log4j.Level

The following examples show how to use org.apache.logging.log4j.Level. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: flogger   Source File: Log4j2Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testLevels() {
  backend.log(FakeLogData.of("finest").setLevel(java.util.logging.Level.FINEST));
  backend.log(FakeLogData.of("finer").setLevel(java.util.logging.Level.FINER));
  backend.log(FakeLogData.of("fine").setLevel(java.util.logging.Level.FINE));
  backend.log(FakeLogData.of("config").setLevel(java.util.logging.Level.CONFIG));
  backend.log(FakeLogData.of("info").setLevel(java.util.logging.Level.INFO));
  backend.log(FakeLogData.of("warning").setLevel(java.util.logging.Level.WARNING));
  backend.log(FakeLogData.of("severe").setLevel(java.util.logging.Level.SEVERE));

  assertLogCount(7);
  assertLogEntry(0, TRACE, "finest");
  assertLogEntry(1, TRACE, "finer");
  assertLogEntry(2, DEBUG, "fine");
  assertLogEntry(3, DEBUG, "config");
  assertLogEntry(4, INFO, "info");
  assertLogEntry(5, WARN, "warning");
  assertLogEntry(6, ERROR, "severe");
}
 
Example 2
Source Project: logging-log4j2   Source File: SLF4JLogger.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Level getLevel() {
    if (logger.isTraceEnabled()) {
        return Level.TRACE;
    }
    if (logger.isDebugEnabled()) {
        return Level.DEBUG;
    }
    if (logger.isInfoEnabled()) {
        return Level.INFO;
    }
    if (logger.isWarnEnabled()) {
        return Level.WARN;
    }
    if (logger.isErrorEnabled()) {
        return Level.ERROR;
    }
    // Option: throw new IllegalStateException("Unknown SLF4JLevel");
    // Option: return Level.ALL;
    return Level.OFF;
}
 
Example 3
Source Project: ambari-logsearch   Source File: OutputKafka.java    License: Apache License 2.0 6 votes vote down vote up
public void onCompletion(RecordMetadata metadata, Exception exception) {
  if (metadata != null) {
    if (!output.isKafkaBrokerUp) {
      logger.info("Started writing to kafka. " + output.getShortDescription());
      output.isKafkaBrokerUp = true;
    }
    output.incrementStat(1);
    output.writeBytesMetric.value += message.length();
  } else {
    output.isKafkaBrokerUp = false;
    String logKeyMessage = this.getClass().getSimpleName() + "_KAFKA_ASYNC_ERROR";
    LogFeederUtil.logErrorMessageByInterval(logKeyMessage, "Error sending message to Kafka. Async Callback", exception, logger,
        Level.ERROR);

    output.failedMessages.add(this);
  }
}
 
Example 4
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 5
public void setupModule(final SetupContext context, final boolean includeStacktrace,
        final boolean stacktraceAsString) {
    // JRE classes: we cannot edit those with Jackson annotations
    context.setMixInAnnotations(StackTraceElement.class, StackTraceElementMixIn.class);
    // Log4j API classes: we do not want to edit those with Jackson annotations because the API module should not
    // depend on Jackson.
    context.setMixInAnnotations(Marker.class, MarkerMixIn.class);
    context.setMixInAnnotations(Level.class, LevelMixIn.class);
    context.setMixInAnnotations(Instant.class, InstantMixIn.class);
    context.setMixInAnnotations(LogEvent.class, LogEventJsonMixIn.class); // different ThreadContext handling
    // Log4j Core classes: we do not want to bring in Jackson at runtime if we do not have to.
    context.setMixInAnnotations(ExtendedStackTraceElement.class, ExtendedStackTraceElementMixIn.class);
    context.setMixInAnnotations(ThrowableProxy.class, includeStacktrace
            ? (stacktraceAsString ? ThrowableProxyWithStacktraceAsStringMixIn.class : ThrowableProxyMixIn.class)
            : ThrowableProxyWithoutStacktraceMixIn.class);
}
 
Example 6
Source Project: logging-log4j2   Source File: XIncludeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testLogger() throws Exception {
    final Logger logger = this.ctx.getLogger(LOGGER_NAME);
    assertThat(logger, is(instanceOf(org.apache.logging.log4j.core.Logger.class)));
    final org.apache.logging.log4j.core.Logger l = (org.apache.logging.log4j.core.Logger) logger;
    assertThat(l.getLevel(), is(equalTo(Level.DEBUG)));
    assertThat(l.filterCount(), is(equalTo(1)));
    final Iterator<Filter> iterator = l.getFilters();
    assertThat(iterator.hasNext(), is(true));
    final Filter filter = iterator.next();
    assertThat(filter, is(instanceOf(ThreadContextMapFilter.class)));
    final Map<String, Appender> appenders = l.getAppenders();
    assertThat(appenders, is(notNullValue()));
    assertThat(appenders, hasSize(1));
    final Appender appender = appenders.get(APPENDER_NAME);
    assertThat(appender, is(notNullValue()));
    assertThat(appender.getName(), is(equalTo("STDOUT")));
}
 
Example 7
Source Project: core-ng-project   Source File: ESLoggerConfigFactory.java    License: Apache License 2.0 6 votes vote down vote up
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 8
@Test
public void testPatternAndParameterizedMessageDateLookup() throws Exception {
    final MessagePatternConverter converter = MessagePatternConverter.newInstance(null, null);
    final Message msg = new ParameterizedMessage("${date:now:buhu}");
    final LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName("MyLogger") //
            .setLevel(Level.DEBUG) //
            .setMessage(msg).build();
    final StringBuilder sb = new StringBuilder();
    converter.format(event, sb);
    assertEquals("Unexpected result", "${date:now:buhu}", sb.toString());
}
 
Example 9
Source Project: logging-log4j2   Source File: AbstractLogger.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final String message,
        final Supplier<?>... paramSuppliers) {
    if (isEnabled(level, marker, message)) {
        logMessage(fqcn, level, marker, message, paramSuppliers);
    }
}
 
Example 10
Source Project: jesterj   Source File: FailWithExceptionConfig.java    License: Apache License 2.0 5 votes vote down vote up
public Plan getPlan() {
  PlanImpl.Builder planBuilder = new PlanImpl.Builder();
  SimpleFileWatchScanner.Builder scanner = new SimpleFileWatchScanner.Builder();
  StepImpl.Builder logAndFail = new StepImpl.Builder();

  File testDocs = new File("data");

  scanner
      .named(SHAKESPEARE)
      .withRoot(testDocs)
      .scanFreqMS(100);
  logAndFail
      .named("logAndFailStep")
      .withProcessor(new LogAndFail.Builder()
          .named("logAndFailProcessor")
          .withLogLevel(Level.ERROR)
          .after(5)
          .throwing(new RuntimeException("BOOM")));


  planBuilder
      .named("myPlan")
      .withIdField("id")
      .addStep(scanner)
      .addStep(logAndFail, SHAKESPEARE)
  ;
  return planBuilder.build();

}
 
Example 11
Source Project: samza   Source File: TestStreamAppender.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSystemProducerAppenderInContainer() throws InterruptedException {
  System.setProperty("samza.container.name", "samza-container-1");

  PatternLayout layout = PatternLayout.newBuilder().withPattern("%m").build();
  MockSystemProducerAppender systemProducerAppender = MockSystemProducerAppender.createAppender("testName", null, layout, false, null, null);
  systemProducerAppender.start();

  log.addAppender(systemProducerAppender);
  log.setLevel(Level.INFO);
  List<String> messages = Lists.newArrayList("testing1", "testing2");
  logAndVerifyMessages(messages);
  systemProducerAppender.stop();
}
 
Example 12
Source Project: simpleretrogen   Source File: TestGenerator.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Mod.EventHandler
public void preinit(FMLPreInitializationEvent init)
{
    final Logger modLog = init.getModLog();
    IWorldGenerator gen = new IWorldGenerator() {
        @Override
        public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider)
        {
            modLog.log(Level.INFO, "Calling!");
        }
    };
    GameRegistry.registerWorldGenerator(gen, 10);
}
 
Example 13
Source Project: logging-log4j2   Source File: PatternLayoutTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testMdcPattern(final String patternStr, final String expectedStr, final boolean useThreadContext)
        throws Exception {
    final PatternLayout layout = PatternLayout.newBuilder().setPattern(patternStr)
            .setConfiguration(ctx.getConfiguration()).build();
    if (useThreadContext) {
        ThreadContext.put("key1", "value1");
        ThreadContext.put("key2", "value2");
    }
    final LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName(this.getClass().getName()).setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
            .setLevel(Level.INFO) //
            .setMessage(new SimpleMessage("Hello")).build();
    assertToByteArray(expectedStr, layout, event);
    assertEncode(expectedStr, layout, event);
}
 
Example 14
Source Project: logging-log4j2   Source File: AbstractFilterableTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAddCompositeFilter() throws Exception {
    final Filter filter1 = ThresholdFilter.createFilter(Level.ERROR, null, null);
    final Filter filter2 = ThresholdFilter.createFilter(Level.ERROR, null, null);
    final Filter compositeFilter = CompositeFilter.createFilters(new Filter[] {filter1, filter2});

    filterable.addFilter(compositeFilter);
    assertSame(compositeFilter, filterable.getFilter());
}
 
Example 15
Source Project: pulsar   Source File: SourceApiV3ResourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = RestException.class, expectedExceptionsMessageRegExp = "Source test-source already exists")
public void testRegisterExistedSource() throws IOException {
    try {
        Configurator.setRootLevel(Level.DEBUG);

        when(mockedManager.containsFunction(eq(tenant), eq(namespace), eq(source))).thenReturn(true);

        registerDefaultSource();
    } catch (RestException re){
        assertEquals(re.getResponse().getStatusInfo(), Response.Status.BAD_REQUEST);
        throw re;
    }
}
 
Example 16
Source Project: Flashtool   Source File: TextAreaAppender.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
  * This method is where the appender does the work.
  *
  * @param event Log event with log data
  */
 @Override
 public void append(LogEvent event) {
   readLock.lock();
   String message = new String(getLayout().toByteArray(event));
   Level l = event.getLevel();
if (styledText!=null) {
	StyleRange styleRange = new StyleRange();
	if (l==Level.ERROR) {
		styleRange.length = message.length();
		styleRange.fontStyle = SWT.NORMAL;
		styleRange.foreground = cred;
		
	}
	else if (l==Level.WARN) {
		styleRange.length = message.length();
		styleRange.fontStyle = SWT.NORMAL;
		styleRange.foreground = cblue;
	}
	else {
		
		styleRange.length = message.length();
		styleRange.fontStyle = SWT.NORMAL;
		styleRange.foreground = cblack;
	}
	Display.getDefault().asyncExec(new Runnable() {
		public void run() {
			// Append formatted message to textarea.
			styleRange.start = styledText.getCharCount();
			styledText.append(message);
			styledText.setStyleRange(styleRange);
			styledText.setSelection(styledText.getCharCount());
		}
	});
}
readLock.unlock();
 }
 
Example 17
Source Project: Mixin   Source File: ModifyConstantInjector.java    License: MIT License 5 votes vote down vote up
private void checkNarrowing(Target target, AbstractInsnNode constNode, Type constantType, Type type, int index, String description) {
    int fromSort = constantType.getSort();
    int toSort = type.getSort();
    if (toSort < fromSort) {
        String fromType = SignaturePrinter.getTypeName(constantType, false);
        String toType = SignaturePrinter.getTypeName(type, false);
        String message = toSort == Type.BOOLEAN ? ". Implicit conversion to <boolean> can cause nondeterministic (JVM-specific) behaviour!" : "";
        Level level = toSort == Type.BOOLEAN ? Level.ERROR : Level.WARN;
        Injector.logger.log(level, "Narrowing conversion of <{}> to <{}> in {} target {} at opcode {} ({}){}", fromType, toType, this.info,
                target, index, description, message);
    }
}
 
Example 18
@Override
public Object onTraversalSuccess() {
    logger.log(Level.INFO, "Collecting read counts done.");
    logger.log(Level.INFO, "Writing counts ...");
    final long[] columnTotals = calculateColumnTotals();

    IntStream.range(0, targetCollection.targetCount()).forEach(target -> {
        final int[] countBuffer = IntStream.range(0, counts.length).map(column -> counts[column][target]).toArray();
        writeOutputRows(countBuffer, columnTotals, target);
    });
    logger.log(Level.INFO, "Writing counts done.");

    writeColumnSummaryOutput();
    return "SUCCESS";
}
 
Example 19
Source Project: logging-log4j2   Source File: EventLookupTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testLookupEventLogger() {
    String msg = "Hello, world!";
    final LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName(this.getClass().getName()) //
            .setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
            .setLevel(Level.INFO) //
            .setMessage(new SimpleMessage(msg)).build();
    final String value = strLookup.lookup(event, "Logger");
    assertEquals(this.getClass().getName(), value);
}
 
Example 20
Source Project: logging-log4j2   Source File: LevelMatchFilterBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private Filter createFilter(String level, boolean acceptOnMatch) {
    Level lvl = Level.ERROR;
    if (level != null) {
        lvl = Level.toLevel(level, Level.ERROR);
    }
    org.apache.logging.log4j.core.Filter.Result onMatch = acceptOnMatch
            ? org.apache.logging.log4j.core.Filter.Result.ACCEPT
            : org.apache.logging.log4j.core.Filter.Result.DENY;
    return new FilterWrapper(LevelMatchFilter.newBuilder()
            .setLevel(lvl)
            .setOnMatch(onMatch)
            .setOnMismatch(org.apache.logging.log4j.core.Filter.Result.NEUTRAL)
            .build());
}
 
Example 21
Source Project: logging-log4j2   Source File: AbstractLogger.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void logIfEnabled(final String fqcn, final Level level, final Marker marker, final Message msg,
        final Throwable t) {
    if (isEnabled(level, marker, msg, t)) {
        logMessageSafely(fqcn, level, marker, msg, t);
    }
}
 
Example 22
Source Project: logging-log4j2   Source File: LevelMatchFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
        final Object p0, final Object p1, final Object p2, final Object p3,
        final Object p4, final Object p5, final Object p6,
        final Object p7, final Object p8, final Object p9) {
    return filter(level);
}
 
Example 23
Source Project: logging-log4j2   Source File: Logger.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void logMessage(final String fqcn, final Level level, final Marker marker, final Message message,
        final Throwable t) {
    final Message msg = message == null ? new SimpleMessage(Strings.EMPTY) : message;
    final ReliabilityStrategy strategy = privateConfig.loggerConfig.getReliabilityStrategy();
    strategy.log(this, getName(), fqcn, marker, level, msg, t);
}
 
Example 24
Source Project: jmeter-debugger   Source File: LoggerPanelAppender.java    License: Apache License 2.0 5 votes vote down vote up
public LoggerPanelAppender(String name, LoggerPanelWrapping panelWrapping) {
    super(name, null, PatternLayout.newBuilder().withPattern(DEFAULT_PATTERN).build());
    start();
    Configuration configuration = ((LoggerContext) LogManager.getContext(false)).getConfiguration();
    configuration.getRootLogger().addAppender(this, Level.INFO, null);
    this.panelWrapping = panelWrapping;
    initializeProcessLogEventMethod();
    initializeLogEventObjectConstructor();
}
 
Example 25
Source Project: logging-log4j2   Source File: DynamicThresholdFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
        final Object p0, final Object p1, final Object p2, final Object p3,
        final Object p4, final Object p5, final Object p6,
        final Object p7) {
    return filter(level, currentContextData());
}
 
Example 26
Source Project: logging-log4j2   Source File: XmlLayoutTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testLayoutLoggerName() {
    final XmlLayout layout = XmlLayout.newBuilder().setLocationInfo(false).setProperties(true).setComplete(true)
            .setCompact(false).setIncludeStacktrace(true).build();

    final Log4jLogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName("a.B") //
            .setLoggerFqcn("f.q.c.n") //
            .setLevel(Level.DEBUG) //
            .setMessage(new SimpleMessage("M")) //
            .setThreadName("threadName") //
            .setTimeMillis(1).build();
    final String str = layout.toSerializable(event);
    assertTrue(str, str.contains("loggerName=\"a.B\""));
}
 
Example 27
Source Project: logging-log4j2   Source File: Configurator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets a logger's level.
 *
 * @param loggerName
 *            the logger name
 * @param level
 *            the new level
 */
public static void setLevel(final String loggerName, final Level level) {
    final LoggerContext loggerContext = LoggerContext.getContext(false);
    if (Strings.isEmpty(loggerName)) {
        setRootLevel(level);
    } else {
        if (setLevel(loggerName, level, loggerContext.getConfiguration())) {
            loggerContext.updateLoggers();
        }
    }
}
 
Example 28
Source Project: wailanbt   Source File: LogHelper.java    License: MIT License 4 votes vote down vote up
public static void off(Object object)
{
    log(Level.OFF, object);
}
 
Example 29
Source Project: logging-log4j2   Source File: LoggerBufferedReader.java    License: Apache License 2.0 4 votes vote down vote up
protected LoggerBufferedReader(final Reader reader, final ExtendedLogger logger, final String fqcn,
                               final Level level, final Marker marker) {
    super(reader);
    this.reader = new InternalBufferedReader(reader, logger, fqcn == null ? FQCN: fqcn, level, marker);
}
 
Example 30
Source Project: logging-log4j2   Source File: Log4jLogger.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void error(final String format) {
    logger.logIfEnabled(FQCN, Level.ERROR, null, format);
}