logging,  how-to

Changing the log format in Spring Boot

Changing the log format in Spring Boot

Do you know that hours of trial and error can save you minutes of reading documentation? Well, that was not the case today because I wasn’t able to find that (although it is).

The Internet is full of (crappy) pages explaining how to change log format replacing the original files (logback-spring.xml, …) but we didn’t want to change and write ALL the configuration. We just wanted to add a field to the log.

You can find that param on the official documentation, but it is easily missed.

logging.pattern.level: <your marvelous pattern>

Do you know how I found that? I had to browse Sleuth code to know how they change it.

	public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
		Map<String, Object> map = new HashMap<String, Object>();
		// This doesn't work with all logging systems but it's a useful default so you see
		// traces in logs without having to configure it.
		if (Boolean.parseBoolean(environment.getProperty("spring.sleuth.enabled", "true"))) {
					"%5p [${spring.zipkin.service.name:" + "${spring.application.name:}},%X{traceId:-},%X{spanId:-}]");
		addOrReplace(environment.getPropertySources(), map);

So easy once you know it.

Ours now is:

"%5p [${spring.application.name:},%X{traceId:-},%X{spanId:-},%X{user_id}]"

user_id is a variable set in the MDC on every request.