Created
February 22, 2019 08:47
-
-
Save mnuessler/bcacce04676b6ca17c8a20f33344f51c to your computer and use it in GitHub Desktop.
A log4j2 rewrite policy that maps the log level to StackDriver severity and stores the value inside the context.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.github.mnuessler.log4j; | |
import org.apache.logging.log4j.Level; | |
import org.apache.logging.log4j.core.Core; | |
import org.apache.logging.log4j.core.LogEvent; | |
import org.apache.logging.log4j.core.appender.rewrite.RewritePolicy; | |
import org.apache.logging.log4j.core.config.plugins.Plugin; | |
import org.apache.logging.log4j.core.config.plugins.PluginFactory; | |
import org.apache.logging.log4j.core.impl.ContextDataFactory; | |
import org.apache.logging.log4j.core.impl.Log4jLogEvent; | |
import org.apache.logging.log4j.util.StringMap; | |
/** | |
* Maps the log4j level to StackDriver severity and stores the value inside the context, so that it can | |
* later be added as an additional field in the JSON appender. | |
*/ | |
@Plugin(name = "StackDriverRewritePolicy", category = Core.CATEGORY_NAME, elementType = "rewritePolicy") | |
public class StackDriverRewritePolicy implements RewritePolicy { | |
private StackDriverRewritePolicy() { | |
} | |
@Override | |
public LogEvent rewrite(final LogEvent source) { | |
final StringMap newContextData = ContextDataFactory.createContextData(source.getContextData()); | |
newContextData.putValue("severity", severityForLevel(source.getLevel())); | |
return new Log4jLogEvent.Builder(source).setContextData(newContextData).build(); | |
} | |
private static String severityForLevel(final Level level) { | |
switch (level.name()) { | |
case "TRACE": | |
case "DEBUG": | |
case "ALL": | |
return "DEBUG"; | |
case "INFO": | |
return "INFO"; | |
case "WARN": | |
return "WARNING"; | |
case "ERROR": | |
return "ERROR"; | |
case "FATAL": | |
return "EMERGENCY"; | |
default: | |
return "DEFAULT"; | |
} | |
} | |
@PluginFactory | |
public static StackDriverRewritePolicy createPolicy() { | |
return new StackDriverRewritePolicy(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment