Introduction
In the previous lesson, we integrated Serilog into an ASP.NET Core application and created the basic configuration. This lesson focuses on the idea that logs are not merely text written to a console. They are structured representations of application events that should support investigation, filtering, correlation, and alerting.
Using an order and payment workflow, we will apply message templates, named properties, destructuring, and event properties. We will also compare string interpolation with structured logging, design a consistent event naming convention, mask sensitive data, and test the resulting events.
A well-designed log event quickly explains what happened, which user or order was involved, whether the operation succeeded, and what technical context is available when something fails. A poorly designed event may contain a long sentence but provide almost no value for queries or dashboards.
1. What is structured logging?
Structured logging records an event as a message template plus named fields rather than as a fully rendered string. The following examples may look similar when printed:
logger.LogInformation($"Order {order.Id} paid by {user.Id}");
logger.LogInformation("Order {OrderId} paid by {UserId}", order.Id, user.Id);In the first example, string interpolation combines the values before the logging provider receives them. In the second example, OrderId and UserId remain named properties. Serilog can preserve these properties in JSON, Seq, or another centralized log store, where they can be queried directly.
With structured logging, you can search for OrderId = 1042, PaymentStatus = Failed, or Amount > 1000 instead of searching only for a phrase such as “payment failed.”
2. Message templates and named properties
Names inside braces in a Serilog message template become named properties. Arguments are matched by position, so the property names and argument order must be reviewed carefully.
Log.Information(
"Payment completed for order {OrderId} by user {UserId} in {ElapsedMs} ms",
orderId,
userId,
elapsedMs);This event contains separate OrderId, UserId, and ElapsedMs properties. Use meaningful, stable names across the application. PascalCase is a practical convention that aligns with common .NET and Serilog usage.
| Concept | Recommended name | Should be avoided |
|---|---|---|
| Order | OrderId | id or Order |
| User | UserId | Writing the complete user object |
| Payment operation | TransactionId | Writing the raw provider response |
| Duration | ElapsedMs | Writing “it took a long time” |
Keep templates constant
Pass changing values as arguments instead of concatenating them into the template. This preserves structured properties and allows the logging system to process the template consistently.
// Avoid
Log.Information("Order " + orderId + " failed for " + userId);
// Prefer
Log.Information(
"Order payment failed for {OrderId} and {UserId}",
orderId,
userId);Keep the rendered message concise. The property names should carry the searchable meaning; the message should describe the event rather than repeat every value in prose.
3. Event properties and event naming
A log event contains a level, a message template, and a collection of properties. These properties provide the business and technical context needed for analysis. Useful fields in a payment workflow include:
EventName: The stable name of the business event.OrderId: The order identifier.UserId: The user who initiated the operation.TransactionId: The payment provider transaction identifier.AmountandCurrency: The transaction value.PaymentMethod: A classified method such as card, bank transfer, or wallet.ElapsedMs: The duration of the operation.Outcome: A bounded value such as Success, Failed, or Rejected.
Use a consistent event naming convention that includes the business area and action, such as Order.PaymentStarted, Order.PaymentCompleted, and Order.PaymentFailed. If different services use different names for the same event, dashboards and alert rules become fragile.
4. Implementation: safe payment logging
The following example represents a small payment service. Instead of logging the complete request, it selects only the fields required for investigation.
public sealed record PaymentRequest(
string CardNumber,
decimal Amount,
string Currency);
public sealed record PaymentResult(
bool IsSuccessful,
string TransactionId);
public sealed class PaymentService
{
private readonly ILogger<PaymentService> _logger;
public PaymentService(ILogger<PaymentService> logger)
{
_logger = logger;
}
public async Task<PaymentResult> PayAsync(
Guid orderId,
Guid userId,
PaymentRequest request,
CancellationToken cancellationToken)
{
var startedAt = Stopwatch.GetTimestamp();
var maskedCard = MaskCard(request.CardNumber);
using var scope = _logger.BeginScope(new Dictionary<string, object>
{
["EventName"] = "Order.PaymentStarted",
["OrderId"] = orderId,
["UserId"] = userId
});
_logger.LogInformation(
"Payment started for order {OrderId} with {PaymentMethod} and {MaskedCard}",
orderId,
"Card",
maskedCard);
try
{
var result = await SendToProviderAsync(request, cancellationToken);
var elapsedMs = Stopwatch.GetElapsedTime(startedAt).TotalMilliseconds;
if (!result.IsSuccessful)
{
_logger.LogWarning(
"Payment rejected for order {OrderId} with outcome {Outcome} in {ElapsedMs} ms",
orderId,
"Rejected",
elapsedMs);
return result;
}
_logger.LogInformation(
"Payment completed for order {OrderId} with transaction {TransactionId} in {ElapsedMs} ms",
orderId,
result.TransactionId,
elapsedMs);
return result;
}
catch (Exception exception)
{
var elapsedMs = Stopwatch.GetElapsedTime(startedAt).TotalMilliseconds;
_logger.LogError(
exception,
"Payment failed for order {OrderId} after {ElapsedMs} ms",
orderId,
elapsedMs);
throw;
}
}
private static string MaskCard(string cardNumber)
{
var digits = new string(cardNumber.Where(char.IsDigit).ToArray());
return digits.Length < 4 ? "****" : $"****{digits[^4..]}";
}
}The raw card number is never written to the log. MaskedCard contains only the last four digits. In production systems, do not log card numbers, CVV values, passwords, access tokens, connection strings, or raw payment provider responses.
Destructuring with the @ operator
Serilog can convert complex objects to strings. The @ operator requests that the object structure be preserved as nested properties.
var order = new
{
Id = orderId,
UserId = userId,
Total = 149.90m,
Currency = "USD"
};
Log.Information("Order received {@Order}", order);This can be useful for small, safe DTOs. It is dangerous to destructure a large or sensitive request object. An explicit property list is often safer:
Log.Information(
"Order received with {OrderId}, {Amount} {Currency}",
order.Id,
order.Total,
order.Currency);When a specific type must be destructured, configure a transformation that exposes only approved fields:
Log.Logger = new LoggerConfiguration()
.Destructure.ByTransforming<PaymentRequest>(request => new
{
request.Amount,
request.Currency,
MaskedCard = MaskCard(request.CardNumber)
})
.CreateLogger();Now destructuring a PaymentRequest produces a controlled representation instead of exposing the original card number.
5. Testing interpolation versus structured logging
Use a JSON-capable sink to inspect the difference. In the structured example, OrderId is a separate property. In the interpolation example, the value may exist only inside the rendered message.
Log.Information($"Order {orderId} paid");
Log.Information("Order {OrderId} paid", orderId);The first line may be readable in a console but difficult to query by order ID in a centralized system. The second line preserves both the template and the property. Therefore, do not embed changing values through interpolation or string concatenation.
6. Testing properties, masking, and event names
Validate logging conventions with automated tests rather than relying only on visual inspection. A small collecting sink can capture Serilog events for assertions.
public sealed class CollectingSink : ILogEventSink
{
public List<LogEvent> Events { get; } = new();
public void Emit(LogEvent logEvent)
{
Events.Add(logEvent);
}
}
[Fact]
public async Task Payment_log_contains_searchable_fields_without_card_number()
{
var sink = new CollectingSink();
using var logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.Sink(sink)
.CreateLogger();
var service = new PaymentService(
new Serilog.Extensions.Logging.SerilogLoggerFactory(logger)
.CreateLogger<PaymentService>());
await service.PayAsync(
Guid.NewGuid(),
Guid.NewGuid(),
new PaymentRequest("4111111111111111", 50, "USD"),
CancellationToken.None);
var text = string.Join(" ", sink.Events.Select(x => x.RenderMessage()));
Assert.DoesNotContain("4111111111111111", text);
Assert.Contains(sink.Events, x => x.Properties.ContainsKey("OrderId"));
Assert.Contains(sink.Events, x => x.Properties.ContainsKey("TransactionId"));
}Adapt logger factory construction to the test infrastructure used by your application. The important assertions are that expected properties exist, sensitive data is absent, and exception context is retained on failed operations.
7. Common mistakes
- Using string interpolation: Values may not be available as separate searchable properties. Use a constant template and arguments.
- Inconsistent property names: Writing
OrderId,OrderID, andIdfor the same concept fragments queries and dashboards. - Destructuring every object: Sensitive fields, unnecessary payloads, and large nested objects can leak into logs.
- Omitting event names: Dashboards and alerts that depend on rendered text are fragile. Establish a stable
EventNameconvention. - Logging raw user input: CR/LF characters can create log injection risks, while very large values create noise and cost. Apply validation, size limits, and safe sanitization.
- Writing exceptions into strings: Use
Log.Error(exception, "...")so the exception remains a first-class event field. - Failing to distinguish outcomes: Use an
Outcomeproperty or consistent event names to make success and failure easy to analyze.
Short practice exercise
- Design
Order.PaymentCompletedandOrder.PaymentFailedevents. - Define
OrderId,UserId,TransactionId,Amount, andOutcomefor both events. - Mask the card number so that only its last four digits are visible.
- Generate a failed-payment event with an exception and test that the exception message does not contain the card number.
- Verify that a dashboard query can select only records where
EventName = Order.PaymentFailed.
Conclusion
Structured logging turns log output from readable text into searchable events. Named properties in message templates make order, user, transaction, and duration values available for filtering in centralized log systems. Destructuring can make complex objects useful for analysis, but it should be limited to safe and deliberately shaped DTOs.
A reliable log design standard combines stable event names, consistent property names, sensitive-data masking, appropriate log levels, and automated tests. In the next lessons, we will connect these events with request logging, correlation IDs, and service-to-service calls to follow a request across the entire system.
Sources
- https://github.com/serilog/serilog/wiki/Writing-Log-Events
- https://github.com/serilog/serilog/wiki/Structured-Data
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-7.0
- https://learn.microsoft.com/en-us/dotnet/core/extensions/high-performance-logging
- https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html