skip to content

In SLF4J placeholder logging, how do you print a literal `{}` in a message, and how are null values and array arguments rendered?

level: juniorimportance: should knowfreq 52%

answer

  1. only the exact pair is an anchor
  2. escape the opening brace only
  3. a backslash written twice in Java source
  4. null prints as the word null
  5. a String array alone becomes the argument list

basics

~20 s

Put a backslash before the brace, written \{} in a Java string literal, and SLF4J prints {} without using up an argument. A null argument prints as null; arrays print as [a, b], except a reference-type array passed alone, which becomes the argument list.

solid answer

~50 s

SLF4J's `MessageFormatter` treats only the exact pair `{}` as an anchor; a lone `{`, a lone `}` or `{bla}` prints as written. To print `{}` literally you escape the `{` with a backslash, `"\\{}"` in Java source, and that escaped anchor consumes no argument; a doubled backslash (`"\\\\{}"`) prints one backslash and then substitutes normally. A `null` argument prints `null`, an object whose `toString()` throws prints `[FAILED toString()]`, and arrays, primitive or object, print element by element as `[1, 2, 3]`, nested arrays recursively and a self-referencing array as `[...]`. The trap is Java's overload choice: a `String[]` passed as the only argument matches `info(String, Object...)` and is used as the argument list, so `"Items {}"` prints only the first element. Cast it to `(Object)` to log the whole array; a primitive `int[]` is never spread.

code

java · 10 lines
java
String[] skus = {"A-1", "B-2"};
int[] bins = {4, 7};
String location = null;

log.info("Literal \\{} kept, sku {}", "A-1");   // Literal {} kept, sku A-1
log.info("Path C:\\\\{}", "stock.csv");        // Path C:\stock.csv
log.info("Location {}", location);             // Location null
log.info("Bins {}", bins);                     // Bins [4, 7]
log.info("Items {}", skus);                    // Items A-1  (array spread as the argument list)
log.info("Items {}", (Object) skus);           // Items [A-1, B-2]

go deeper

for a junior

