Search in sources :

Example 11 with ExtendedLogger

use of org.apache.logging.log4j.spi.ExtendedLogger in project logging-log4j2 by apache.

the class GenerateExtendedLoggerTest method testGenerateSource.

@Test
public void testGenerateSource() throws Exception {
    final String CLASSNAME = "org.apache.logging.log4j.core.MyExtendedLogger";
    // generate custom logger source
    final List<String> values = Arrays.asList("DIAG=350 NOTICE=450 VERBOSE=550".split(" "));
    final List<Generate.LevelInfo> levels = Generate.LevelInfo.parse(values, Generate.ExtendedLogger.class);
    final String src = Generate.generateSource(CLASSNAME, levels, Generate.Type.EXTEND);
    final File f = new File(TEST_SOURCE);
    f.getParentFile().mkdirs();
    try (final FileOutputStream out = new FileOutputStream(f)) {
        out.write(src.getBytes(Charset.defaultCharset()));
    }
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    final List<String> errors = new ArrayList<>();
    try (final StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null)) {
        final Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Collections.singletonList(f));
        String classPath = System.getProperty("jdk.module.path");
        List<String> optionList = new ArrayList<>();
        if (Strings.isNotBlank(classPath)) {
            optionList.add("-classpath");
            optionList.add(classPath);
        }
        // compile generated source
        compiler.getTask(null, fileManager, diagnostics, optionList, null, compilationUnits).call();
        // check we don't have any compilation errors
        for (final Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
            if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
                errors.add(String.format("Compile error: %s%n", diagnostic.getMessage(Locale.getDefault())));
            }
        }
    }
    assertTrue(errors.isEmpty(), errors.toString());
    // load the compiled class
    final Class<?> cls = Class.forName(CLASSNAME);
    // check that all factory methods exist and are static
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create").getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", Class.class).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", Object.class).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", String.class).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", Class.class, MessageFactory.class).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", Object.class, MessageFactory.class).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", String.class, MessageFactory.class).getModifiers()));
    // check that the extended log methods exist
    final String[] extendedMethods = { "diag", "notice", "verbose" };
    for (final String name : extendedMethods) {
        assertDoesNotThrow(() -> {
            cls.getDeclaredMethod(name, Marker.class, Message.class, Throwable.class);
            cls.getDeclaredMethod(name, Marker.class, Object.class, Throwable.class);
            cls.getDeclaredMethod(name, Marker.class, String.class, Throwable.class);
            cls.getDeclaredMethod(name, Marker.class, Message.class);
            cls.getDeclaredMethod(name, Marker.class, Object.class);
            cls.getDeclaredMethod(name, Marker.class, String.class);
            cls.getDeclaredMethod(name, Message.class);
            cls.getDeclaredMethod(name, Object.class);
            cls.getDeclaredMethod(name, String.class);
            cls.getDeclaredMethod(name, Message.class, Throwable.class);
            cls.getDeclaredMethod(name, Object.class, Throwable.class);
            cls.getDeclaredMethod(name, String.class, Throwable.class);
            cls.getDeclaredMethod(name, String.class, Object[].class);
            cls.getDeclaredMethod(name, Marker.class, String.class, Object[].class);
            // 2.4 lambda support
            cls.getDeclaredMethod(name, Marker.class, MessageSupplier.class);
            cls.getDeclaredMethod(name, Marker.class, MessageSupplier.class, Throwable.class);
            cls.getDeclaredMethod(name, Marker.class, String.class, Supplier[].class);
            cls.getDeclaredMethod(name, Marker.class, Supplier.class);
            cls.getDeclaredMethod(name, Marker.class, Supplier.class, Throwable.class);
            cls.getDeclaredMethod(name, MessageSupplier.class);
            cls.getDeclaredMethod(name, MessageSupplier.class, Throwable.class);
            cls.getDeclaredMethod(name, String.class, Supplier[].class);
            cls.getDeclaredMethod(name, Supplier.class);
            cls.getDeclaredMethod(name, Supplier.class, Throwable.class);
        });
    }
    // now see if it actually works...
    final Method create = cls.getDeclaredMethod("create", String.class);
    final Object extendedLogger = create.invoke(null, "X.Y.Z");
    int n = 0;
    for (final String name : extendedMethods) {
        final Method method = cls.getDeclaredMethod(name, String.class);
        method.invoke(extendedLogger, "This is message " + n++);
    }
    // This logger extends o.a.l.log4j.spi.ExtendedLogger,
    // so all the standard logging methods can be used as well
    final ExtendedLogger logger = (ExtendedLogger) extendedLogger;
    logger.trace("trace message");
    logger.debug("debug message");
    logger.info("info message");
    logger.warn("warn message");
    logger.error("error message");
    logger.fatal("fatal message");
    final TestLogger underlying = (TestLogger) LogManager.getLogger("X.Y.Z");
    final List<String> lines = underlying.getEntries();
    for (int i = 0; i < lines.size() - 6; i++) {
        assertEquals(" " + levels.get(i).name + " This is message " + i, lines.get(i));
    }
    // test that the standard logging methods still work
    int i = lines.size() - 6;
    assertEquals(" TRACE trace message", lines.get(i++));
    assertEquals(" DEBUG debug message", lines.get(i++));
    assertEquals(" INFO info message", lines.get(i++));
    assertEquals(" WARN warn message", lines.get(i++));
    assertEquals(" ERROR error message", lines.get(i++));
    assertEquals(" FATAL fatal message", lines.get(i++));
}
Also used : ArrayList(java.util.ArrayList) JavaFileObject(javax.tools.JavaFileObject) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) MessageSupplier(org.apache.logging.log4j.util.MessageSupplier) Supplier(org.apache.logging.log4j.util.Supplier) MessageFactory(org.apache.logging.log4j.message.MessageFactory) JavaCompiler(javax.tools.JavaCompiler) Method(java.lang.reflect.Method) TestLogger(org.apache.logging.log4j.test.TestLogger) ExtendedLogger(org.apache.logging.log4j.spi.ExtendedLogger) FileOutputStream(java.io.FileOutputStream) JavaFileObject(javax.tools.JavaFileObject) File(java.io.File) Test(org.junit.jupiter.api.Test)

