Logging standard¶
This page sets the rules for log statements in ConnectSoft services and libraries. It is written for engineers who add or review logging code. How logging is wired (Serilog configuration, sinks, enrichers and OpenTelemetry) is explained in Logging; this page covers only what a log statement must look like.
ConnectSoft code logs through Microsoft.Extensions.Logging.ILogger<T> together with two extension methods from ConnectSoft.Extensions.Logging:
ILogger.Here(log => ...)adds the calling member name, file and line number to the entry;ILogger.BeginScopeWithFlow(flowName)opens a scope that adds the flow name and the current trace and span IDs to every entry inside it.
Log levels¶
The levels follow the Microsoft.Extensions.Logging meanings. This table is guidance; the rules below say which level a domain operation uses.
| Level | Use for |
|---|---|
Trace |
Step-by-step detail used only while debugging a component. |
Debug |
Diagnostic detail that helps during development and is off in production. |
Information |
The normal flow of an operation: started, completed, important state changes. |
Warning |
An unexpected situation the code recovered from, such as a retry or a fallback. |
Error |
An operation that failed. The exception is attached. |
Critical |
A failure that stops the host or loses data. |
Rules¶
CS-LOG-001: Log with message templates¶
Severity: major · Applies to: service, library, api-client, blazor · Enforced by: analyzer CA2254 (target: ENF-004) · Status: active
Why¶
A message template keeps each value as a separate structured property, so logs can be searched and grouped by OrderId or CustomerId. String interpolation or concatenation turns the values into plain text, breaks grouping by message, and allocates even when the level is disabled.
Do¶
- Pass a constant template with named placeholders and the values as arguments.
- Name placeholders in PascalCase after the value they hold, for example
{OrderId}. - Use the same placeholder name for the same value everywhere, so one query finds every entry about an order.
Don't¶
- Use
$"..."interpolation or+concatenation in the message. - Use positional placeholders such as
{0}. - Give the same value different names in different messages, such as
{Id}in one place and{OrderId}in another.
Example¶
// Do
this.logger.Here(log => log.LogInformation(
message: "Create Order for {OrderId} started...",
orderId));
// Don't
this.logger.Here(log => log.LogInformation($"Create Order for {orderId} started..."));
How to check¶
- Search the change for
Log\w+\(\s*\$",message: \$"and" +inside log calls. - Check that placeholders are PascalCase and named consistently with existing messages about the same value.
- Analyzer CA2254 reports non-constant templates. It is not yet enforced by the build; see ENF-004.
CS-LOG-002: Use Here() in application code and source-generated logging in hot paths and libraries¶
Severity: minor · Applies to: service, library · Enforced by: manual · Status: active
Why¶
Here() adds the caller member and line to every entry, which makes application logs easy to trace back to code. It is the established style across ConnectSoft services. Source-generated logging ([LoggerMessage]) avoids boxing and allocation and checks the level before formatting. That matters in code that runs very often, and in shared libraries whose callers cannot control how often they are called.
Do¶
- In application code (domain services, controllers, handlers, jobs), log through
this.logger.Here(log => log.LogXxx(...)). - In a hot path, use
[LoggerMessage]partial methods. A hot path is code that runs per item in a loop, per message in a high-volume consumer, or in request middleware. - In
ConnectSoft.Extensions.*libraries, use[LoggerMessage]partial methods with anEventIdthat is unique within the library.
Don't¶
- Call
logger.LogXxx(...)directly in application code withoutHere(). - Use
Here()inside a per-item loop or per-request middleware. - Reuse an
EventIdfor a different message in the same library.
Example¶
// Application code
this.logger.Here(log => log.LogInformation(
message: "Order {OrderId} shipped to {WarehouseId}",
orderId,
warehouseId));
// Hot path or library code
internal static partial class OrderBatchLog
{
[LoggerMessage(EventId = 1201, Level = LogLevel.Debug, Message = "Processing order line {LineNumber} of {OrderId}")]
public static partial void ProcessingLine(ILogger logger, int lineNumber, Guid orderId);
}
How to check¶
- In application code, log calls go through
Here(). - In loops, consumers and middleware, look for
Here()or directLogXxxcalls and ask for[LoggerMessage]. - In
ConnectSoft.Extensions.*libraries, every log call is a[LoggerMessage]method, andEventIdvalues are unique within the library.
CS-LOG-003: Scope every public domain operation with a flow name¶
Severity: minor · Applies to: service · Enforced by: manual · Status: active
Why¶
The flow scope tags every entry written during the operation, including entries from repositories and libraries it calls, with the operation name and the trace context. Without it, entries from concurrent operations cannot be told apart.
Do¶
- Open
BeginScopeWithFlowas the first statement of every public method of a domain service implementation, such as a processor or retriever inDomainModel.Impl. - Name the flow
<ClassName>/<MethodName>withnameof, so a rename keeps it correct.
Don't¶
- Build the flow name from a string literal.
- Open the scope after work has already been logged.
Example¶
public async Task<IOrder> CreateOrder(CreateOrderInput input, CancellationToken token = default)
{
using (this.logger.BeginScopeWithFlow(nameof(DefaultOrdersProcessor) + "/" + nameof(this.CreateOrder)))
{
// operation body
}
}
How to check¶
Every public method in DomainModel.Impl service classes starts with using (this.logger.BeginScopeWithFlow(nameof(<Class>) + "/" + nameof(this.<Method>))).
CS-LOG-004: Log the start, completion and failure of a domain operation¶
Severity: major · Applies to: service · Enforced by: manual · Status: active
Why¶
Operators diagnose production issues from these three entries. An operation that logs a start without a completion or a failure is either still running or lost an exception.
Do¶
- Log
"<Operation> <Aggregate> for {Id} started..."atInformationbefore validation. - Log
"<Operation> <Aggregate> for {Id} successfully completed..."atInformationas the last statement in thetryblock. - In the
catchblock, log atErrorwith the exception object attached, then rethrow withthrow;. - Filter cancellation out of that
catchblock withwhen (ex is not OperationCanceledException). A cancelled operation is not a failure: it is not logged atErrorand not counted in the failure metric (CS-ERR-008).
Don't¶
- Swallow the exception after logging it.
- Rethrow with
throw ex;, which loses the original stack trace. - Log the failure without passing the exception, for example by logging only
ex.Message.
Example¶
try
{
this.logger.Here(log => log.LogInformation(message: "Create Order for {OrderId} started...", orderId));
await this.createOrderInputValidator.ValidateAndThrowAsync(input, token).ConfigureAwait(false);
// work
this.logger.Here(log => log.LogInformation(message: "Create Order for {OrderId} successfully completed...", orderId));
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
this.meters.AddOrderFailed(tenantId: tenantId, aggregate: aggregateName);
this.logger.Here(log => log.LogError(exception: ex, message: "Failed to create the Order with id : {OrderId}", orderId));
throw;
}
The metrics calls in this example are covered by the domain service shape standard.
How to check¶
- Each public domain operation has the three entries at the stated levels.
- The
LogErrorcall passesexception: ex. - The
catchblock ends withthrow;. - The
catchblock filters outOperationCanceledException.
CS-LOG-005: Never log secrets or personal data¶
Severity: blocker · Applies to: service, library, api-client, blazor · Enforced by: manual · Status: active
Why¶
Log sinks are kept for a long time, copied to several systems and read by more people than the data they describe. A password or personal record in a log is a data breach that cannot be recalled.
Do¶
- Log identifiers (
OrderId,CustomerId,TenantId) instead of the data they identify. - Log the name of a configuration key, not its value.
- When a request or response must be logged for diagnosis, log only fields that are known to be safe.
Don't¶
Log any of these: - passwords, tokens, API keys, client secrets, connection strings or certificates; - personal data such as names, national ID numbers, e-mail addresses, phone numbers, addresses or health information; - whole request or response bodies, options objects or entities, because they may contain any of the above.
Example¶
// Do
this.logger.Here(log => log.LogInformation(message: "Customer {CustomerId} updated their contact details", customerId));
// Don't
this.logger.Here(log => log.LogInformation(message: "Customer {CustomerEmail} updated phone to {Phone}", email, phone));
How to check¶
- Read every placeholder in the change and ask what value it carries.
- Search log templates for
Password,Token,Secret,Key,ConnectionString,Email,PhoneandName. - Check that no log call passes a whole request, response, entity or options object.
CS-LOG-006: Treat existing log text as behaviour¶
Severity: minor · Applies to: service, library · Enforced by: manual · Status: active
Why¶
Dashboards, alerts and saved queries match on message templates and placeholder names. Changing them silently breaks monitoring that nobody checks until an incident. ADR-0103 therefore lists log text among the behaviour that an upgrade does not change.
Do¶
- Keep existing message templates and placeholder names when refactoring or upgrading.
- When a change to a template is needed, state it in the pull request description so monitoring can be updated.
Don't¶
- Rewrite existing log messages for style in a refactoring, an upgrade or an analyzer fix.
How to check¶
Compare the log templates in the diff. Any changed template or placeholder name is named in the pull request description.
CS-LOG-007: Test logs that are behaviour with FakeLogger, never with a mocked ILogger¶
Severity: major · Applies to: service, library, api-client, blazor, template · Enforced by: manual · Status: active
Why¶
Operators, alerts and dashboards depend on some log entries (CS-LOG-004, CS-LOG-006). A change that drops the failure log, or logs it without the exception, raises no error and is noticed only during an incident. Verifying ILogger.Log on a mock depends on the internal state type that the logging extensions pass, so the setup is brittle and usually proves only that some call happened. FakeLogger from the built-in Microsoft.Extensions.Diagnostics.Testing package records every entry with its level, event id, message, exception and structured values.
Do¶
- Where a test asserts a log entry, use
FakeLogger<T>fromMicrosoft.Extensions.Diagnostics.Testing(namespaceMicrosoft.Extensions.Logging.Testing). In a test host, register it withservices.AddFakeLogging()and read the entries fromGetFakeLogCollector(). - Assert the logs that are behaviour:
- the failure log of every public domain operation: level
Error, the thrown exception attached, and the identifier as a structured value; - every log entry that an alert, a dashboard or a saved query depends on.
- the failure log of every public domain operation: level
- Assert the level, the structured values and the exception. Assert the whole formatted message only when a consumer depends on the exact text.
- Where a test does not assert logs, pass
NullLogger<T>.InstanceorNullLoggerFactory.Instance.
Don't¶
- Mock
ILogger,ILogger<T>orILoggerFactorywith a mocking library, or verify calls toLog. - Pass
Mock.Of<ILogger<T>>()as a dummy logger. - Write a custom test logger or log collector.
Example¶
[TestMethod]
public async Task CreateOrderShouldLogTheFailureWithTheExceptionWhenTheInputIsInvalid()
{
// Arrange
var logger = new FakeLogger<DefaultOrdersProcessor>();
DefaultOrdersProcessor processor = this.CreateProcessor(logger);
Guid orderId = Guid.NewGuid();
CreateOrderInput input = new() { OrderId = orderId, CustomerId = Guid.Empty };
// Act
ValidationException exception = await Assert.ThrowsExactlyAsync<ValidationException>(() => processor.CreateOrder(input));
// Assert
FakeLogRecord failure = logger.Collector.GetSnapshot().Single(record => record.Level == LogLevel.Error);
Assert.AreSame(exception, failure.Exception);
Assert.AreEqual(orderId.ToString(), failure.GetStructuredStateValue("OrderId"));
}
How to check¶
- No new or changed test creates a mock of
ILogger,ILogger<T>orILoggerFactory. - Every new or changed public domain operation has a failure-path test that asserts its
Errorentry withFakeLogger. - Tests that do not assert logs pass
NullLogger<T>.Instance.
CS-LOG-008: Count and log references that enrichment cannot resolve¶
Severity: major · Applies to: service, library, template · Enforced by: manual · Status: active
Why¶
Enrichment code that turns ids into names, labels or other details often shows a blank for an id it cannot resolve, so that one bad reference does not break a whole page or report. When the blank is silent, drift from the system of record looks like a rendering bug, and nobody learns how many records are affected.
Do¶
- When a lookup misses, keep the documented fallback, and log one Warning per enrichment run that gives the number of misses and the kind of reference.
- Record the misses on a counter when the service has a metrics class.
Don't¶
- Map an unresolved reference to an empty value without any log entry or metric.
- Log every miss individually in a loop over a large set.
How to check¶
An enrichment test with one unknown id asserts the fallback value and a Warning, or a counter value, that reports one miss.
CS-LOG-009: Log the status the client receives, outside the exception mapping¶
Severity: major · Applies to: service, template · Enforced by: manual · Status: active
Why¶
Request-logging middleware records the status of the response as it sees it. Registered inside the problem details middleware, it sees the exception before it is mapped, and logs a 500 for a refusal that the client receives as 403 or 404. Triage that counts those lines as server errors chases failures that never happened.
Do¶
- Register request logging before the exception mapping middleware in the pipeline, so that it wraps the mapping and logs the final status.
- Count server errors from the status the client received.
Don't¶
- Register
UseSerilogRequestLogging, or other request logging, afterUseProblemDetailsorUseExceptionHandler.
How to check¶
A test host test sends a request that is refused with a 4xx status and asserts that the request log records the same status.
CS-LOG-010: Write response headers only before the response starts, never from a log enricher¶
Severity: major · Applies to: service, library, template · Enforced by: manual · Status: active
Why¶
Log events are written throughout a request, including after the response has started. An enricher that sets a response header on each log event throws "Headers are read-only" once the response has started, and an enricher that creates an id when the header is missing gives the events of one request different correlation ids.
Do¶
- Set correlation and other response headers once, in middleware, before the response starts, for example with
Response.OnStarting. - Let log enrichers read the correlation id from the request context only.
- List each enricher assembly once in
Serilog:Using, and remove the old assembly when you replace an enricher.
Don't¶
- Write response headers from a log enricher, a logging scope or any code that runs per log event.
- Create a new correlation id inside an enricher.
How to check¶
- An enricher test with a response that has started asserts that no exception is thrown and that all events of the request carry one correlation id.
- In each changed settings file,
Serilog:Usinglists each enricher assembly once and no longer lists the assembly of a replaced enricher.
Related¶
- Logging explains how logging is configured.
- Testing standard
- Engineering standards describes how rules are written and applied.
- ADR-0103: Package upgrade and warning policy