Java Code Examples for org.apache.logging.log4j.core.LogEvent#getLoggerName()

The following examples show how to use org.apache.logging.log4j.core.LogEvent#getLoggerName() . 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: ESLoggerConfigFactory.java    From core-ng-project with Apache License 2.0 6 votes vote down vote up
public static void configureLogger() {
    LoggerContext context = (LoggerContext) LogManager.getContext(false);
    Configuration config = context.getConfiguration();

    Map<String, ESLogger> loggers = Maps.newConcurrentHashMap();
    Appender appender = new AbstractAppender("", null, null) {
        @Override
        public void append(LogEvent event) {
            String name = event.getLoggerName();
            ESLogger logger = loggers.computeIfAbsent(name, key -> new ESLogger(key, null, (LoggerImpl) LoggerFactory.getLogger(key)));
            logger.log(event.getLevel(), event.getMarker(), event.getMessage(), event.getThrown());
        }
    };
    appender.start();
    config.addAppender(appender);

    var loggerConfig = new LoggerConfig("", Level.INFO, false); // only enable info and higher level
    loggerConfig.addAppender(appender, null, null);
    config.addLogger("", loggerConfig);
    context.updateLoggers();
}
 
Example 2
Source File: RollbarAppender.java    From rollbar-java with MIT License 6 votes vote down vote up
@Override
public void append(LogEvent event) {
  if (event.getLoggerName() != null && event.getLoggerName().startsWith(PACKAGE_NAME)) {
    LOGGER.warn("Recursive logging from [{}] for appender [{}].", event.getLoggerName(),
        getName());
    return;
  }

  ThrowableProxy throwableProxy = event.getThrownProxy();
  ThrowableWrapper rollbarThrowableWrapper = buildRollbarThrowableWrapper(throwableProxy);
  Map<String, Object> custom = this.buildCustom(event);
  String message = event.getMessage() != null ? event.getMessage().getFormattedMessage() : null;
  Level level = this.getLevel(event);

  rollbar.log(rollbarThrowableWrapper, custom, message, level, false);
}
 
Example 3
Source File: FlumeAppender.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Publish the event.
 * @param event The LogEvent.
 */
@Override
public void append(final LogEvent event) {
    final String name = event.getLoggerName();
    if (name != null) {
        for (final String pkg : EXCLUDED_PACKAGES) {
            if (name.startsWith(pkg)) {
                return;
            }
        }
    }
    timer.startOrResume();
    final FlumeEvent flumeEvent = factory.createEvent(event, mdcIncludes, mdcExcludes, mdcRequired, mdcPrefix,
        eventPrefix, compressBody);
    flumeEvent.setBody(getLayout().toByteArray(flumeEvent));
    if (update()) {
        String msg = timer.stop();
        LOGGER.debug(msg);
    } else {
        timer.pause();
    }
    manager.send(flumeEvent);
}
 
Example 4
Source File: Log4jLogEvent.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
public LogEventProxy(final LogEvent event, final boolean includeLocation) {
    this.loggerFQCN = event.getLoggerFqcn();
    this.marker = event.getMarker();
    this.level = event.getLevel();
    this.loggerName = event.getLoggerName();

    final Message temp = event.getMessage();
    message = temp instanceof ReusableMessage
            ? memento((ReusableMessage) temp)
            : temp;
    this.timeMillis = event.getInstant().getEpochMillisecond();
    this.nanoOfMillisecond = event.getInstant().getNanoOfMillisecond();
    this.thrown = event.getThrown();
    this.thrownProxy = event.getThrownProxy();
    this.contextData = memento(event.getContextData());
    this.contextStack = event.getContextStack();
    this.source = includeLocation ? event.getSource() : null;
    this.threadId = event.getThreadId();
    this.threadName = event.getThreadName();
    this.threadPriority = event.getThreadPriority();
    this.isLocationRequired = includeLocation;
    this.isEndOfBatch = event.isEndOfBatch();
    this.nanoTime = event.getNanoTime();
}
 
Example 5
Source File: MutableLogEvent.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the fields of this {@code MutableLogEvent} from another event.
 * Similar in purpose and usage as {@link org.apache.logging.log4j.core.impl.Log4jLogEvent.LogEventProxy},
 * but a mutable version.
 * <p>
 * This method is used on async logger ringbuffer slots holding MutableLogEvent objects in each slot.
 * </p>
 *
 * @param event the event to copy data from
 */
