org.apache.logging.log4j.spi.AbstractLogger Java Examples

The following examples show how to use org.apache.logging.log4j.spi.AbstractLogger. 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: Log4jTaglibLoggerContext.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public Log4jTaglibLogger getLogger(final String name, final MessageFactory messageFactory) {
    // Note: This is the only method where we add entries to the 'loggerRegistry' ivar.
    Log4jTaglibLogger logger = this.loggerRegistry.getLogger(name, messageFactory);
    if (logger != null) {
        AbstractLogger.checkMessageFactory(logger, messageFactory);
        return logger;
    }

    synchronized (this.loggerRegistry) {
        logger = this.loggerRegistry.getLogger(name, messageFactory);
        if (logger == null) {
            final LoggerContext context = LogManager.getContext(false);
            final ExtendedLogger original = messageFactory == null ?
                    context.getLogger(name) : context.getLogger(name, messageFactory);
            // wrap a logger from an underlying implementation
            logger = new Log4jTaglibLogger(original, name, original.getMessageFactory());
            this.loggerRegistry.putIfAbsent(name, messageFactory, logger);
        }
    }

    return logger;
}
 
Example #2
Source File: TagUtils.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
static Log4jTaglibLogger resolveLogger(final Log4jTaglibLoggerContext context, final Object logger,
                                       final MessageFactory factory) throws JspException {
    if (logger instanceof Logger) {
        if (logger instanceof Log4jTaglibLogger) {
            return (Log4jTaglibLogger) logger;
        }
        if (logger instanceof AbstractLogger) {
            if (LOGGER.isInfoEnabled() && !WARNED_FOR.contains(logger)) {
                LOGGER.info("Constructing new Log4jTaglibLogger from AbstractLogger {} name and message factory.",
                        logger.getClass().getName());
                WARNED_FOR.add(logger);
            }
            final AbstractLogger original = (AbstractLogger) logger;
            return getLogger(context, original.getName(), original.getMessageFactory());
        }
        throw new JspException(
                "Log4j Tag Library requires base logging system to extend Log4j AbstractLogger.");
    }
    if (logger instanceof String) {
        return getLogger(context, (String) logger, factory);
    }
    throw new JspException("Logger must be of type String or org.apache.logging.log4j.Logger.");
}
 
Example #3
Source File: LoggerAwareTagSupportTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetLoggerWithTaglibLogger() throws Exception {
    this.setUp(null);

    final AbstractLogger wrapped = (AbstractLogger)LogManager.getLogger("testGetLoggerWithTaglibLogger");
    final Log4jTaglibLogger logger = new Log4jTaglibLogger(wrapped, wrapped.getName(), wrapped.getMessageFactory());

    this.tag.setLogger(logger);
    Log4jTaglibLogger returned = this.tag.getLogger();

    assertNotNull("The first returned logger should not be null.", returned);
    assertSame("The first returned logger should be the same as the set.", logger, returned);
    assertEquals("The name is not correct.", "testGetLoggerWithTaglibLogger", returned.getName());

    returned = this.tag.getLogger();

    assertNotNull("The second returned logger should not be null.", returned);
    assertSame("The second returned logger should be the same as the set.", logger, returned);
}
 
Example #4
Source File: Log4j2StatusLoggerWrapperTest.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void errorDelegatesProperly() {

    // given
    String expectedMessage = UUID.randomUUID().toString();
    AbstractLogger logger = mock(AbstractLogger.class);
    Logger wrapper = new Log4j2StatusLoggerWrapper(logger);
    
    String arg1 = UUID.randomUUID().toString();
    String arg2 = UUID.randomUUID().toString();

    // when
    wrapper.error(expectedMessage, arg1, arg2);

    // then
    ArgumentCaptor<Object[]> captor = ArgumentCaptor.forClass(Object[].class);
    verify(logger).error(eq(expectedMessage), captor.capture());

    assertEquals(arg1, captor.getAllValues().get(0));
    assertEquals(arg2, captor.getAllValues().get(1));

}
 
Example #5
Source File: Log4j2StatusLoggerWrapperTest.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void warnDelegatesProperly() {
    
    // given
    String expectedMessage = UUID.randomUUID().toString();
    AbstractLogger logger = mock(AbstractLogger.class);
    Logger wrapper = new Log4j2StatusLoggerWrapper(logger);

    String arg1 = UUID.randomUUID().toString();
    String arg2 = UUID.randomUUID().toString();

    // when
    wrapper.error(expectedMessage, arg1, arg2);

    // then
    ArgumentCaptor<Object[]> captor = ArgumentCaptor.forClass(Object[].class);
    verify(logger).error(eq(expectedMessage), captor.capture());

    assertEquals(arg1, captor.getAllValues().get(0));
    assertEquals(arg2, captor.getAllValues().get(1));

}
 