Example 12 with ExtendedLogger

use of org.apache.logging.log4j.spi.ExtendedLogger in project logging-log4j2 by apache.

the class FileAppenderPermissionsTest method testFilePermissions.

@Test
@LoggerContextSource(value = "log4j-posix.xml", timeout = 10)
void testFilePermissions(final LoggerContext context) throws IOException {
    final ExtendedLogger logger = context.getLogger(getClass());
    for (int i = 0; i < 1000; i++) {
        logger.debug("This is test message number {}", box(i));
    }
    final String permissions = PosixFilePermissions.toString(Files.getPosixFilePermissions(Paths.get("target/permissions1/AppenderTest-1.log")));
    assertEquals("rw-------", permissions);
}
Also used : ExtendedLogger(org.apache.logging.log4j.spi.ExtendedLogger) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) LoggerContextSource(org.apache.logging.log4j.core.test.junit.LoggerContextSource)

Example 13 with ExtendedLogger

use of org.apache.logging.log4j.spi.ExtendedLogger in project logging-log4j2 by apache.

the class AsyncAppenderTest method exceptionTest.

static void exceptionTest(final LoggerContext context) throws InterruptedException {
    final ExtendedLogger logger = context.getLogger(AsyncAppender.class);
    final Exception parent = new IllegalStateException("Test");
    final Throwable child = new LoggingException("This is a test", parent);
    logger.error("This is a test", child);
    final ListAppender appender = context.getConfiguration().getAppender("List");
    final List<String> messages;
    try {
        messages = appender.getMessages(1, 2, TimeUnit.SECONDS);
    } finally {
        appender.clear();
    }
    assertNotNull(messages);
    assertEquals(1, messages.size());
    assertTrue(messages.get(0).contains(parent.getClass().getName()));
}
Also used : ExtendedLogger(org.apache.logging.log4j.spi.ExtendedLogger) LoggingException(org.apache.logging.log4j.LoggingException) ListAppender(org.apache.logging.log4j.core.test.appender.ListAppender) LoggingException(org.apache.logging.log4j.LoggingException)

