Think a log pattern is just text?
Think again.
A single percent sign (%) plus a conversion character like %p or %d controls what appears in every line, and some choices cost CPU.
This post walks through log4j format pattern conversion characters and syntax, shows date formats, width and truncation modifiers, caller/context options, and practical patterns for console and file logging.
You’ll also get performance tips: which specifiers to avoid in hot paths and how to balance detail with throughput.
Understanding log4j Format Pattern Syntax and Core Conversion Characters

Every log4j conversion pattern starts with a percent sign (%) followed by a conversion character that tells the logger what information to insert. Literal text like brackets, hyphens, or spaces appear exactly as typed in your pattern string. Need to print an actual percent sign in your log output? Escape it by typing %%.
The most essential conversion specifiers control the core elements of every log line:
- %p – log level (INFO, DEBUG, WARN, ERROR, FATAL)
- %d – date and timestamp, supports custom formats and predefined keywords
- %c – logger or category name
- %m – the application’s log message
- %n – platform newline character
- %t – thread name that generated the log event
- %r – milliseconds elapsed since the JVM started
- %C – fully qualified class name where the log call occurred
Additional conversion characters like %M (method name), %F (source file name), and %L (line number) pinpoint the exact code location that triggered the log statement. Context patterns use %x for nested diagnostic context (NDC) and %X for mapped diagnostic context (MDC), which inject request-scoped metadata like user IDs or transaction tokens.
Some conversions carry a steep runtime cost. The %C, %M, %F, and %L specifiers are slow because they walk the call stack to extract caller information. Reserve these for local debugging or low-traffic environments. In production systems handling thousands of requests per second, stack inspection can degrade throughput and increase CPU usage noticeably.
log4j Format Pattern Date and Time Formatting Options

Log4j offers two approaches to timestamp formatting: custom date patterns using Java’s SimpleDateFormat syntax, and predefined keywords that apply common formats instantly. Custom patterns look like %d{MM-dd-yyyy HH:mm:ss} and let you control every element of the timestamp. Predefined keywords like ISO8601, ABSOLUTE, and DATE provide standardized formats without memorizing pattern strings.
Here are the most common date formatting patterns and their outputs:
- %d{MM-dd-yyyy HH:mm:ss} – “11-02-2012 23:08:10”
- %d{MM-dd-yyyy HH:mm:ss,SSS} – “11-02-2012 23:09:38,304” (includes milliseconds)
- %d{ISO8601} – “2012-11-02 23:13:58,300” (standard sortable format)
- %d{ABSOLUTE} – “23:17:07,097” (time only, no date)
- %d{DATE} – “02 Nov 2012 23:18:19,547” (human-friendly format)
Performance matters when formatting timestamps. JDK date formatters can introduce latency under load, while Log4j’s built-in formatters process dates much faster. Stick with built-in keywords (ISO8601, ABSOLUTE, DATE) or use Log4j’s optimized custom formatters when millisecond precision matters. High-throughput applications should benchmark date formatting choices, since every log statement pays the formatting cost.
log4j PatternLayout Format Modifiers for Alignment, Width, and Truncation

Format modifiers adjust how each conversion character prints by controlling alignment, minimum width, and maximum length. A modifier sits between the percent sign and the conversion character. The syntax %-5p tells log4j to left-justify the log level within a field five characters wide, padding with spaces if needed. Without the minus sign, %5p right-justifies the level instead.
Truncation modifiers limit output length to keep logs readable. The pattern %.30c restricts the logger name to 30 characters maximum, cutting from the left when names exceed that length. Combined width and truncation looks like %20.30c, which pads the logger name to at least 20 characters while capping it at 30. The %c{1} precision modifier is different. It reduces the logger name to just the last component, turning “com.example.MyService” into “MyService.”
| Modifier | Meaning | Example Output |
|---|---|---|
| %-5p | Left-justify level in 5-character field | “INFO ” (two trailing spaces) |
| %5p | Right-justify level in 5-character field | ” INFO” (two leading spaces) |
| %.30c | Truncate logger name to max 30 chars | “…example.service.MyService” |
| %c{1} | Print only last logger name component | “MyService” |
log4j Pattern Examples for Console and File Logging