Example #6
Source File: Log4j2StatusLoggerWrapperTest.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void infoDelegatesProperly() {
    // given
    String expectedMessage = UUID.randomUUID().toString();
    AbstractLogger logger = mock(AbstractLogger.class);
    Logger wrapper = new Log4j2StatusLoggerWrapper(logger);

    String arg1 = UUID.randomUUID().toString();
    String arg2 = UUID.randomUUID().toString();

    // when
    wrapper.info(expectedMessage, arg1, arg2);

    // then
    ArgumentCaptor<Object[]> captor = ArgumentCaptor.forClass(Object[].class);
    verify(logger).info(eq(expectedMessage), captor.capture());

    assertEquals(arg1, captor.getAllValues().get(0));
    assertEquals(arg2, captor.getAllValues().get(1));

}
 
Example #7
Source File: Log4j2StatusLoggerWrapperTest.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void debugDelegatesProperly() {

    // given
    String expectedMessage = UUID.randomUUID().toString();
    AbstractLogger logger = mock(AbstractLogger.class);
    Logger wrapper = new Log4j2StatusLoggerWrapper(logger);

    String arg1 = UUID.randomUUID().toString();
    String arg2 = UUID.randomUUID().toString();

    // when
    wrapper.debug(expectedMessage, arg1, arg2);

    // then
    ArgumentCaptor<Object[]> captor = ArgumentCaptor.forClass(Object[].class);
    verify(logger).debug(eq(expectedMessage), captor.capture());

    assertEquals(arg1, captor.getAllValues().get(0));
    assertEquals(arg2, captor.getAllValues().get(1));

}
 
Example #8
Source File: Log4j2StatusLoggerWrapperTest.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void traceDelegatesProperly() {

    // given
    String expectedMessage = UUID.randomUUID().toString();
    AbstractLogger logger = mock(AbstractLogger.class);
    Logger wrapper = new Log4j2StatusLoggerWrapper(logger);

    String arg1 = UUID.randomUUID().toString();
    String arg2 = UUID.randomUUID().toString();

    // when
    wrapper.trace(expectedMessage, arg1, arg2);

    // then
    ArgumentCaptor<Object[]> captor = ArgumentCaptor.forClass(Object[].class);
    verify(logger).trace(eq(expectedMessage), captor.capture());

    assertEquals(arg1, captor.getAllValues().get(0));
    assertEquals(arg2, captor.getAllValues().get(1));

}
 
Example #9
Source File: AsyncLogger.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private void handleRingBufferFull(final RingBufferLogEventTranslator translator) {
    if (AbstractLogger.getRecursionDepth() > 1) { // LOG4J2-1518, LOG4J2-2031
        // If queue is full AND we are in a recursive call, call appender directly to prevent deadlock
        AsyncQueueFullMessageUtil.logWarningToStatusLogger();
        logMessageInCurrentThread(translator.fqcn, translator.level, translator.marker, translator.message,
                translator.thrown);
        translator.clear();
        return;
    }
    final EventRoute eventRoute = loggerDisruptor.getEventRoute(translator.level);
    switch (eventRoute) {
        case ENQUEUE:
            loggerDisruptor.enqueueLogMessageWhenQueueFull(translator);
            break;
        case SYNCHRONOUS:
            logMessageInCurrentThread(translator.fqcn, translator.level, translator.marker, translator.message,
                    translator.thrown);
            translator.clear();
            break;
        case DISCARD:
            translator.clear();
            break;
        default:
            throw new IllegalStateException("Unknown EventRoute " + eventRoute);
    }
}
 
Example #10
Source File: AsyncAppender.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Actual writing occurs here.
 *
 * @param logEvent The LogEvent.
 */
@Override
public void append(final LogEvent logEvent) {
    if (!isStarted()) {
        throw new IllegalStateException("AsyncAppender " + getName() + " is not active");
    }
    final Log4jLogEvent memento = Log4jLogEvent.createMemento(logEvent, includeLocation);
    InternalAsyncUtil.makeMessageImmutable(logEvent.getMessage());
    if (!transfer(memento)) {
        if (blocking) {
            if (AbstractLogger.getRecursionDepth() > 1) { // LOG4J2-1518, LOG4J2-2031
                // If queue is full AND we are in a recursive call, call appender directly to prevent deadlock
                AsyncQueueFullMessageUtil.logWarningToStatusLogger();
                logMessageInCurrentThread(logEvent);
            } else {
                // delegate to the event router (which may discard, enqueue and block, or log in current thread)
                final EventRoute route = asyncQueueFullPolicy.getRoute(thread.getId(), memento.getLevel());
                route.logMessage(this, memento);
            }
        } else {
            error("Appender " + getName() + " is unable to write primary appenders. queue is full");
            logToErrorAppenderIfNecessary(false, memento);
        }
    }
}
 
