Search in sources :

Example 6 with Logger

use of org.apache.logging.log4j.core.Logger in project ignite by apache.

the class Log4J2Logger method fileName.

/** {@inheritDoc} */
@Nullable
@Override
public String fileName() {
    for (Logger log = impl; log != null; log = log.getParent()) {
        for (Appender a : log.getAppenders().values()) {
            if (a instanceof FileAppender)
                return ((FileAppender) a).getFileName();
            if (a instanceof RollingFileAppender)
                return ((RollingFileAppender) a).getFileName();
            if (a instanceof RoutingAppender) {
                try {
                    RoutingAppender routing = (RoutingAppender) a;
                    Field appsFiled = routing.getClass().getDeclaredField("appenders");
                    appsFiled.setAccessible(true);
                    Map<String, AppenderControl> appenders = (Map<String, AppenderControl>) appsFiled.get(routing);
                    for (AppenderControl control : appenders.values()) {
                        Appender innerApp = control.getAppender();
                        if (innerApp instanceof FileAppender)
                            return normilize(((FileAppender) innerApp).getFileName());
                        if (innerApp instanceof RollingFileAppender)
                            return normilize(((RollingFileAppender) innerApp).getFileName());
                    }
                } catch (IllegalAccessException | NoSuchFieldException e) {
                    error("Failed to get file name (was the implementation of log4j2 changed?).", e);
                }
            }
        }
    }
    return null;
}
Also used : Appender(org.apache.logging.log4j.core.Appender) RoutingAppender(org.apache.logging.log4j.core.appender.routing.RoutingAppender) ConsoleAppender(org.apache.logging.log4j.core.appender.ConsoleAppender) FileAppender(org.apache.logging.log4j.core.appender.FileAppender) RollingFileAppender(org.apache.logging.log4j.core.appender.RollingFileAppender) FileAppender(org.apache.logging.log4j.core.appender.FileAppender) RollingFileAppender(org.apache.logging.log4j.core.appender.RollingFileAppender) AppenderControl(org.apache.logging.log4j.core.config.AppenderControl) RollingFileAppender(org.apache.logging.log4j.core.appender.RollingFileAppender) IgniteLogger(org.apache.ignite.IgniteLogger) Logger(org.apache.logging.log4j.core.Logger) Field(java.lang.reflect.Field) RoutingAppender(org.apache.logging.log4j.core.appender.routing.RoutingAppender) Map(java.util.Map) Nullable(org.jetbrains.annotations.Nullable)

Example 7 with Logger

use of org.apache.logging.log4j.core.Logger in project ignite by apache.

the class Log4J2Logger method createConsoleLogger.

/**
     * Creates console appender with some reasonable default logging settings.
     *
     * @return Logger with auto configured console appender.
     */
public static Logger createConsoleLogger() {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(true);
    Configuration cfg = ctx.getConfiguration();
    PatternLayout.Builder builder = PatternLayout.newBuilder();
    builder.withPattern("%d{ABSOLUTE}][%-5p][%t][%c{1}] %m%n").withCharset(Charset.defaultCharset()).withAlwaysWriteExceptions(false).withNoConsoleNoAnsi(false);
    PatternLayout layout = builder.build();
    ConsoleAppender.Builder consoleAppenderBuilder = ConsoleAppender.newBuilder();
    consoleAppenderBuilder.withName(CONSOLE_APPENDER).withLayout(layout);
    ConsoleAppender consoleApp = consoleAppenderBuilder.build();
    consoleApp.start();
    AppenderRef ref = AppenderRef.createAppenderRef(CONSOLE_APPENDER, Level.TRACE, null);
    AppenderRef[] refs = { ref };
    LoggerConfig logCfg = LoggerConfig.createLogger(false, Level.INFO, LogManager.ROOT_LOGGER_NAME, "", refs, null, null, null);
    logCfg.addAppender(consoleApp, null, null);
    cfg.addAppender(consoleApp);
    cfg.addLogger(LogManager.ROOT_LOGGER_NAME, logCfg);
    ctx.updateLoggers(cfg);
    return (Logger) LogManager.getContext().getLogger(LogManager.ROOT_LOGGER_NAME);
}
Also used : ConsoleAppender(org.apache.logging.log4j.core.appender.ConsoleAppender) Configuration(org.apache.logging.log4j.core.config.Configuration) PatternLayout(org.apache.logging.log4j.core.layout.PatternLayout) AppenderRef(org.apache.logging.log4j.core.config.AppenderRef) IgniteLogger(org.apache.ignite.IgniteLogger) Logger(org.apache.logging.log4j.core.Logger) LoggerContext(org.apache.logging.log4j.core.LoggerContext) LoggerConfig(org.apache.logging.log4j.core.config.LoggerConfig)

Example 8 with Logger

use of org.apache.logging.log4j.core.Logger in project logging-log4j2 by apache.

the class SmtpAppenderTest method testDelivery.