A simple console pattern balances readability and speed. The pattern [%p] %c – %m%n prints the log level in brackets, the logger name, a separator, the message, and a newline. This minimal format works well when you’re tailing logs during development and don’t need timestamps for every line.
Production applications typically need timestamps and more context. The pattern [%p] %d{MM-dd-yyyy HH:mm:ss,SSS} %c %M – %m%n adds a custom date format with milliseconds, the logger name, and the method name. File appenders often use %d{ISO8601} %-5p %c{1} – %m%n, which gives you an ISO timestamp, a left-justified log level, and a compact logger name. This format sorts correctly and parses easily in log analysis tools.
When building scripts to parse log files, pick a delimiter that won’t appear in typical messages. The pipe character (|) is uncommon in program output and simplifies parsing with Perl, Ruby, or awk. A pipe-delimited pattern like %d{ISO8601}|%-5p|%c|%m%n separates timestamp, level, logger, and message into distinct columns.
- Simple console: [%p] %c – %m%n – fast, minimal output for development
- Standard detailed: [%p] %d{MM-dd-yyyy HH:mm:ss,SSS} %c %M – %m%n – includes method and milliseconds
- ISO timestamp: %d{ISO8601} %-5p %c{1} – %m%n – file-friendly, compact logger
- Pipe-delimited: %d{ISO8601}|%-5p|%c|%m%n – easy to parse with scripts
- Left-justified level: %d{HH:mm:ss} %-6p %c{1} – %m%n – aligned columns, time-only timestamp
- Custom date style: %d{dd/MM/yyyy HH:mm:ss.SSS} %-5p %c – %m%n – European date format with high precision
Detailed Caller and Context Information in log4j Format Patterns

Caller-based conversion characters extract the exact code location that generated a log event. The %C specifier prints the fully qualified class name, %M gives you the method name, %F shows the source file, and %L provides the line number. Combined, these let you write patterns like %C.%M(%F:%L) that output “com.example.MyClass.processOrder(MyClass.java:142).”
These conversions are expensive. Log4j must walk the call stack to resolve class, method, file, and line information, an operation that becomes slow under load. Many production patterns omit these entirely or include only the line number for troubleshooting.
- %C – fully qualified class name; slow, avoid in high-throughput logs
- %M – method name; requires stack walking, use sparingly
- %F – source file name; costly lookup, helpful during debugging
- %L – line number; less expensive than class/method but still has overhead
- %x – nested diagnostic context (NDC); adds hierarchical context like request flow steps
- %X{key} – mapped diagnostic context (MDC); injects key-value pairs such as userId or requestId for tracing
- %ex or %throwable – exception stack trace; essential for error logs
A fully detailed pattern combining thread, caller, MDC, and exceptions looks like %d{yyyy-MM-dd HH:mm:ss.SSS} %-5p [%t] %c{1} %X{userId} %C.%M(%F:%L) – %m%n %ex. This pattern captures timestamp, level, thread name, compact logger, user ID from MDC, class.method(file:line), message, newline, and exception trace. Reserve this level of detail for debugging sessions or low-volume error logs.
Configuring log4j Format Pattern in XML and Properties Files

Log4j2 XML configurations nest the pattern inside a PatternLayout element. A console appender might look like this:
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="[%p] %d{ISO8601} %c %M - %m%n"/>
</Console>
</Appenders>
Properties-based configurations set the pattern on the appender’s layout. For a console appender in Log4j2, you’d write appender.console.layout.type=PatternLayout followed by appender.console.layout.pattern=%d{ISO8601} %-6p %c{1} – %m%n. The appender name (console in this case) must match everywhere it appears in your config file.
| Format | Configuration Snippet | Notes |
|---|---|---|
| Log4j2 XML | <PatternLayout pattern=”[%p] %d{ISO8601} %c %M – %m%n”/> | Nested inside <Appenders> section |
| Log4j2 Properties | appender.console.layout.pattern=%d{ISO8601} %-6p %c{1} – %m%n | Appender name must match throughout file |
| Log4j 1.x Properties | log4j.appender.console.layout.ConversionPattern=%d{ISO8601} %-5p %c{1} – %m%n | Legacy syntax for older Log4j versions |
Performance Considerations for log4j Format Patterns in Production

