How to create custom RewritePolicy in log4j2? -
i'm trying code own rewritepolicy in log4j2. documentation states :
rewritepolicy interface allows implementations inspect , possibly modify logevents before passed appender. rewritepolicy declares single method named rewrite must implemented. method passed logevent , can return same event or create new one.
here's java class :
public final class markerinjectorrewritepolicy implements rewritepolicy { @override public logevent rewrite(final logevent event) { final marker marker = event.getmarker(); if (marker == null) return event; // if there's marker, add threadcontextmap routingappender can routes log messages event.getcontextmap().put("_marker", marker.getname()); return event; } }
here's yaml configuration file :
rewrite: name: rewrite_appender appenderref: ref: routing_appender propertiesrewritepolicy: property: - name: foo value: bar
however have no idea how inject in configuration file. how can make work @ runtime?
your custom rewrite policy should coded log4j2 plugin. enables configure custom rewritepolicy in rewriteappender.
@plugin(name = "injectmarkerpolicy", category = "core", elementtype = "rewritepolicy", printobject = true) public final class markerinjectorrewritepolicy implements rewritepolicy { @override public logevent rewrite(final logevent event) { final marker marker = event.getmarker(); if (marker == null) return event; // if there's marker, add threadcontextmap // routingappender can routes log messages // event's context map immutable, need make copy... map<string, string> mdc = new hashmap<>(event.getcontextmap()); mdc.put("_marker", marker.getname()); logevent result = new log4jlogevent(event.getloggername(), event.getmarker(), event.getloggerfqcn(), event.getlevel(), event.getmessage(), event.getthrown(), mdc, event.getcontextstack(), event.getthreadname(), event.getsource(), event.gettimemillis()); return result; } }
example config (todo: set correct value packages attribute):
<configuration status="trace" packages="my.rewritepolicy.plugin.package"> <appenders> <console name="stdout"> <patternlayout pattern="[%-5level] %c{1.} %m%n"/> </console> <rewrite name="rewrite"> <injectmarkerpolicy /> <appenderref ref="stdout"/> </rewrite> </appenders> <loggers> <root level="trace"> <appenderref ref="rewrite"/> </root> </loggers> </configuration>
Comments
Post a Comment