For operations that can succeed, fail, or produce specific results, use Operation.Begin(). This provides manual control over the operation's outcome.
Outcomes:
- Success: Call
op.Complete(). This logs an Information level event with Outcome = "completed". - Failure/Abandonment: If the block exits without calling
Complete(), a Warning level event is logged with Outcome = "abandoned". - Cancellation: Call
op.Cancel() to suppress all logging for that operation (no event is written for completion or abandonment).
Adding extra properties: You can attach additional data to the log event using op.Complete(propertyName, value). This does not change the log message text but adds the property for filtering.
using SerilogTimings;
using (var op = Operation.Begin("Retrieving orders for {CustomerId}", customer.Id))
{
// Timed block of code goes here
op.Complete("Rows", orders.Rows.Length);
}
// Log output: [INF] Retrieving orders for customer-67890 completed in 7.8 ms (with property Rows attached)