Reputation: 4239
How do get Keycloak 4.5.0.Final to log in JSON format?
I'm running Keycloak in Kubernetes using the Helm chart, which provides hooks for running JBoss CLI scripts (keycloak.cli.custom
) or shell scripts (keycloak.preStartScript
).
But I would like to avoid having to customize the Docker image.
Upvotes: 5
Views: 6255
Reputation: 315
(The question asked about 4.5.0, but this might be helpful for more modern versions - e.g. 21.0.2 - as people may come across this through searches etc as I did.)
You can enable JSON logging with an option on startup, as described here:
bin/kc.[sh|bat] start --log-console-output=json
Upvotes: 1
Reputation: 2105
I'm using keycloak 8.0.1 so this may not apply to your 4.5 version but all I had to do was to supply a jboss cli script to use the json formatter instead of the PATTERN formatter
# Undertow HTTP Server Configuration
echo Started configuring Undertow ....
# Create a new log formatter to output json with full stacktrace details
/subsystem=logging/json-formatter=SUMO_FORMATTER:add(pretty-print=false, exception-output-type=detailed-and-formatted, print-details=false)
# Disable the original console output that was in plain text format
/subsystem=logging/console-handler=CONSOLE/:write-attribute(name=enabled,value=false)
# Create a new console logger that uses the new json formatter
/subsystem=logging/console-handler=SUMO_CONSOLE:add(enabled=true, named-formatter=SUMO_FORMATTER)
# Make the root logger use the new console logger
/subsystem=logging/root-logger=ROOT/:write-attribute(name=handlers,value=["SUMO_CONSOLE"])
echo ... Completed configuring Undertow
There's some doco on it here
Upvotes: 3
Reputation: 6914
Following this great article (which also link to Github), one can achieve JSON logs following these steps:
deployments
folder (please follow the article to get the full details)Final code may looke something like this:
public class MyEventListenerProvider implements EventListenerProvider {
public MyEventListenerProvider() {
// use c'tor to init variables / connections / etc. - plugin load hook
this.jsonMapper = new ObjectMapper();
}
ObjectMapper jsonMapper;
private stringify(Object obj) {
try {
return this.jsonMapper.writeValueAsString(obj);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
@Override
public void onEvent(Event event) {
System.out.println(this.stringify(event));
}
@Override
public void onEvent(AdminEvent adminEvent, boolean b) {
System.out.println(this.stringify(adminEvent));
}
@Override
public void close() {
// use close to close connections / reset variables - plugin unload hook
}
This sample is written on the fly (it's partial, sorry if there are compilation errors) and uses Jackson lib as described here
Upvotes: 2