Recall that only the exact {} pair is an anchor, that a backslash before the { escapes it, and that null prints as null while arrays print as bracketed lists.

for a middle

Explain why an escaped anchor consumes no argument and why a String array passed alone reaches the varargs overload through Java's most-specific-method rule, with a cast to Object as the fix.

for a senior

Point out the production consequences: a large array logged at INFO walks every element, a mismatched anchor count fails silently, and user text containing {} cannot shift arguments.

for a principal

Treat the spreading trap and silent anchor mismatches as review-checklist items, and weigh whether a team rule against logging whole collections at high-volume levels is worth enforcing.

## The formatting anchor SLF4J's classic logging methods, such as `info(String, Object)`, `info(String, Object, Object)` and `info(String, Object...)` and their equivalents at every level, take a **message pattern** plus arguments. The pattern is filled in by `org.slf4j.helpers.MessageFormatter`, which the providers shipped inside the SLF4J project (`slf4j-simple`, `slf4j-jdk14`, `slf4j-reload4j`) call to build the final text. Its javadoc calls the `{}` pair the **formatting anchor**: reading left to right, each anchor is replaced by the next argument. Only the exact two-character sequence `{}` is an anchor. Other braces are ordinary text: - `"Value is {bla} {}"` with `3` prints `Value is {bla} 3`. - `"Incorrect {subst"` prints unchanged, because no `}` follows the `{` directly. - `"File name is {{}}."` with `App folder.zip` prints `File name is {App folder.zip}.`: the inner pair is the anchor and the outer braces are text. - Fewer arguments than anchors leaves the unused anchors in the output as a literal `{}`; more arguments than anchors drops the extras from the message without any error. ## Escaping a literal {} To print `{}` itself, put a **backslash immediately before the `{`**. The `MessageFormatter` javadoc says only the `{` should be escaped and there is no need to escape the `}`. In a Java string literal the backslash is itself escaped, so the source text has two of them: ```java log.info("Set \\{} is not equal to {}.", "1,2"); // prints: Set {} is not equal to 1,2. ``` An escaped anchor **consumes no argument**: the formatter writes `{`, steps past it, and the next real anchor still receives the first argument. When you really want a backslash in front of a substituted value, as in a Windows path, escape the escape: the runtime text `C:\\{}` (written `"C:\\\\{}"` in Java source) prints one backslash followed by the argument, so `file.zip` gives `C:\file.zip`. ## How each kind of argument is rendered | Argument | Printed as | |---|---| | an ordinary object | its `toString()` | | `null` | `null` | | a primitive array (`int[]`, `byte[]`, `double[]` ...) | `[1, 2]` | | an object array (`Integer[]`, `Object[]` ...) | `[2, 3]`, nested arrays printed recursively | | an array that contains itself | `[...]` at the point of the cycle | | an object whose `toString()` throws | `[FAILED toString()]` | Three details matter in practice: - The formatter **walks every element** of an array rather than printing an identity string such as `[I@1b6d3586`, so logging a large array produces a long line. - An argument's own text is appended as it is and **never re-scanned**: logging the string `"[{}]"` into `"Value is {}."` prints `Value is [{}].`. - A failing `toString()` does not propagate to your code: the formatter reports the failure through SLF4J's internal reporter and prints `[FAILED toString()]` in that slot. ## The array-as-argument-list trap Java, not SLF4J, decides which overload a call reaches. Pass a **reference-type array as the only argument**, as in `log.info("Items {}", skus)` with `String[] skus = {"A-1", "B-2"}`, and both `info(String, Object)` and `info(String, Object...)` apply; the compiler picks the more specific one, `info(String, Object...)`, and hands your array over **as the argument list itself**. The formatter then sees `A-1` and `B-2` as two separate arguments, fills the single anchor with the first and drops the second, printing `Items A-1`. The fixes are simple: 1. Cast it, `log.info("Items {}", (Object) skus)`, so the single-argument overload receives the array as one value and prints `Items [A-1, B-2]`. 2. Or log it beside another argument, `log.info("{} items: {}", skus.length, skus)`, which reaches the two-argument overload and prints `2 items: [A-1, B-2]`. A primitive array such as `int[]` is not an `Object[]`, so it can only match `info(String, Object)` and is never spread. The same spreading happens for any reference-type array, such as `Integer[]` or `Object[]`, and it is easy to miss in review because the line still compiles and still logs something plausible. ## Where this formatting happens Formatting runs only after the provider has decided the event is enabled and needs its text. A backend that implements SLF4J's `Logger` interface itself may use its own formatting code, so if output differs from the rules above, check that backend's documentation. A trailing exception argument follows a separate rule: it is taken off the argument list and printed as a stack trace rather than through an anchor.

  • What does SLF4J print when a call has fewer arguments than `{}` anchors, or more arguments than anchors?
    Unused anchors stay in the output as a literal `{}`: `"Value {} is smaller than {}"` with one argument prints `Value 1 is smaller than {}`. Extra arguments are silently left out of the message. Neither case raises an error, so a mismatched count shows up only when someone reads the line.
  • If an argument's own text contains `{}`, does SLF4J substitute the next argument into it?
    No. `MessageFormatter` scans only the pattern for anchors and appends each argument's text as it is. Logging `"[{}]"` into `"Value is {}."` prints `Value is [{}].`, so user-supplied values cannot shift the remaining arguments.

  • Both braces must be escaped, so you write a backslash before the { and the }.
  • Doubling the braces as {{}} escapes a placeholder in SLF4J.
  • A null argument makes the logger throw a NullPointerException.
  • An array argument prints as its identity hash, like [I@1b6d3586.
  • Passing a String array as the only argument always prints the whole array.
  • An argument whose text contains {} gets the next argument substituted into it.