Sub topic 8
Customizing the log pattern
This chapter assumes you can set properties in application.properties or application.yml and that you know the log levels and the console and file output from earlier chapters. Here you change what each log line looks like.
What a pattern is
A log pattern is a template that Logback fills in for every log event. It mixes literal text with conversion words. A conversion word starts with % and names a piece of the event, such as the time, the level, or the message.
The pattern is a rendering step only. It does not change which events are logged. Levels and logger names decide that.
Replace that placeholder with the real diagram below.
Each appender has its own pattern. That is why Spring Boot has separate properties for the console and the file.
The properties that control the pattern
Spring Boot exposes four properties. Each one changes a different amount of the default format.
| Property | What it replaces | Example value |
|---|---|---|
| `logging.pattern.console` | The whole console pattern | `%d{HH:mm:ss} %-5level %msg%n` |
| `logging.pattern.file` | The whole file pattern | `%d %-5level [%thread] %logger - %msg%n` |
| `logging.pattern.dateformat` | Only the timestamp format in the default patterns | `yyyy-MM-dd HH:mm:ss.SSS` |
| `logging.pattern.level` | Only the level part in the default patterns | `%5p [%X{requestId:-none}]` |
Prefer the narrow properties when they are enough. logging.pattern.dateformat and logging.pattern.level keep Boot's defaults for everything else, including colors, the process ID, and exception formatting. A full logging.pattern.console replaces all of that, so you must supply every piece you still want.
Reading the default pattern
The default console pattern in Spring Boot 3.x looks roughly like this. The exact text differs slightly between versions.
%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}It is dense, but it uses the same few parts you will use in your own pattern:
%d{...}prints the timestamp.%5pprints the level, padded to 5 characters.%15.15tprints the thread name, padded and cut to exactly 15 characters.%-40.40logger{39}prints the logger name, shortened to fit 40 characters.%m%nprints the message and a line break.%wExprints the exception stack trace, if there is one.%clr(...){color}is a Spring Boot addition that colors text when the terminal supports it.
Common conversion words
| Word | Output |
|---|---|
| `%d{pattern}` | Timestamp. `%d{HH:mm:ss.SSS}` prints `14:03:22.417`. |
| `%level` or `%p` | The level, such as `INFO`. |
| `%thread` or `%t` | The thread name. |
| `%logger{n}` | The logger name, abbreviated to about `n` characters. |
| `%msg` or `%m` | The formatted message. |
| `%n` | A platform-specific line break. |
| `%X{key}` | A value from the MDC. |
| `%X{key:-default}` | The MDC value, or `default` if the key is not set. |
| `%ex` or `%wEx` | The exception and its stack trace. |
Padding and truncation
A number after the % sets a minimum width. A minus sign left-justifies the text. A dot and a second number sets a maximum width.
%-5levelpads on the right to 5 characters, soINFOandERRORline up.%5levelpads on the left.%.20loggercuts the name to 20 characters, from the left.%-20.20loggeralways produces exactly 20 characters.
%logger{36} is different from truncation. It abbreviates package names. com.example.orders.OrderService becomes c.e.orders.OrderService when space is short. The class name is kept whole, so the result can still be longer than 36 characters.
A worked example
Here is a custom console pattern that shows a time, a padded level, a request ID from the MDC, a short logger name, and the message.
logging.pattern.console=%d{HH:mm:ss.SSS} %-5level [%X{requestId:-none}] %logger{36} - %msg%n
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] [%X{requestId:-none}] %logger{36} - %msg%nThe file pattern keeps the full date and adds the thread name. Files are read later, often across days, so they need more context than a console you watch live.
To see the output, add a small runner to a Spring Boot application:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class PatternDemo implements CommandLineRunner {
private static final Logger log = LoggerFactory.getLogger(PatternDemo.class);
@Override
public void run(String... args) {
log.info("No request id yet");
MDC.put("requestId", "req-42");
try {
log.warn("Now with a request id");
} finally {
MDC.remove("requestId");
}
}
}With the console pattern above, the output looks like this:
14:03:22.417 INFO [none] c.e.demo.PatternDemo - No request id yet
14:03:22.418 WARN [req-42] c.e.demo.PatternDemo - Now with a request idThe :-none default is what keeps the first line readable. Without it, Logback prints an empty string for a missing key, which leaves empty brackets [].
Using YAML
In application.yml, a value that starts with % must be quoted. A bare % at the start of a YAML scalar is a syntax error.
logging:
pattern:
dateformat: "yyyy-MM-dd HH:mm:ss.SSS"
console: "%d{HH:mm:ss.SSS} %-5level [%X{requestId:-none}] %logger{36} - %msg%n"Single quotes inside a date format, such as yyyy-MM-dd'T'HH:mm, are valid in both formats. In YAML, wrap the whole value in double quotes and keep the single quotes inside.
Exceptions and custom patterns
When a log call passes an exception as the last argument, the pattern decides how the stack trace appears. Logback's pattern layout adds exception output at the end of the line if your pattern has no exception word. If you want to control it yourself, end the pattern with %n%wEx. Boot's %wEx wraps long lines of the stack trace and applies the logging.exception-conversion-word setting. Put it after %n, because the stack trace starts on a new line.
When properties are not enough
Properties give you a pattern per appender. They cannot add a third appender or send one logger to a different file. For that you write your own logback-spring.xml, covered in the next chapters. Note that Boot's default includes read the logging.pattern.* values. If you declare your own appender with its own <pattern>, the properties no longer apply to it.
Pitfalls
- Slow conversion words.
%L(line number),%M(method), and%C(caller class) make Logback capture the call stack for every event. This costs real time in hot paths. Avoid them in production. - Forgetting
%n. Without it, all lines run together. - Unquoted YAML. The application fails to start with a parsing error.
- Mixing up
%msgand the format.%msgalready contains the substituted{}values. You do not add them in the pattern. - Sensitive data in the pattern. Anything in the MDC appears on every line. Never put tokens or personal data there.
- Colors in files.
%clris meant for terminals. Boot removes ANSI codes for file output by default, but custom patterns copied between console and file settings can leak escape codes if you force colors on.
Exercise
You want every console line to start with a time like 14:03:22.417, then the level left-aligned to 5 characters, then the message. You also want the existing colors and stack-trace handling of Spring Boot's default pattern to stay. Which properties would you set, and why is a full logging.pattern.console a worse choice here?
Show answer
Set logging.pattern.dateformat=HH:mm:ss.SSS and, if you want left alignment of the level, logging.pattern.level=%-5p. These two replace only the timestamp and level parts of the default pattern, so colors, the process ID, and %wEx stay. A full logging.pattern.console replaces the whole pattern, so you would have to rebuild colors and exception handling yourself. Note that the default pattern still prints other parts such as the thread and logger, so if you want only time, level, and message, you do need a full console pattern such as %d{HH:mm:ss.SSS} %-5level %msg%n and accept losing the defaults.
Exercise
A line prints [] where the request ID should be when no request is active. What change to the pattern fixes it, and what does it print instead?
Show answer
Change %X{requestId} to %X{requestId:-none}. When the MDC has no requestId, the line shows [none] instead of [].