org.apache.logging.log4j.core.Logger Java Examples

The following examples show how to use org.apache.logging.log4j.core.Logger. 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 vote down vote up
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: PatternParserTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPatternTruncateFromEnd() {
    final List<PatternFormatter> formatters = parser.parse(patternTruncateFromEnd);
    assertNotNull(formatters);
    final LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName("org.apache.logging.log4j.PatternParserTest") //
            .setLoggerFqcn(Logger.class.getName()) //
            .setLevel(Level.INFO) //
            .setMessage(new SimpleMessage("Hello, world")) //
            .setThreadName("Thread1") //
            .setTimeMillis(System.currentTimeMillis()) //
            .build();
    final StringBuilder buf = new StringBuilder();
    for (final PatternFormatter formatter : formatters) {
        formatter.format(event, buf);
    }
    final String str = buf.toString();
    final String expected = "INFO  org.a Hello, world" + Strings.LINE_SEPARATOR;
    assertTrue("Expected to end with: " + expected + ". Actual: " + str, str.endsWith(expected));
}
 
Example #3
Source File: ValidationVisitorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidationErrorsAreLogged() {
    Kafka k = TestUtils.fromYaml("/example.yaml", Kafka.class, true);
    assertThat(k, is(notNullValue()));
    TestLogger logger = new TestLogger((Logger) LogManager.getLogger(ValidationVisitorTest.class));
    HasMetadata resource = new KafkaBuilder()
            .withNewMetadata()
                .withName("testname")
                .withNamespace("testnamespace")
            .endMetadata()
            .withApiVersion("v1alpha1")
        .build();
    ResourceVisitor.visit(k, new ValidationVisitor(resource, logger));
    logger.assertLoggedAtLeastOnce(lm -> lm.level() == Level.WARN
        && ("Kafka resource testname in namespace testnamespace: " +
            "Contains object at path spec.kafka with an unknown property: foo").equals(lm.formattedMessage()));
    logger.assertLoggedAtLeastOnce(lm -> lm.level() == Level.WARN
            && ("Kafka resource testname in namespace testnamespace: " +
            "In API version v1alpha1 the property topicOperator at path spec.topicOperator has been deprecated. " +
            "This feature should now be configured at path spec.entityOperator.topicOperator.").equals(lm.formattedMessage()));
    logger.assertNotLogged(lm -> lm.level() == Level.WARN
            && ("Kafka resource testname in namespace testnamespace: " +
            "In API version v1alpha1 the property tolerations at path spec.zookeeper.tolerations has been deprecated. " +
            "This feature should now be configured at path spec.zookeeper.template.pod.tolerations.").equals(lm.formattedMessage()));
}
 
Example #4
Source File: ConsoleShellFactory.java    From Bukkit-SSHD with Apache License 2.0 6 votes vote down vote up
public void start(Environment env) throws IOException {
    try {
        consoleReader = new ConsoleReader(in, new FlushyOutputStream(out), new SshTerminal());
        consoleReader.setExpandEvents(true);
        consoleReader.addCompleter(new ConsoleCommandCompleter());

        StreamHandler streamHandler = new FlushyStreamHandler(out, new ConsoleLogFormatter(), consoleReader);
        streamHandlerAppender = new StreamHandlerAppender(streamHandler);

        ((Logger) LogManager.getRootLogger()).addAppender(streamHandlerAppender);

        environment = env;
        thread = new Thread(this, "SSHD ConsoleShell " + env.getEnv().get(Environment.ENV_USER));
        thread.start();
    } catch (Exception e) {
        throw new IOException("Error starting shell", e);
    }
}
 
Example #5
Source File: OpenCensusLog4jLogCorrelationTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void addBlankSpanToLogEntryWithAllSpans() {
  String log =
      logWithSpanAndLog4jConfiguration(
          TEST_PATTERN,
          SpanContext.INVALID,
          new Function<Logger, Void>() {
            @Override
            public Void apply(Logger logger) {
              logger.fatal("message #3");
              return null;
            }
          });
  assertThat(log)
      .isEqualTo(
          "traceId=00000000000000000000000000000000 spanId=0000000000000000 sampled=false FATAL "
              + "- message #3");
}
 