public void initFrom(final LogEvent event) {
    this.loggerFqcn = event.getLoggerFqcn();
    this.marker = event.getMarker();
    this.level = event.getLevel();
    this.loggerName = event.getLoggerName();
    this.thrown = event.getThrown();
    this.thrownProxy = event.getThrownProxy();

    this.instant.initFrom(event.getInstant());

    // NOTE: this ringbuffer event SHOULD NOT keep a reference to the specified
    // thread-local MutableLogEvent's context data, because then two threads would call
    // ReadOnlyStringMap.clear() on the same shared instance, resulting in data corruption.
    this.contextData.putAll(event.getContextData());

    this.contextStack = event.getContextStack();
    this.source = event.isIncludeLocation() ? event.getSource() : null;
    this.threadId = event.getThreadId();
    this.threadName = event.getThreadName();
    this.threadPriority = event.getThreadPriority();
    this.endOfBatch = event.isEndOfBatch();
    this.includeLocation = event.isIncludeLocation();
    this.nanoTime = event.getNanoTime();
    setMessage(event.getMessage());
}
 
Example 6
Source File: LoggerNamePatternSelector.java    From TerminalConsoleAppender with MIT License 5 votes vote down vote up
@Override
public PatternFormatter[] getFormatters(LogEvent event) {
    final @Nullable String loggerName = event.getLoggerName();
    if (loggerName != null) {
        //noinspection ForLoopReplaceableByForEach
        for (int i = 0; i < this.formatters.size(); i++) {
            LoggerNameSelector selector = this.formatters.get(i);
            if (selector.test(loggerName)) {
                return selector.get();
            }
        }
    }

    return this.defaultFormatters;
}
 
Example 7
Source File: CloudwatchLogsLog4J2Appender.java    From cloudwatchlogs-java-appender with Apache License 2.0 5 votes vote down vote up
@Override
public void append(LogEvent event) {
    StringBuilder message = new StringBuilder(event.getMessage().getFormattedMessage());
    Throwable thrown = event.getThrown();
    while (thrown != null) {
        message.append("\n").append(dump(thrown));
        thrown = thrown.getCause();
        if (thrown != null) {
            message.append("\nCaused by:");
        }
    }

    String account = event.getContextData().getValue(CloudwatchLogsMDCPropertyNames.ACCOUNT);
    String action = event.getContextData().getValue(CloudwatchLogsMDCPropertyNames.ACTION);
    String user = event.getContextData().getValue(CloudwatchLogsMDCPropertyNames.USER);
    String session = event.getContextData().getValue(CloudwatchLogsMDCPropertyNames.SESSION);
    String request = event.getContextData().getValue(CloudwatchLogsMDCPropertyNames.REQUEST);

    Marker marker = event.getMarker();
    String eventId = marker == null ? null : marker.getName();

    Map<String, String> customMdcAttributes = new HashMap<>();
    for (String key : config.getCustomMdcKeys()) {
        String value = event.getContextData().getValue(key);
        if (value != null) {
            customMdcAttributes.put(key, value);
        }
    }

    CloudwatchLogsLogEvent logEvent = new CloudwatchLogsLogEvent(event.getLevel().toString(), event.getLoggerName(),
            eventId, message.toString(), event.getTimeMillis(), event.getThreadName(), account, action, user,
            session, request, customMdcAttributes);
    while (!eventQueue.offer(logEvent)) {
        eventQueue.poll();
        discardedCount++;
    }
}
 
Example 8
Source File: PulsarAppender.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public void append(final LogEvent event) {
    if (avoidRecursive
        && event.getLoggerName() != null
        && event.getLoggerName().startsWith("org.apache.pulsar")) {
        LOGGER.warn("Recursive logging from [{}] for appender [{}].", event.getLoggerName(), getName());
    } else {
        try {
            tryAppend(event);
        } catch (final Exception e) {
            error("Unable to write to Pulsar in appender [" + getName() + "]", event, e);
        }
    }
}
 
Example 9
Source File: JsonLog4j2Layout.java    From javalite with Apache License 2.0 5 votes vote down vote up
/**
 * Formats a {@link org.apache.logging.log4j.core.LogEvent}.
 *
 * @param event The LogEvent.
 * @return The XML representation of the LogEvent.
 */
@Override
public String toSerializable(final LogEvent event) {
    String loggerName = event.getLoggerName();
    String level = event.getLevel().toString();
    String message = event.getMessage().getFormattedMessage();
    if (!message.startsWith("{") && !message.startsWith("[")) {
        message = "\"" + message + "\"";
    }
    String threadName = event.getThreadName();
    Date timeStamp = new Date(event.getTimeMillis());
    String context = Context.toJSON();

    Throwable throwable = event.getThrown();

    String exception = "";
    if (throwable != null) {
        exception = ",\"exception\":{\"message\":\"";
        String exceptionMessage = throwable.getMessage() != null ? throwable.getMessage() : "";
        //need to be careful here, sanitizing, since the message may already contain a chunk of JSON, so escaping or cleaning double quotes is not prudent:)
        exception += sanitize(exceptionMessage, false, '\n', '\t', '\r') + "\",\"stacktrace\":\"" + escapeControlChars(Util.getStackTraceString(throwable)) + "\"}";
    }

    String contextJson = context != null ? ",\"context\":" + context : "";

    String timestampString = this.simpleDateFormat == null ? timeStamp.toString() : simpleDateFormat.format(timeStamp);

    return "{\"level\":\"" + level + "\",\"timestamp\":\"" + timestampString
            + "\",\"thread\":\"" + threadName + "\",\"logger\":\"" + loggerName + "\",\"message\":"
            + message + contextJson + exception + "}" + System.getProperty("line.separator");
}
 
