In Serilog, how does Log.Information("Shipment {TrackingNumber} picked up by {CourierId}", number, courierId) bind its arguments, and why is an interpolated string wrong?
answer
- holes bound by position, not by name
- extra arguments become __N properties
- missing value renders the raw {Hole}
- {0}-style holes are positional
- template text is the event type
basics
~20 sSerilog parses the template, then assigns the arguments to its named holes in order: number becomes TrackingNumber, courierId becomes CourierId. An interpolated string bakes the values into the template text: no properties, and a new template per value.
solid answer
~50 sThe first argument is a **message template**, not a format string. Serilog parses it (and caches the parse) into text and property tokens, then binds the remaining arguments to the named holes **by position**: the hole names become property names, and the values are captured with their types. A count mismatch is not an exception: extra arguments become properties named `__2`, `__3` and so on, missing ones leave the property absent so the hole renders as the literal `{CourierId}`, and `SelfLog` notes the mismatch. Holes that are all numeric (`{0}`, `{1}`) bind by index instead. With `$"Shipment {number} picked up"`, C# builds the string before Serilog sees it, so the template is the finished text: no `TrackingNumber` property to query, a different template per shipment (defeating grouping by template and churning the parse cache), and any brace in the data is parsed as a hole.
code
csharp · 7 lines// three holes, two arguments: {DepotCode} renders as raw text
Log.Information("Shipment {TrackingNumber} picked up by {CourierId} at {DepotCode}",
"CX-1042", 77);
// two holes, three arguments: the extra value is captured as __2
Log.Information("Shipment {TrackingNumber} picked up by {CourierId}",
"CX-1042", 77, "DEPOT-9");go deeper
Write templates with named holes and pass values as arguments in the same order; never build the message with $ interpolation.
Explain binding by position, the __N names for extra arguments, raw holes for missing ones, format and alignment specifiers, and that all-numeric holes are positional.
Tie template stability to querying and grouping by event type, explain the 1000-entry parse cache churn from unique strings, and use SelfLog to catch mismatches.
Treat message templates as an event schema: agree on property names across services so dashboards and alerts survive refactoring.
## Template, not format string Every Serilog logging method takes a `messageTemplate` string followed by property values. The methods carry the `[MessageTemplateFormatMethod("messageTemplate")]` attribute, which tells tooling which argument is the template. A template is ordinary text with **holes** in braces: ```csharp Log.Information("Shipment {TrackingNumber} picked up by {CourierId}", number, courierId); ``` Serilog parses the template into tokens - text, `{TrackingNumber}`, text, `{CourierId}` - and keeps the parsed result in a cache keyed by the template string. It then creates a `LogEvent` holding the template, the timestamp, the level and a **property** for each hole. A sink can render the familiar sentence, and a structured sink can store `TrackingNumber` and `CourierId` as separate, queryable fields. ## How arguments meet holes The binding rules, from Serilog's `PropertyBinder`: 1. If every hole is numeric (`{0}`, `{1}`), the template is **positional** and argument *n* fills hole `{n}`, like `string.Format`. 2. Otherwise holes are **named**, and they are filled **in the order they appear**, whatever their names. `"{CourierId} took {TrackingNumber}"` with `(number, courierId)` swaps the values silently. 3. **Too many arguments**: the extras are still captured, under generated names `__2`, `__3`, and so on, and `SelfLog` records "Named property count does not match parameter count". 4. **Too few arguments**: the unmatched holes get no property. When the message is rendered, the hole is written as its raw text, so the output reads `picked up by {CourierId}`. 5. **No holes but arguments supplied**: the arguments are ignored and `SelfLog` notes it. Nothing here throws, because Serilog never lets a logging mistake break the caller. The only signal is in `SelfLog` and in the output. ## What a hole may contain | Form | Meaning | |---|---| | `{TrackingNumber}` | property name: letters, digits and underscores, not starting with a digit | | `{WeightKg:0.0}` | format string applied when rendering; the stored value stays a number | | `{Status,-10}` | alignment (padding) when rendering | | `{@Shipment}` / `{$Shipment}` | capture operators - destructure or stringify the value | | `{{` and `}}` | literal braces | The capture operators decide *how* an object becomes a property value; they are a separate topic from binding. ## How the message is rendered The template and the properties are stored separately; the sentence is only produced when a text sink or formatter needs it. Rendering follows a few rules worth knowing: - String values are written **in quotes** by default, so the rendered message reads `Shipment "CX-1042" picked up by 77`. The `:l` (literal) format removes the quotes, which is why the console and file sinks' default output templates use `{Message:lj}`. - A format such as `{WeightKg:0.0}` affects only the rendered text; the stored property keeps its numeric value for queries. - Destructured objects render in a compact object notation, or as JSON with the `:j` option in an output template. This separation is what lets the same event be a readable line on the console and a set of typed fields in a log store. ## Why interpolation breaks it ```csharp // wrong Log.Information($"Shipment {number} picked up by {courierId}"); ``` The C# compiler turns the interpolated string into an ordinary string before the call. Serilog receives `"Shipment CX-1042 picked up by 77"` as the template: - **No properties.** There is no `TrackingNumber` field to search or aggregate on; the value exists only inside text. - **No stable event type.** Every shipment produces a different template, so grouping events by template - which `RenderedCompactJsonFormatter` turns into an `@i` event id - no longer groups anything. - **Cache churn.** Serilog's template cache holds up to 1000 parsed templates and is cleared when full; unique strings keep filling it. - **Accidental holes.** If a value contains braces, for example a JSON fragment, Serilog parses it as a hole. - **Wasted work.** The string is built even when the level is disabled, whereas a template's arguments are only bound if the event will be written. The same rule holds when Serilog sits behind `ILogger<T>`: pass a template and arguments, never a pre-built string. ## A courier API example ```csharp Log.Information("Shipment {TrackingNumber} picked up by {CourierId} at {DepotCode}", shipment.TrackingNumber, courier.Id, depot.Code); ``` Rendered on the console it reads as a sentence; in a JSON sink it is one event with three typed properties plus the template itself, so a query for all pickups at one depot needs no text parsing.
- The template is "{CourierId} collected {TrackingNumber}" but the call passes (number, courierId). What is stored?Named holes bind in order of appearance, not by matching names to variables, so `CourierId` receives the tracking number and `TrackingNumber` receives the courier id. Nothing warns you because the counts match. Keeping argument order identical to hole order is the only defence.
- Why is Log.Debug($"Payload {json}") wasteful even when Debug is disabled?The interpolated string is built by the caller before Serilog can check the level, so the formatting cost is paid on every call. With a template and arguments, Serilog checks `IsEnabled` first and skips binding entirely when the level is off; only argument evaluation itself still happens.
- Serilog matches arguments to holes by variable name
- A missing argument makes Serilog throw a FormatException
- An interpolated string still produces properties for each hole
- Extra arguments beyond the holes are silently thrown away
- {WeightKg:0.0} stores the weight as a formatted string