Java Code Examples for org.apache.logging.log4j.core.Logger#addAppender()
The following examples show how to use
org.apache.logging.log4j.core.Logger#addAppender() .
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: AbstractADTest.java From anomaly-detection with Apache License 2.0 | 6 votes |
/** * Set up test with junit that a warning was logged with log4j */ protected void setUpLog4jForJUnit(Class<?> cls) { String loggerName = toLoggerName(callerClass(cls)); logger = (Logger) LogManager.getLogger(loggerName); testAppender = new TestAppender(loggerName); testAppender.start(); logger.addAppender(testAppender); logger.setLevel(Level.DEBUG); }
Example 2
Source File: LoggingStrategyFunctionalTest.java From pocket-etl with Apache License 2.0 | 5 votes |
@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 3
Source File: DefaultCredentialsProvider2Test.java From htmlunit with Apache License 2.0 | 5 votes |
/** * 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 4
Source File: HttpWebConnectionTest.java From htmlunit with Apache License 2.0 | 5 votes |
/** * @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 5
Source File: Log4j2Test.java From flogger with Apache License 2.0 | 5 votes |
@Before public void setUpLoggerBackend() { // A unique name should produce a different logger for each test allowing tests to be run in // parallel. String loggerName = String.format("%s_%02d", Log4j2Test.class.getName(), uid.incrementAndGet()); logger = (Logger) LogManager.getLogger(loggerName); appender = new CapturingAppender(); logger.addAppender(appender); logger.setLevel(TRACE); backend = new Log4j2LoggerBackend(logger); events = appender.events; }
Example 6
Source File: LogUtil.java From carbon-identity-framework with Apache License 2.0 | 5 votes |
public static void configureAndAddConsoleAppender() { final NullAppender appender = new NullAppender("NullAppender", null, null); appender.start(); final Logger logger = (Logger) LogManager.getRootLogger(); logger.addAppender(appender); }
Example 7
Source File: CsvParameterLayoutTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
static void testLayoutNormalApi(final Logger root, final AbstractCsvLayout layout, final boolean messageApi) throws Exception { removeAppenders(root); // set up appender final ListAppender appender = new ListAppender("List", null, layout, true, false); appender.start(); appender.countDownLatch = new CountDownLatch(4); // set appender on root and set level to debug root.addAppender(appender); root.setLevel(Level.DEBUG); // output messages if (messageApi) { logDebugObjectArrayMessage(root); } else { logDebugNormalApi(root); } final int msgCount = 4; if (appender.getMessages().size() < msgCount) { // wait until background thread finished processing appender.countDownLatch.await(10, 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 char d = layout.getFormat().getDelimiter(); Assert.assertEquals("1" + d + "2" + d + "3", list.get(0)); Assert.assertEquals("2" + d + "3", list.get(1)); Assert.assertEquals("5" + d + "6", list.get(2)); Assert.assertEquals("7" + d + "8" + d + "9" + d + "10", list.get(3)); }
Example 8
Source File: FlumeAppenderTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Test public void testStructured() throws IOException { final Agent[] agents = new Agent[] { Agent.createAgent("localhost", testPort) }; final FlumeAppender avroAppender = FlumeAppender.createAppender(agents, null, null, "false", "Avro", null, "1000", "1000", "1", "1000", "avro", "false", null, null, null, "ReqCtx_", null, "true", "1", null, null, null, null); avroAppender.start(); final Logger eventLogger = (Logger) LogManager.getLogger("EventLogger"); Assert.assertNotNull(eventLogger); eventLogger.addAppender(avroAppender); eventLogger.setLevel(Level.ALL); final StructuredDataMessage msg = new StructuredDataMessage("Transfer", "Success", "Audit"); msg.put("memo", "This is a memo"); msg.put("acct", "12345"); msg.put("amount", "100.00"); ThreadContext.put("id", UUID.randomUUID().toString()); ThreadContext.put("memo", null); ThreadContext.put("test", "123"); EventLogger.logEvent(msg); final Transaction transaction = channel.getTransaction(); transaction.begin(); final Event event = channel.take(); Assert.assertNotNull(event); Assert.assertTrue("Channel contained event, but not expected message", getBody(event).endsWith("Success")); transaction.commit(); transaction.close(); eventSource.stop(); eventLogger.removeAppender(avroAppender); avroAppender.stop(); }
Example 9
Source File: ConsoleAppender.java From DiscordSRV with GNU General Public License v3.0 | 4 votes |
public ConsoleAppender() { super("DiscordSRV-ConsoleChannel", null, PATTERN_LAYOUT, false); Logger rootLogger = (Logger) LogManager.getRootLogger(); rootLogger.addAppender(this); }
Example 10
Source File: TestAppender.java From iaf with Apache License 2.0 | 4 votes |
public static void addToRootLogger(TestAppender appender, Level level) { Logger logger = getRootLogger(); logger.setLevel(level); logger.addAppender(appender); }
Example 11
Source File: SmtpAppenderTest.java From logging-log4j2 with Apache License 2.0 | 4 votes |
@Test public void testDelivery() { final String subjectKey = getClass().getName(); final String subjectValue = "SubjectValue1"; ThreadContext.put(subjectKey, subjectValue); final int smtpPort = AvailablePortFinder.getNextAvailable(); final SmtpAppender appender = SmtpAppender.newBuilder() .setName("Test") .setTo("[email protected]") .setCc("[email protected]") .setBcc("[email protected]") .setFrom("[email protected]") .setReplyTo("[email protected]") .setSubject("Subject Pattern %X{" + subjectKey + "}") .setSmtpHost(HOST) .setSmtpPort(smtpPort) .setBufferSize(3) .build(); appender.start(); final LoggerContext context = LoggerContext.getContext(); final Logger root = context.getLogger("SMTPAppenderTest"); root.addAppender(appender); root.setAdditive(false); root.setLevel(Level.DEBUG); final SimpleSmtpServer server = SimpleSmtpServer.start(smtpPort); root.debug("Debug message #1"); root.debug("Debug message #2"); root.debug("Debug message #3"); root.debug("Debug message #4"); root.error("Error with exception", new RuntimeException("Exception message")); root.error("Error message #2"); server.stop(); assertTrue(server.getReceivedEmailSize() == 2); final Iterator<SmtpMessage> messages = server.getReceivedEmail(); final SmtpMessage email = messages.next(); assertEquals("[email protected]", email.getHeaderValue("To")); assertEquals("[email protected]", email.getHeaderValue("Cc")); // assertEquals("[email protected]", email.getHeaderValue("Bcc")); // BCC // can't be tested with Dumpster 1.6 assertEquals("[email protected]", email.getHeaderValue("From")); assertEquals("[email protected]", email.getHeaderValue("Reply-To")); final String headerValue = email.getHeaderValue("Subject"); assertEquals(headerValue, "Subject Pattern " + subjectValue); final String body = email.getBody(); assertFalse(body.contains("Debug message #1")); assertTrue(body.contains("Debug message #2")); assertTrue(body.contains("Debug message #3")); assertTrue(body.contains("Debug message #4")); assertTrue(body.contains("Error with exception")); assertTrue(body.contains("RuntimeException")); assertTrue(body.contains("Exception message")); assertFalse(body.contains("Error message #2")); final SmtpMessage email2 = messages.next(); final String body2 = email2.getBody(); assertFalse(body2.contains("Debug message #4")); assertFalse(body2.contains("Error with exception")); assertTrue(body2.contains("Error message #2")); }
Example 12
Source File: SocketAppenderTest.java From logging-log4j2 with Apache License 2.0 | 4 votes |
static void testTcpAppender(final TcpSocketTestServer tcpTestServer, final Logger logger, final int bufferSize) throws Exception { // @formatter:off final SocketAppender appender = SocketAppender.newBuilder() .setHost("localhost") .setPort(tcpTestServer.getLocalPort()) .setReconnectDelayMillis(-1) .setName("test") .setImmediateFail(false) .setBufferSize(bufferSize) .setLayout(JsonLayout.newBuilder().setProperties(true).build()) .build(); // @formatter:on appender.start(); Assert.assertEquals(bufferSize, appender.getManager().getByteBuffer().capacity()); // set appender on root and set level to debug logger.addAppender(appender); logger.setAdditive(false); logger.setLevel(Level.DEBUG); final String tcKey = "UUID"; final String expectedUuidStr = UUID.randomUUID().toString(); ThreadContext.put(tcKey, expectedUuidStr); ThreadContext.push(expectedUuidStr); final String expectedExMsg = "This is a test"; try { logger.debug("This is a test message"); final Throwable child = new LoggingException(expectedExMsg); logger.error("Throwing an exception", child); logger.debug("This is another test message"); } finally { ThreadContext.remove(tcKey); ThreadContext.pop(); } Thread.sleep(250); LogEvent event = tcpTestServer.getQueue().poll(3, TimeUnit.SECONDS); assertNotNull("No event retrieved", event); assertTrue("Incorrect event", event.getMessage().getFormattedMessage().equals("This is a test message")); assertTrue("Message not delivered via TCP", tcpTestServer.getCount() > 0); assertEquals(expectedUuidStr, event.getContextData().getValue(tcKey)); event = tcpTestServer.getQueue().poll(3, TimeUnit.SECONDS); assertNotNull("No event retrieved", event); assertTrue("Incorrect event", event.getMessage().getFormattedMessage().equals("Throwing an exception")); assertTrue("Message not delivered via TCP", tcpTestServer.getCount() > 1); assertEquals(expectedUuidStr, event.getContextStack().pop()); assertNotNull(event.getThrownProxy()); assertEquals(expectedExMsg, event.getThrownProxy().getMessage()); }
Example 13
Source File: ReconfigureAppenderTest.java From logging-log4j2 with Apache License 2.0 | 4 votes |
private void createAndAddAppender() { ConfigurationBuilder<BuiltConfiguration> config_builder = ConfigurationBuilderFactory.newConfigurationBuilder(); // All loggers must have a root logger. The default root logger logs ERRORs to the console. // Override this with a root logger that does not log anywhere as we leave it up the the // appenders on the logger. config_builder.add(config_builder.newRootLogger(Level.INFO)); // Initialise the logger context. LoggerContext logger_context = Configurator.initialize(config_builder.build()); // Retrieve the logger. Logger logger = (Logger) LogManager.getLogger(this.getClass()); Builder pattern_builder = PatternLayout.newBuilder().setPattern( "[%d{dd-MM-yy HH:mm:ss}] %p %m %throwable %n"); PatternLayout pattern_layout = (PatternLayout) pattern_builder.build(); appender = RollingFileAppender .newBuilder() .setLayout(pattern_layout) .setName("rollingfileappender") .setFilePattern("target/filepattern.%i.log") .setPolicy(SizeBasedTriggeringPolicy.createPolicy("5 MB")) .setAppend(true) .setStrategy( DirectWriteRolloverStrategy .newBuilder() .setConfig(logger_context.getConfiguration()) .setMaxFiles("5") .build()) .setConfiguration(logger_context.getConfiguration()) .build(); appender.start(); logger.addAppender(appender); }