Example #6
Source File: CsvParameterLayoutTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testLogJsonArgument() throws InterruptedException {
    final ListAppender appender = (ListAppender) init.getAppender("List");
    appender.countDownLatch = new CountDownLatch(4);
    appender.clear();
    final Logger logger = (Logger) LogManager.getRootLogger();
    final String json = "{\"id\":10,\"name\":\"Alice\"}";
    logger.error("log:{}", json);
    // wait until background thread finished processing
    final int msgCount = 1;
    if (appender.getMessages().size() < msgCount) {
        appender.countDownLatch.await(5, TimeUnit.SECONDS);
    }
    assertEquals("Background thread did not finish processing: msg count", msgCount, appender.getMessages().size());

    // don't stop appender until background thread is done
    appender.stop();
    final List<String> list = appender.getMessages();
    final String eventStr = list.get(0).toString();
    Assert.assertTrue(eventStr, eventStr.contains(json));
}
 
Example #7
Source File: Log4j2BackendFactory.java    From flogger with Apache License 2.0 5 votes vote down vote up
@Override
public LoggerBackend create(String loggingClassName) {
  // Compute the logger name exactly the same way as in SimpleBackendFactory.
  // The logger name must match the name of the logging class so that we can return it from
  // Log4j2LoggerBackend#getLoggerName().
  // We cast org.apache.logging.log4j.core.Logger here so that
  // we can access the methods only avilable under org.apache.logging.log4j.core.Logger.
  // TODO(b/27920233): Strip inner/nested classes when deriving logger name.
  Logger logger = (Logger) LogManager.getLogger(loggingClassName.replace('$', '.'));
  return new Log4j2LoggerBackend(logger);
}
 
Example #8
Source File: Log4JFilter.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Result filter(Logger logger, Level level, Marker marker, Object msg, Throwable t) {
    String candidate = null;
    if (msg != null) {
        candidate = msg.toString();
    }
    return validateMessage(candidate);
}
 
Example #9
Source File: PatternParserTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBadPattern() {
    final Calendar cal = Calendar.getInstance();
    cal.set(2001, Calendar.FEBRUARY, 3, 4, 5, 6);
    cal.set(Calendar.MILLISECOND, 789);
    final long timestamp = cal.getTimeInMillis();

    final List<PatternFormatter> formatters = parser.parse(badPattern);
    assertNotNull(formatters);
    final Throwable t = new Throwable();
    final StackTraceElement[] elements = t.getStackTrace();
    final LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName("a.b.c") //
            .setLoggerFqcn(Logger.class.getName()) //
            .setLevel(Level.INFO) //
            .setMessage(new SimpleMessage("Hello, world")) //
            .setThreadName("Thread1") //
            .setSource(elements[0]) //
            .setTimeMillis(timestamp) //
            .build();
    final StringBuilder buf = new StringBuilder();
    for (final PatternFormatter formatter : formatters) {
        formatter.format(event, buf);
    }
    final String str = buf.toString();

    // eats all characters until the closing '}' character
    final String expected = "[2001-02-03 04:05:06,789] - Hello, world";
    assertTrue("Expected to start with: " + expected + ". Actual: " + str, str.startsWith(expected));
}
 
Example #10
Source File: HttpWebConnectionTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
@Alerts(DEFAULT = "Host",
        IE = {})
public void hostHeaderFirst() throws Exception {
    final Logger logger = (Logger) LogManager.getLogger("org.apache.http.headers");
    final Level oldLevel = logger.getLevel();
    Configurator.setLevel(logger.getName(), Level.DEBUG);

    final StringWriter stringWriter = new StringWriter();
    final PatternLayout layout = PatternLayout.newBuilder().withPattern("%msg%n").build();

    final WriterAppender writerAppender = WriterAppender.newBuilder().setName("writeLogger").setTarget(stringWriter)
            .setLayout(layout).build();
    writerAppender.start();

    logger.addAppender(writerAppender);
    try {
        startWebServer("./");

        final WebClient webClient = getWebClient();
        webClient.getPage(URL_FIRST + "LICENSE.txt");
        final String[] messages = StringUtils.split(stringWriter.toString(), "\n");
        for (int i = 0; i < getExpectedAlerts().length; i++) {
            assertTrue(messages[i + 1].contains(getExpectedAlerts()[i]));
        }
    }
    finally {
        logger.removeAppender(writerAppender);
        Configurator.setLevel(logger.getName(), oldLevel);
    }
}
 