Example 14 with ExtendedLogger

use of org.apache.logging.log4j.spi.ExtendedLogger in project logging-log4j2 by apache.

the class AsyncAppenderTest method rewriteTest.

static void rewriteTest(final LoggerContext context) throws InterruptedException {
    final ExtendedLogger logger = context.getLogger(AsyncAppender.class);
    logger.error("This is a test");
    logger.warn("Hello world!");
    final ListAppender appender = context.getConfiguration().getAppender("List");
    final List<String> messages;
    try {
        messages = appender.getMessages(2, 2, TimeUnit.SECONDS);
    } finally {
        appender.clear();
    }
    assertNotNull(messages);
    assertEquals(2, messages.size());
    final String messagePrefix = AsyncAppenderTest.class.getName() + " rewriteTest ";
    assertEquals(messagePrefix + "This is a test", messages.get(0));
    assertEquals(messagePrefix + "Hello world!", messages.get(1));
}
Also used : ExtendedLogger(org.apache.logging.log4j.spi.ExtendedLogger) ListAppender(org.apache.logging.log4j.core.test.appender.ListAppender)

Example 15 with ExtendedLogger

use of org.apache.logging.log4j.spi.ExtendedLogger in project logging-log4j2 by apache.

the class SimpleLoggerContext method getLogger.

@Override
public ExtendedLogger getLogger(final String name, final MessageFactory messageFactory) {
    // Note: This is the only method where we add entries to the 'loggerRegistry' ivar.
    final ExtendedLogger extendedLogger = loggerRegistry.getLogger(name, messageFactory);
    if (extendedLogger != null) {
        AbstractLogger.checkMessageFactory(extendedLogger, messageFactory);
        return extendedLogger;
    }
    final SimpleLogger simpleLogger = new SimpleLogger(name, defaultLevel, showLogName, showShortName, showDateTime, showContextMap, dateTimeFormat, messageFactory, props, stream);
    loggerRegistry.putIfAbsent(name, messageFactory, simpleLogger);
    return loggerRegistry.getLogger(name, messageFactory);
}
Also used : ExtendedLogger(org.apache.logging.log4j.spi.ExtendedLogger)

Aggregations

ExtendedLogger (org.apache.logging.log4j.spi.ExtendedLogger)15 ListAppender (org.apache.logging.log4j.core.test.appender.ListAppender)3 Test (org.junit.jupiter.api.Test)3 Map (java.util.Map)2 ConcurrentMap (java.util.concurrent.ConcurrentMap)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 RendererMap (org.apache.log4j.or.RendererMap)2 LoggerContextSource (org.apache.logging.log4j.core.test.junit.LoggerContextSource)2 LocalizedMessage (org.apache.logging.log4j.message.LocalizedMessage)2 MapMessage (org.apache.logging.log4j.message.MapMessage)2 Message (org.apache.logging.log4j.message.Message)2 ObjectMessage (org.apache.logging.log4j.message.ObjectMessage)2 SimpleMessage (org.apache.logging.log4j.message.SimpleMessage)2 TestLogger (org.apache.logging.log4j.test.TestLogger)2 Test (org.junit.Test)2 PLogger (com.navercorp.pinpoint.bootstrap.logging.PLogger)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 Method (java.lang.reflect.Method)1 ArrayList (java.util.ArrayList)1