Example #11
Source File: AsyncLogger.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void handleRingBufferFull(final StackTraceElement location,
                                  final String fqcn,
                                  final Level level,
                                  final Marker marker,
                                  final Message msg,
                                  final Throwable thrown) {
    if (AbstractLogger.getRecursionDepth() > 1) { // LOG4J2-1518, LOG4J2-2031
        // If queue is full AND we are in a recursive call, call appender directly to prevent deadlock
        AsyncQueueFullMessageUtil.logWarningToStatusLogger();
        logMessageInCurrentThread(fqcn, level, marker, msg, thrown);
        return;
    }
    final EventRoute eventRoute = loggerDisruptor.getEventRoute(level);
    switch (eventRoute) {
        case ENQUEUE:
            loggerDisruptor.enqueueLogMessageWhenQueueFull(this,
                    this, // asyncLogger: 0
                    location, // location: 1
                    fqcn, // 2
                    level, // 3
                    marker, // 4
                    msg, // 5
                    thrown); // 6
            break;
        case SYNCHRONOUS:
            logMessageInCurrentThread(fqcn, level, marker, msg, thrown);
            break;
        case DISCARD:
            break;
        default:
            throw new IllegalStateException("Unknown EventRoute " + eventRoute);
    }
}
 
Example #12
Source File: SetLoggerTagTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private static void checkMessageFactory(final String msg, final MessageFactory messageFactory,
        final Logger testLogger) {
    if (messageFactory == null) {
        assertEquals(msg, AbstractLogger.DEFAULT_MESSAGE_FACTORY_CLASS,
                testLogger.getMessageFactory().getClass());
    } else {
        MessageFactory actual = testLogger.getMessageFactory();
        assertEquals(msg, messageFactory, actual);
    }
}
 
Example #13
Source File: LoggerTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private static void checkMessageFactory(final MessageFactory messageFactory, final Logger testLogger) {
    if (messageFactory == null) {
        assertEquals(AbstractLogger.DEFAULT_MESSAGE_FACTORY_CLASS, testLogger.getMessageFactory().getClass());
    } else {
        MessageFactory actual = testLogger.getMessageFactory();
        assertEquals(messageFactory, actual);
    }
}
 
Example #14
Source File: LoggerContext.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Obtains a Logger from the Context.
 *
 * @param name The name of the Logger to return.
 * @param messageFactory The message factory is used only when creating a logger, subsequent use does not change the
 *            logger but will log a warning if mismatched.
 * @return The Logger.
 */
@Override
public Logger getLogger(final String name, final MessageFactory messageFactory) {
    // Note: This is the only method where we add entries to the 'loggerRegistry' ivar.
    Logger logger = loggerRegistry.getLogger(name, messageFactory);
    if (logger != null) {
        AbstractLogger.checkMessageFactory(logger, messageFactory);
        return logger;
    }

    logger = newInstance(this, name, messageFactory);
    loggerRegistry.putIfAbsent(name, messageFactory, logger);
    return loggerRegistry.getLogger(name, messageFactory);
}
 
Example #15
Source File: AsyncLoggerConfig.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void handleQueueFull(final LogEvent event) {
    if (AbstractLogger.getRecursionDepth() > 1) { // LOG4J2-1518, LOG4J2-2031
        // If queue is full AND we are in a recursive call, call appender directly to prevent deadlock
        AsyncQueueFullMessageUtil.logWarningToStatusLogger();
        logToAsyncLoggerConfigsOnCurrentThread(event);
    } else {
        // otherwise, we leave it to the user preference
        final EventRoute eventRoute = delegate.getEventRoute(event.getLevel());
        eventRoute.logMessage(this, event);
    }
}
 
Example #16
Source File: SimpleLoggerContext.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #17
Source File: AbstractStringLayout.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@code StringBuilder} that this Layout implementation can use to write the formatted log event to.
 *
 * @return a {@code StringBuilder}
 */
protected static StringBuilder getStringBuilder() {
    if (AbstractLogger.getRecursionDepth() > 1) { // LOG4J2-2368
        // Recursive logging may clobber the cached StringBuilder.
        return new StringBuilder(DEFAULT_STRING_BUILDER_SIZE);
    }
    StringBuilder result = threadLocal.get();
    if (result == null) {
        result = new StringBuilder(DEFAULT_STRING_BUILDER_SIZE);
        threadLocal.set(result);
    }
    trimToMaxSize(result);
    result.setLength(0);
    return result;
}
 