Example #11
Source File: FlumeAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    eventSource = new AvroSource();
    channel = new MemoryChannel();

    Configurables.configure(channel, new Context());

    avroLogger = (Logger) LogManager.getLogger("avrologger");
    /*
     * Clear out all other appenders associated with this logger to ensure
     * we're only hitting the Avro appender.
     */
    removeAppenders(avroLogger);
    final Context context = new Context();
    testPort = String.valueOf(AvailablePortFinder.getNextAvailable());
    context.put("port", testPort);
    context.put("bind", "0.0.0.0");
    Configurables.configure(eventSource, context);

    final List<Channel> channels = new ArrayList<>();
    channels.add(channel);

    final ChannelSelector cs = new ReplicatingChannelSelector();
    cs.setChannels(channels);

    eventSource.setChannelProcessor(new ChannelProcessor(cs));

    eventSource.start();

    Assert.assertTrue("Reached start or error", LifecycleController
            .waitForOneOf(eventSource, LifecycleState.START_OR_ERROR));
    Assert.assertEquals("Server is started", LifecycleState.START,
            eventSource.getLifecycleState());
}
 
Example #12
Source File: DenyAllFilter.java    From logging-log4j2 with 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) {
    return Result.DENY;
}
 
Example #13
Source File: NoMarkerFilter.java    From logging-log4j2 with 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(marker);
}
 
Example #14
Source File: LoggingStrategyFunctionalTest.java    From pocket-etl with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    logger = (Logger) LogManager.getRootLogger();
    appender = OutputStreamAppender.newBuilder().setName("Appender").setTarget(out).build();
    appender.start();
    logger.addAppender(appender);
    logger.setLevel(Level.INFO);
}
 
Example #15
Source File: BurstFilter.java    From logging-log4j2 with 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) {
    return filter(level);
}
 
Example #16
Source File: Log4j2LevelSetter.java    From summerframework with Apache License 2.0 5 votes vote down vote up
@Override
public void setLoggerLevel(String name, String level) {
    Collection<Logger> notCurrentLoggerCollection =
        org.apache.logging.log4j.core.LoggerContext.getContext(false).getLoggers();
    Collection<org.apache.logging.log4j.core.Logger> currentLoggerCollection =
        org.apache.logging.log4j.core.LoggerContext.getContext().getLoggers();
    Collection<org.apache.logging.log4j.core.Logger> loggerCollection = notCurrentLoggerCollection;
    loggerCollection.addAll(currentLoggerCollection);
    for (org.apache.logging.log4j.core.Logger logger : loggerCollection) {
        if (name.equals(logger.getName())) {
            logger.setLevel(org.apache.logging.log4j.Level.toLevel(level));
        }
    }
}
 
Example #17
Source File: ThresholdFilter.java    From logging-log4j2 with 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) {
    return filter(level);
}
 
Example #18
Source File: ThresholdFilter.java    From logging-log4j2 with 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);
}
 
Example #19
Source File: ThreadContextMapFilter.java    From logging-log4j2 with 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();
}
 
Example #20
Source File: NoMarkerFilter.java    From logging-log4j2 with 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) {
    return filter(marker);
}
 
Example #21
Source File: ThreadContextMapFilter.java    From logging-log4j2 with 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();
}
 
Example #22
Source File: JdaFilter.java    From DiscordSRV with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Result filter(Logger logger, Level level, Marker marker, String message, Object... parameters) {
    return check(
            logger.getName(),
            level,
            message,
            null);
}
 
Example #23
Source File: LogConfiguration.java    From wekaDeeplearning4j with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Update the weka dl4j log level.
 */
protected void updateWekaDl4jLogLevel() {
  LoggerContext context = getLoggerContext();
  Collection<Logger> loggers = context.getLoggers();
  for (Logger logger : loggers) {
    if (logger.getName().startsWith("weka")) {
      updateLogLevel(logger.getName(), wekaDl4jLogLevel);
    }
  }
}
 
Example #24
Source File: LevelMatchFilter.java    From logging-log4j2 with 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 #25
Source File: DenyAllFilter.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
                     final Object... params) {
    return Result.DENY;
}
 
Example #26
Source File: MapFilter.java    From logging-log4j2 with Apache License 2.0 4 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) {
    return Result.NEUTRAL;
}
 
Example #27
Source File: ConsoleShellFactory.java    From Bukkit-SSHD with Apache License 2.0 4 votes vote down vote up
public void destroy() {
    ((Logger) LogManager.getRootLogger()).removeAppender(streamHandlerAppender);
}
 
Example #28
Source File: NoMarkerFilter.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
                     final Object p0) {
    return filter(marker);
}
 
Example #29
Source File: DynamicThresholdFilter.java    From logging-log4j2 with Apache License 2.0 4 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) {
    return filter(level, currentContextData());
}
 
Example #30
Source File: MarkerFilter.java    From logging-log4j2 with Apache License 2.0 4 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) {
    return filter(marker);
}