org.apache.logging.log4j.core.appender.WriterAppender Java Examples

The following examples show how to use org.apache.logging.log4j.core.appender.WriterAppender. 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: 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 #2
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 #3
Source File: DebugFrameImplTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
void loggedCalls() throws Exception {
    final URL url = getClass().getResource("debugFrameImplTest.html");
    final String expectedLog = IOUtils.toString(getClass().getResourceAsStream("debugFrameImplTest.txt"),
            ISO_8859_1);

    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();

    loggerDebugFrameImpl_.addAppender(writerAppender);
    try {
        client_.getPage(url);
    }
    finally {
        loggerDebugFrameImpl_.removeAppender(writerAppender);
    }

    assertEquals(expectedLog, stringWriter.toString());
}
 
Example #4
Source File: Log4j2LoggingHelper.java    From herd with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: S2STestService.java    From Openfire with Apache License 2.0 6 votes vote down vote up
String addAppender(final Writer writer) {
    final String name = "openfire-s2s-test-appender-" + StringUtils.randomString( 10 );
    final LoggerContext context = LoggerContext.getContext(false);
    final Configuration config = context.getConfiguration();
    final PatternLayout layout = PatternLayout.createDefaultLayout(config);
    final Appender appender = WriterAppender.createAppender(layout, null, writer, name, false, true);
    appender.start();
    config.addAppender(appender);

    final Level level = null;
    final Filter filter = null;
    for (final LoggerConfig loggerConfig : config.getLoggers().values()) {
        loggerConfig.addAppender(appender, level, filter);
    }
    config.getRootLogger().addAppender(appender, level, filter);
    return name;
}
 
Example #6
Source File: LoggerStringWriter.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private static void removeWriterAppender(final LoggerContext context) {
    final Configuration config = context.getConfiguration();
    LoggerConfig rootConfig = config.getRootLogger();
    // Stopping the logger is subject to race conditions where logging during cleanup on global executor
    // may still try to log and raise an error.
    WriterAppender writerAppender = (WriterAppender) rootConfig.getAppenders().get(APPENDER_NAME);
    if (writerAppender != null) {
        writerAppender.stop(0, NANOSECONDS);
    }
    // Don't remove directly from map, because the root logger also cleans up filters.
    rootConfig.removeAppender(APPENDER_NAME);
}
 
Example #7
Source File: DefaultCredentialsProvider2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that on calling the website twice, only the first time unauthorized response is returned.
 *
 * @throws Exception if an error occurs
 */
@Test
public void basicAuthentication_singleAuthenticaiton() 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 {
        ((DefaultCredentialsProvider) getWebClient().getCredentialsProvider()).addCredentials("jetty", "jetty");

        loadPage("Hi There");
        int unauthorizedCount = StringUtils.countMatches(stringWriter.toString(), "HTTP/1.1 401");
        assertEquals(1, unauthorizedCount);

        // and again
        loadPage("Hi There");
        unauthorizedCount = StringUtils.countMatches(stringWriter.toString(), "HTTP/1.1 401");
        assertEquals(1, unauthorizedCount);
    }
    finally {
        logger.removeAppender(writerAppender);
        Configurator.setLevel(logger.getName(), oldLevel);
    }
}
 
Example #8
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 #9
Source File: UserMgtFailureAuditLoggerTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void initMethod() {

    out = new ByteArrayOutputStream();
    writer = new PrintWriter(out);
    PatternLayout layout = PatternLayout.createDefaultLayout();
    appender = WriterAppender.newBuilder().setName("writeLogger").setTarget(writer).setLayout(layout).build();
    appender.start();
    logger.addAppender(appender);
    userMgtFailureAuditLogger = spy(UserMgtFailureAuditLogger.class);
    when(userMgtFailureAuditLogger.isEnable()).thenReturn(true);
}
 
Example #10
Source File: RequestLoggingTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Before
public void setupAppender() {
  LoggerContext ctx = (LoggerContext) LogManager.getContext(false);

  writer = new StringWriter();
  appender = WriterAppender.createAppender(
    PatternLayout
      .newBuilder()
      .withPattern("%-5p [%t]: %m%n")
      .build(),
      null, writer, "RequestLoggingTest", false, true);
  appender.start();

}
 
Example #11
Source File: CLogOut.java    From TweetwallFX with MIT License 4 votes vote down vote up
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);
}