@Test
public void testDelivery() {
    final String subjectKey = getClass().getName();
    final String subjectValue = "SubjectValue1";
    ThreadContext.put(subjectKey, subjectValue);
    final SmtpAppender appender = SmtpAppender.createAppender(null, "Test", "to@example.com", "cc@example.com", "bcc@example.com", "from@example.com", "replyTo@example.com", "Subject Pattern %X{" + subjectKey + "}", null, HOST, PORT, null, null, "false", "3", null, null, "true");
    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(PORTNUM);
    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("to@example.com", email.getHeaderValue("To"));
    assertEquals("cc@example.com", email.getHeaderValue("Cc"));
    // assertEquals("bcc@example.com", email.getHeaderValue("Bcc")); // BCC
    // can't be tested with Dumpster 1.6
    assertEquals("from@example.com", email.getHeaderValue("From"));
    assertEquals("replyTo@example.com", 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"));
}
Also used : SmtpMessage(org.apache.logging.dumbster.smtp.SmtpMessage) SimpleSmtpServer(org.apache.logging.dumbster.smtp.SimpleSmtpServer) Logger(org.apache.logging.log4j.core.Logger) LoggerContext(org.apache.logging.log4j.core.LoggerContext) Test(org.junit.Test)

Example 9 with Logger

use of org.apache.logging.log4j.core.Logger in project logging-log4j2 by apache.

the class JeroMqAppenderTest method testMultiThreadedServer.

@Test(timeout = DEFAULT_TIMEOUT_MILLIS)
public void testMultiThreadedServer() throws Exception {
    final int nThreads = 10;
    final JeroMqAppender appender = ctx.getRequiredAppender(APPENDER_NAME, JeroMqAppender.class);
    final int expectedReceiveCount = 2 * nThreads;
    final JeroMqTestClient client = new JeroMqTestClient(JeroMqManager.getContext(), ENDPOINT, expectedReceiveCount);
    final ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
        final Future<List<String>> future = executor.submit(client);
        Thread.sleep(100);
        final Logger logger = ctx.getLogger(getClass().getName());
        appender.resetSendRcs();
        final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(nThreads);
        for (int i = 0; i < 10.; i++) {
            fixedThreadPool.submit(new Runnable() {

                @Override
                public void run() {
                    logger.info("Hello");
                    logger.info("Again");
                }
            });
        }
        final List<String> list = future.get();
        Assert.assertEquals(expectedReceiveCount, appender.getSendRcTrue());
        Assert.assertEquals(0, appender.getSendRcFalse());
        int hello = 0;
        int again = 0;
        for (final String string : list) {
            switch(string) {
                case "Hello":
                    hello++;
                    break;
                case "Again":
                    again++;
                    break;
                default:
                    Assert.fail("Unexpected message: " + string);
            }
        }
        Assert.assertEquals(nThreads, hello);
        Assert.assertEquals(nThreads, again);
    } finally {
        ExecutorServices.shutdown(executor, DEFAULT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS, JeroMqAppenderTest.class.getSimpleName());
    }
}
Also used : ExecutorService(java.util.concurrent.ExecutorService) List(java.util.List) Logger(org.apache.logging.log4j.core.Logger) Test(org.junit.Test)

Example 10 with Logger

use of org.apache.logging.log4j.core.Logger in project logging-log4j2 by apache.

the class ClassLoaderContextSelectorTest method testMultipleClassLoaders.

@Test
public void testMultipleClassLoaders() throws Exception {
    final Class<?> logging1 = loader1.loadClass(PKG + ".a.Logging1");
    final Field field1 = logging1.getDeclaredField("logger");
    final Logger logger1 = (Logger) ReflectionUtil.getStaticFieldValue(field1);
    assertNotNull(logger1);
    final Class<?> logging2 = loader2.loadClass(PKG + ".b.Logging2");
    final Field field2 = logging2.getDeclaredField("logger");
    final Logger logger2 = (Logger) ReflectionUtil.getStaticFieldValue(field2);
    assertNotNull(logger2);
    final Class<?> logging3 = loader3.loadClass(PKG + ".c.Logging3");
    final Field field3 = logging3.getDeclaredField("logger");
    final Logger logger3 = (Logger) ReflectionUtil.getStaticFieldValue(field3);
    assertNotNull(logger3);
    assertNotSame(logger1.getContext(), logger2.getContext());
    assertNotSame(logger1.getContext(), logger3.getContext());
    assertNotSame(logger2.getContext(), logger3.getContext());
}
Also used : Field(java.lang.reflect.Field) Logger(org.apache.logging.log4j.core.Logger) Test(org.junit.Test)

Aggregations

Logger (org.apache.logging.log4j.core.Logger)34 Test (org.junit.Test)20 LoggerContext (org.apache.logging.log4j.core.LoggerContext)6 Appender (org.apache.logging.log4j.core.Appender)5 StatusLogger (org.apache.logging.log4j.status.StatusLogger)5 Field (java.lang.reflect.Field)4 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)4 Marker (org.apache.logging.log4j.Marker)4 ListAppender (org.apache.logging.log4j.test.appender.ListAppender)4 IgniteLogger (org.apache.ignite.IgniteLogger)3 LogEvent (org.apache.logging.log4j.core.LogEvent)3 ConsoleAppender (org.apache.logging.log4j.core.appender.ConsoleAppender)3 List (java.util.List)2 Map (java.util.Map)2 ExecutorService (java.util.concurrent.ExecutorService)2 FileAppender (org.apache.logging.log4j.core.appender.FileAppender)2 RollingFileAppender (org.apache.logging.log4j.core.appender.RollingFileAppender)2 RoutingAppender (org.apache.logging.log4j.core.appender.routing.RoutingAppender)2 Log4jLogger (org.apache.logging.slf4j.Log4jLogger)2 LogLevel (com.torodb.packaging.config.model.generic.LogLevel)1