Skip to content

Commit

Permalink
Merge pull request #3 from kumuluz/feature/contextData
Browse files Browse the repository at this point in the history
Added context data to Log4j logger
  • Loading branch information
jmezna authored Jul 10, 2019
2 parents 1e52e8c + b655b89 commit 693d14a
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions log4j2/src/main/java/com/kumuluz/ee/logs/Log4j2LogCommons.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.MarkerManager;

import java.util.HashMap;
import java.util.ServiceLoader;

/**
* Kumuluz-logs logger interface
*
Expand Down Expand Up @@ -165,6 +168,10 @@ private void logEnd(LogResourceContext logResourceContext) {
* @param logMessage object defining LogMessage
*/
private void log(LogLevel level, Marker marker, Marker parentMarker, LogMessage logMessage) {
HashMap<String, String> context = new HashMap<>();

context = addContextData(context);


String message;
if (logMessage == null || logMessage.getMessage() == null) {
Expand All @@ -174,13 +181,31 @@ private void log(LogLevel level, Marker marker, Marker parentMarker, LogMessage
}

if (logMessage != null && logMessage.getFields() != null) {
CloseableThreadContext.putAll(context);
try (final CloseableThreadContext.Instance ctc = CloseableThreadContext.putAll(logMessage.getFields())) {
logger.log(Log4j2LogUtil.convertToLog4j2Level(level), MarkerManager.getMarker(marker.toString())
.setParents(MarkerManager.getMarker(parentMarker.toString())), message);
}
} else {
logger.log(Log4j2LogUtil.convertToLog4j2Level(level), MarkerManager.getMarker(marker.toString())
.setParents(MarkerManager.getMarker(parentMarker.toString())), message);

}
}

/**
* @param data defines input data
* @return data with appended context data
*/
private HashMap<String, String> addContextData(HashMap<String, String> data) {

ServiceLoader.load(RequestContext.class).forEach(provider -> {
HashMap<String, String> context = provider.getContext();
if (context != null) {
data.putAll(context);
}
});

return data;
}
}

0 comments on commit 693d14a

Please sign in to comment.