Logging Generation v2
Logging Generation v2
Section titled “Logging Generation v2”Generation v2 is the state-based logging mode. Its output closely resembles the built-in [LoggerMessage] generator, but with additional features: dynamically generated MessageTemplates and the ability to expand array/IEnumerable parameters.
It is used automatically in LoggerGenerationMode.Auto for methods that exceed the v1 limits (more than 6 non-exception parameters, or [ExpandEnumerable]/[LogProperties] parameters).
Selecting v2
Section titled “Selecting v2”// Force v2 for the whole interface[Logger(GenerationMode = LoggerGenerationMode.V2)]interface IOrderServiceTelemetry { }
// Or per method[Logger]interface IOrderServiceTelemetry{ [Info(GenerationMode = LoggerGenerationMode.V2)] void OrderPlaced(int orderId, string customerName);}Log generation
Section titled “Log generation”As with v1, decorate a method with [Log] (or a semantic level attribute) and return either void (non-scoped) or IDisposable/IDisposable? (scoped).
The shared [Log], [Logger], [LoggerGeneration], and LogPrefixType reference tables are on the Logging Generation v1 page.
Custom message templates
Section titled “Custom message templates”[Log].MessageTemplate lets you customise the log message. Template placeholders map to method parameters:
[Logger]interface IOrderServiceTelemetry{ [Info("Order {OrderId} placed for {CustomerName}")] void OrderPlaced(int orderId, string customerName);}If no template is specified, one is generated from the method name and parameters.
[ExpandEnumerable]
Section titled “[ExpandEnumerable]”Applied to an array or IEnumerable parameter, it logs the individual elements rather than the collection as a whole.
| Property | Type | Description |
|---|---|---|
MaximumValueCount | int | The maximum number of elements to output. Default 5. |
[Logger]interface IOrderServiceTelemetry{ [Info] void OrdersRetrieved(int orderId, [ExpandEnumerable(maximumValueCount: 100)] string[] orderNumbers);}[LogProperties]
Section titled “[LogProperties]”The external Microsoft.Extensions.Logging.LogPropertiesAttribute (from Microsoft.Extensions.Telemetry.Abstractions) expands an object’s public properties into individual log properties.
| Property | Type | Description |
|---|---|---|
OmitReferenceName | bool | Whether the reference name is omitted from property names. Default false. |
SkipNullProperties | bool | Whether null properties are skipped. Default false. |
Transitive | bool | Whether nested objects are expanded transitively. Default false. |
The companion LogPropertyIgnoreAttribute marks a property to be skipped during expansion.
Next steps
Section titled “Next steps”- Logging Generation v1 — the
LoggerMessage.Definemode and its limits - Logging — choosing between v1 and v2
- Diagnostics — the
TSG2xxxLogging rules