Example 10
Source File: KafkaAppender.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void append(final LogEvent event) {
    if (event.getLoggerName() != null && event.getLoggerName().startsWith("org.apache.kafka")) {
        LOGGER.warn("Recursive logging from [{}] for appender [{}].", event.getLoggerName(), getName());
    } else {
        try {
            tryAppend(event);
        } catch (final Exception e) {
            error("Unable to write to Kafka in appender [" + getName() + "]", event, e);
        }
    }
}
 
Example 11
Source File: EventLookup.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Looks up the value from the logging event.
 * @param event The current LogEvent.
 * @param key  the key to be looked up.
 * @return The value of the specified log event field.
 */
@Override
public String lookup(final LogEvent event, final String key) {
    switch (key) {
        case "Marker": {
            return event.getMarker() != null ? event.getMarker().getName() : null;
        }
        case "ThreadName": {
            return event.getThreadName();
        }
        case "Level": {
            return event.getLevel().toString();
        }
        case "ThreadId": {
            return Long.toString(event.getThreadId());
        }
        case "Timestamp": {
            return Long.toString(event.getTimeMillis());
        }
        case "Exception": {
            if (event.getThrown() != null) {
                return event.getThrown().getClass().getSimpleName();
            }
            if (event.getThrownProxy() != null) {
                return event.getThrownProxy().getName();
            }
            return null;
        }
        case "Logger": {
            return event.getLoggerName();
        }
        case "Message": {
            return event.getMessage().getFormattedMessage();
        }
        default: {
            return null;
        }
    }
}
 
Example 12
Source File: LoggerNameLevelRewritePolicy.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public LogEvent rewrite(final LogEvent event) {
    if (event.getLoggerName() == null || !event.getLoggerName().startsWith(loggerName)) {
        return event;
    }
    final Level sourceLevel = event.getLevel();
    final Level newLevel = map.get(sourceLevel);
    if (newLevel == null || newLevel == sourceLevel) {
        return event;
    }
    final LogEvent result = new Log4jLogEvent.Builder(event).setLevel(newLevel).build();
    return result;
}
 
Example 13
Source File: Log4jLogEvent.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
public Builder(final LogEvent other) {
    Objects.requireNonNull(other);
    if (other instanceof RingBufferLogEvent) {
        ((RingBufferLogEvent) other).initializeBuilder(this);
        return;
    }
    if (other instanceof MutableLogEvent) {
        ((MutableLogEvent) other).initializeBuilder(this);
        return;
    }
    this.loggerFqcn = other.getLoggerFqcn();
    this.marker = other.getMarker();
    this.level = other.getLevel();
    this.loggerName = other.getLoggerName();
    this.message = other.getMessage();
    this.instant.initFrom(other.getInstant());
    this.thrown = other.getThrown();
    this.contextStack = other.getContextStack();
    this.includeLocation = other.isIncludeLocation();
    this.endOfBatch = other.isEndOfBatch();
    this.nanoTime = other.getNanoTime();

    // Avoid unnecessarily initializing thrownProxy, threadName and source if possible
    if (other instanceof Log4jLogEvent) {
        final Log4jLogEvent evt = (Log4jLogEvent) other;
        this.contextData = evt.contextData;
        this.thrownProxy = evt.thrownProxy;
        this.source = evt.source;
        this.threadId = evt.threadId;
        this.threadName = evt.threadName;
        this.threadPriority = evt.threadPriority;
    } else {
        if (other.getContextData() instanceof StringMap) {
            this.contextData = (StringMap) other.getContextData();
        } else {
            if (this.contextData.isFrozen()) {
                this.contextData = ContextDataFactory.createContextData();
            } else {
                this.contextData.clear();
            }
            this.contextData.putAll(other.getContextData());

        }
        this.thrownProxy = other.getThrownProxy();
        this.source = other.getSource();
        this.threadId = other.getThreadId();
        this.threadName = other.getThreadName();
        this.threadPriority = other.getThreadPriority();
    }
}