Example #18
Source File: AsyncLoggerConfigUseAfterShutdownTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
 public void testNoErrorIfLogAfterShutdown() throws Exception {
     final Logger log = LogManager.getLogger("com.foo.Bar");
     log.info("some message");
     CoreLoggerContexts.stopLoggerContext(); // stop async thread

     // call the #logMessage() method to bypass the isEnabled check: 
     // before the LOG4J2-639 fix this would throw a NPE
     ((AbstractLogger) log).logMessage("com.foo.Bar", Level.INFO, null, new SimpleMessage("msg"), null);
}
 
Example #19
Source File: AsyncLoggerUseAfterShutdownTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoErrorIfLogAfterShutdown() throws Exception {
    final Logger log = LogManager.getLogger("com.foo.Bar");
    final String msg = "Async logger msg";
    log.info(msg, new InternalError("this is not a real error"));
    CoreLoggerContexts.stopLoggerContext(); // stop async thread

    // call the #logMessage() method to bypass the isEnabled check: 
    // before the LOG4J2-639 fix this would throw a NPE
    ((AbstractLogger) log).logMessage("com.foo.Bar", Level.INFO, null, new SimpleMessage("msg"), null);
}
 
Example #20
Source File: LoggerTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private static void checkMessageFactory(final MessageFactory messageFactory, final Logger testLogger) {
    if (messageFactory == null) {
        assertEquals(AbstractLogger.DEFAULT_MESSAGE_FACTORY_CLASS, testLogger.getMessageFactory().getClass());
    } else {
        MessageFactory actual = testLogger.getMessageFactory();
        assertEquals(messageFactory, actual);
    }
}
 
Example #21
Source File: Log4jLogger_impl.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * create a new LogWrapper class for the specified source class
 * 
 * @param component
 *           specified source class
 */
private Log4jLogger_impl(Class<?> component) {
   super(component);

   coreLogger = (org.apache.logging.log4j.core.Logger) LogManager.getLogger( (null == component) 
                                    ?  "org.apache.uima"
                                    : component.getName());
   mf = coreLogger.getMessageFactory();
   
   logger = new ExtendedLoggerWrapper((AbstractLogger) coreLogger, coreLogger.getName(), mf);
}
 
Example #22
Source File: Log4j2Impl.java    From mybatis with Apache License 2.0 5 votes vote down vote up
public Log4j2Impl(String clazz) {
  Logger logger = LogManager.getLogger(clazz);

  if (logger instanceof AbstractLogger) {
    log = new Log4j2AbstractLoggerImpl((AbstractLogger) logger);
  } else {
    log = new Log4j2LoggerImpl(logger);
  }
}
 
Example #23
Source File: Log4j2Impl.java    From mybaties with Apache License 2.0 5 votes vote down vote up
public Log4j2Impl(String clazz) {
  Logger logger = LogManager.getLogger(clazz);

  if (logger instanceof AbstractLogger) {
    log = new Log4j2AbstractLoggerImpl((AbstractLogger) logger);
  } else {
    log = new Log4j2LoggerImpl(logger);
  }
}
 
Example #24
Source File: Log4j2Impl.java    From elasticsearch-jdbc with MIT License 5 votes vote down vote up
public Log4j2Impl(String clazz) {
    Logger logger = LogManager.getLogger(clazz);

    if (logger instanceof AbstractLogger) {
        log = new Log4j2AbstractLoggerImpl((AbstractLogger) logger);
    } else {
        log = new Log4j2LoggerImpl(logger);
    }
}
 
Example #25
Source File: LambdaLoggerTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
public AbstractLogger enable() {
    enabled = true;
    return this;
}
 
Example #26
Source File: LambdaLoggerTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
public AbstractLogger disable() {
    enabled = false;
    return this;
}
 
Example #27
Source File: BHBotLogger.java    From BHBot with GNU General Public License v3.0 4 votes vote down vote up
private BHBotLogger(final Logger logger) {
    super((AbstractLogger) logger, logger.getName(), logger.getMessageFactory());
    this.logger = this;
}
 
Example #28
Source File: Log4j2AbstractLoggerImpl.java    From mybatis with Apache License 2.0 4 votes vote down vote up
public Log4j2AbstractLoggerImpl(AbstractLogger abstractLogger) {
  log = new ExtendedLoggerWrapper(abstractLogger, abstractLogger.getName(), abstractLogger.getMessageFactory());
}
 
Example #29
Source File: MuLogger.java    From vethrfolnir-mu with GNU General Public License v3.0 4 votes vote down vote up
public static MuLogger getLogger(String name)
{
	Logger logger = LogManager.getLogger(name);
	return new MuLogger((AbstractLogger) logger, logger.getName(), logger.getMessageFactory());
}
 
Example #30
Source File: MuLogger.java    From vethrfolnir-mu with GNU General Public License v3.0 4 votes vote down vote up
public static MuLogger getLogger(Class<?> type)
{
	Logger logger = LogManager.getLogger(type);
	return new MuLogger((AbstractLogger) logger, logger.getName(), logger.getMessageFactory());
}