The %C, %M, %F, and %L conversions are slow because they inspect the call stack on every log statement. In a high-throughput service logging thousands of events per second, stack walking can spike CPU usage and degrade request latency. Date formatting using JDK’s SimpleDateFormat can also introduce bottlenecks, while Log4j’s built-in formatters process timestamps much faster.
Keep production patterns lean by following these practices:
- Avoid %C, %M, %F, and %L in hot code paths. Enable caller lookups only when diagnosing specific issues.
- Use predefined date keywords (ISO8601, ABSOLUTE, DATE) instead of complex custom date patterns to get Log4j’s optimized formatters.
- Reduce logger name verbosity with %c{1} or %c{2} to limit string allocations and shorten log lines.
- Profile your logging overhead under realistic load. If logs consume more than 5% of CPU, simplify your patterns or reduce log volume.
Troubleshooting log4j Format Pattern Issues

Syntax errors usually surface as malformed percent sequences or missing braces around date patterns. Typing %d MM-dd-yyyy instead of %d{MM-dd-yyyy} will print “MM-dd-yyyy” literally instead of formatting the date. If your logs show unexpected “null” values for caller information, the stack walker couldn’t resolve the source location. This happens when code is heavily optimized or obfuscated.
Logger precision set to zero (%c{0}) produces blank fields because it asks for zero package components. Increment the precision to at least 1 to see the final logger name segment. When a literal percent sign disappears from output, remember to escape it with %% in your pattern string. Date patterns that produce “invalid date format” errors often use unsupported tokens. Log4j date formatting follows SimpleDateFormat conventions, so check that your pattern letters match Java’s date/time syntax.
- Missing braces around date pattern (%d MM-dd-yyyy) prints the pattern literally instead of a formatted date
- Caller info (%C, %M, %F, %L) showing null means the stack walker couldn’t resolve code location
- Logger precision %c{0} produces blank output; use %c{1} or higher to print name components
- Literal percent sign vanishes unless escaped as %%
- “Invalid date format” errors point to unsupported SimpleDateFormat tokens in your %d{pattern} string
Final Words
We unpacked how each log4j format pattern token turns into log output — from %p and %d to %c and %m. You got date/time options, alignment and truncation tricks, ready-to-use console/file patterns, caller/context specifiers, and config snippets.
We flagged costly lookups (%C, %M, %F, %L) and noted faster built-in date formatters, plus quick troubleshooting steps.
Apply the examples, avoid expensive conversions in high-throughput paths, and tweak patterns in your config files. Use this guide to shape a clear, performant log4j format pattern that keeps debugging fast and your logs useful.
FAQ
Q: What is the log4j format pattern syntax and how do conversion patterns start?
A: The log4j format pattern syntax defines message layout; every conversion begins with a % symbol, literal characters pass through, and %% prints a literal percent sign.
Q: What are the core conversion specifiers I should know?
A: The core conversion specifiers are %p (level), %d (timestamp), %c (logger), %m (message), %n (newline), %M (method), %F (file), and %L (line), used in most layouts.
Q: How do I format dates and timestamps in log4j patterns?
A: You format dates with %d{pattern} or keywords ISO8601, ABSOLUTE, DATE; include milliseconds with SSS. Prefer Log4j built-in formatters over JDK ones for speed.
Q: How do format modifiers control alignment, width, and truncation?
A: Format modifiers control layout: %-5p left‑justifies, %5p right‑justifies, %.30c truncates to 30 chars, %20.30c pads then truncates, and %c{1} shows the final logger segment.
Q: What are ready-to-use pattern examples for console and file logging?
A: Ready examples: simple console “[%p] %c – %m%n”; detailed “[%p] %d{MM-dd-yyyy HH:mm:ss,SSS} %c %M – %m%n”; file-friendly “%d{ISO8601} %-5p %c{1} – %m%n”.
Q: When should I include caller information or context (MDC/NDC) in patterns?
A: You should include caller info (%C,%M,%F,%L) only for debugging because it’s slow; use MDC (%X) or NDC (%x) for lightweight tracing like userId or requestId.
Q: How do I configure PatternLayout in XML and properties files?
A: You configure PatternLayout by setting the pattern attribute or property: XML
Q: What performance considerations matter for log4j patterns in production?
A: The key production risks are %C, %M, %F, %L (extremely slow due to stack walking) and JDK date formatters; avoid caller lookups in high‑throughput code and prefer built‑in formatters.
Q: How do I troubleshoot common log4j pattern issues?
A: Troubleshoot by fixing malformed % sequences and missing braces, using %% for literal percent, replacing unsupported date tokens, and checking logger precision or unresolved stack walkers.
