All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.chavaillaz.appender.log4j.converter.DefaultEventConverter Maven / Gradle / Ivy

package com.chavaillaz.appender.log4j.converter;

import com.chavaillaz.appender.log4j.ElasticsearchAppender;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.ThrowableInformation;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Default converter converting the following fields:
 * 
    *
  • datetime: Date of logging event
  • *
  • host: Taken from appender configuration)
  • *
  • environment: Taken from appender configuration)
  • *
  • application: Taken from appender configuration)
  • *
  • logger: Logger of logging event
  • *
  • level: Level of logging event
  • *
  • logmessage: Message of the logging event
  • *
  • thread: Thread that created the logging event
  • *
*

All the MDC fields will also be added as is (if they not already exist).

*

In case the event contains an exception, it also includes the fields:

*
    *
  • class: Class of the exception
  • *
  • stacktrace: Stacktrace of the exception
  • *
*/ public class DefaultEventConverter implements EventConverter { @Override public String getDateField() { return "datetime"; } @Override public Map convert(ElasticsearchAppender appender, LoggingEvent event) { Map data = new HashMap<>(); writeBasic(data, appender, event); writeThrowable(data, event); writeMDC(data, event); return data; } protected void writeBasic(Map json, ElasticsearchAppender appender, LoggingEvent event) { json.put(getDateField(), new Date(event.getTimeStamp()).toInstant().toString()); json.put("host", appender.getHostName()); json.put("environment", appender.getEnvironmentName()); json.put("application", appender.getApplicationName()); json.put("logger", event.getLoggerName()); json.put("level", event.getLevel().toString()); json.put("logmessage", event.getMessage()); json.put("thread", event.getThreadName()); } protected void writeMDC(Map json, LoggingEvent event) { for (Object key : event.getProperties().keySet()) { json.putIfAbsent(key.toString(), event.getProperties().get(key).toString()); } } protected void writeThrowable(Map json, LoggingEvent event) { ThrowableInformation throwableInformation = event.getThrowableInformation(); if (throwableInformation != null) { Throwable throwable = throwableInformation.getThrowable(); json.put("class", throwable.getClass().getCanonicalName()); json.put("stacktrace", getStackTrace(throwable)); } } protected String getStackTrace(Throwable throwable) { Writer result = new StringWriter(); PrintWriter printWriter = new PrintWriter(result); throwable.printStackTrace(printWriter); return result.toString(); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy