Overview
TheMessageTemplate class represents a parsed message template string. It contains text and property tokens that can be rendered into a final message string given the associated property values.
Constructors
MessageTemplate(IEnumerable<MessageTemplateToken>)
Construct a message template using manually-defined text and property tokens.The text and property tokens defining the template.
MessageTemplate(string, IEnumerable<MessageTemplateToken>)
Construct a message template using manually-defined text and property tokens with the full template text.The full text of the template; used by Serilog internally to avoid unneeded string concatenation.
The text and property tokens defining the template.
ArgumentNullException- Whentextortokensis null
Properties
A static property representing the empty message template.
The raw text describing the template. This is the original template string before parsing.
The tokens parsed from the template. This includes both text tokens and property tokens.
Methods
Render(IReadOnlyDictionary<string, LogEventPropertyValue>, IFormatProvider)
Convert the message template into a textual message, given the properties matching the tokens in the message template.Properties matching template tokens.
Supplies culture-specific formatting information, or null.
string - The message created from the template and properties. If the properties are mismatched with the template, the template will be returned with incomplete substitution.
Exceptions:
ArgumentNullException- Whenpropertiesis null
Render(IReadOnlyDictionary<string, LogEventPropertyValue>, TextWriter, IFormatProvider)
Convert the message template into a textual message and write it to the specified output.Properties matching template tokens.
The text writer to output the rendered message to.
Supplies culture-specific formatting information, or null.
ArgumentNullException- Whenpropertiesoroutputis null
ToString()
Render the template as a string. Returns the raw template text. Returns:string - The string representation of the template (the Text property).
Usage Examples
Basic Template
Template with Formatting
Template with Multiple Properties
Empty Template
Template Syntax
Message templates support:- Named properties:
{PropertyName} - Positional properties:
{0},{1}, etc. - Format strings:
{Amount:C},{Date:yyyy-MM-dd} - Destructuring:
{@Object}for structured logging - Stringification:
{$Object}to force ToString()
Performance Notes
- The
MessageTemplateclass caches parsed tokens for efficient reuse - Using the constructor with both text and tokens avoids string concatenation overhead
- Templates are immutable and thread-safe