Reputation: 583
I need to generate a random string for a correlation key for each log message and I found that there is a way to generate UUID in log4j configuration file.
There is a mention of UUID
on https://logging.apache.org/log4j/2.x/manual/layouts.html, but it doesn't say anything about how to use it.
I am trying to set this as a value for a key in my JsonLayout.
appender.rolling.layout.external-correlation-id.type = KeyValuePair
appender.rolling.layout.external-correlation-id.key = external-correlation-id
appender.rolling.layout.external-correlation-id.value = %u{"RANDOM"}
But that doesn't do anything. It just adds the literal string in the log message ... "external-correlation-id":"%u{\"RANDOM\"}" ...
.
How can I get a random string to set it in the log message? Is there a way for me to atleast directly call the UUID.randomUUID()
in thelog4j properties file?
I don't want to use MDC for this and am looking for a way to do it directly from the log4j configuration file.
Any other help with this will be very appreciated.
Upvotes: 2
Views: 1809
Reputation: 391
I've done something similar in a JsonLayout in a KeyValuePair using a custom StrLookup.
The code below shows a simple example of returning a UUID every time a message is logged using a custom Lookup. One would add the ability to have different operations per key etc. but this works.
import java.util.UUID;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.lookup.StrLookup;
@Plugin(name = "dyn", category = "Lookup")
public class DynamicLookup implements StrLookup {
@Override
public String lookup(String key) {
if("uuid".equals(key)) {
return UUID.randomUUID().toString();
} else {
return null;
}
}
@Override
public String lookup(LogEvent event, String key) {
if("uuid".equals(key)) {
return UUID.randomUUID().toString();
} else {
return null;
}
}
}
Then reference the Lookup using double $$ to have the value evaluated every message instead of just once.
<KeyValuePair key="event_id" value="$${dyn:uuid:-}"/>
Upvotes: 3