How do you stop Serilog from logging a shipment's recipient details or its whole object graph, using Destructure.ByTransforming, the size limits and a custom IDestructuringPolicy?
answer
- ByTransforming matches the exact type only
- ByTransformingWhere for derived types
- ToMaximumDepth / StringLength / CollectionCount
- IDestructuringPolicy.TryDestructure
- policies ignored without @
basics
~20 sRegister Destructure.ByTransforming<Shipment>(s => new { s.TrackingNumber, s.Status }) so {@Shipment} logs only safe fields, cap graphs with ToMaximumDepth, ToMaximumStringLength and ToMaximumCollectionCount, and write an IDestructuringPolicy for rules across many types. None of these affect {Shipment} without @.
solid answer
~40 sDestructuring is configured on `LoggerConfiguration.Destructure`. `ByTransforming<Shipment>(s => new { s.TrackingNumber, s.Status, s.WeightKg })` replaces the object with a projection whenever a `Shipment` is destructured; note it matches the **exact** type, so a derived `ExpressShipment` needs `ByTransformingWhere<Shipment>(t => typeof(Shipment).IsAssignableFrom(t), ...)`. `ToMaximumDepth` (default 10), `ToMaximumStringLength` (default unlimited, minimum 2) and `ToMaximumCollectionCount` (default unlimited, minimum 1) bound what any object can produce. For a rule that spans many types - for example masking every property marked with your own attribute - implement `IDestructuringPolicy.TryDestructure` and register it with `Destructure.With(...)`. All of these run only when destructuring is requested; `{Shipment}` without `@` still calls `ToString()`, so that method must not print personal data either.
go deeper
Know that Destructure.ByTransforming lets you choose which fields of an object are logged with @.
Explain the exact-type match of ByTransforming, ByTransformingWhere for derived types, and the three limits with their defaults.
Design a privacy-safe logging setup: transformations or a custom IDestructuringPolicy, safe ToString overrides, identifiers instead of entities, and limits as a safety net.
Own a data-classification rule for logs, decide where masking is enforced, and how compliance is verified across services.
## Where the controls live `LoggerConfiguration.Destructure` exposes the destructuring rules for a logger: | Method | Effect | |---|---| | `ByTransforming<T>(Func<T, object>)` | replace values of exactly type `T` with the returned object | | `ByTransformingWhere<T>(Func<Type, bool>, Func<T, object>)` | same, for every type the predicate accepts | | `With(params IDestructuringPolicy[])` / `With<TPolicy>()` | add custom policies | | `AsScalar<T>()` | never destructure `T`; keep it as a scalar | | `AsDictionary<T>()` | capture `T` as a dictionary | | `ToMaximumDepth(int)` | depth limit, default 10 | | `ToMaximumStringLength(int)` | truncate captured strings, at least 2 | | `ToMaximumCollectionCount(int)` | cap elements per collection, at least 1 | The same rules can be set from the `Destructure` section of the Serilog configuration. ## Transforming one type In a courier API the `Shipment` entity carries a `Recipient` with a name, phone and address. Logging it with `@` would copy all of that into every event. A transformation fixes the shape once: ```csharp Log.Logger = new LoggerConfiguration() .Destructure.ByTransforming<Shipment>(s => new { s.TrackingNumber, s.Status, s.WeightKg, ParcelCount = s.Parcels.Count }) .Destructure.ToMaximumCollectionCount(20) .Destructure.ToMaximumStringLength(200) .WriteTo.Console() .CreateLogger(); Log.Information("Shipment updated {@Shipment}", shipment); ``` The projection (an anonymous object here) is itself destructured, so it becomes a structure with four properties and no type tag. Three details matter: 1. **Exact type match.** `ByTransforming<T>` registers a policy whose predicate is `t == typeof(T)`. A subclass or an EF Core proxy type derived from `Shipment` is not matched. Use `ByTransformingWhere<Shipment>(t => typeof(Shipment).IsAssignableFrom(t), s => ...)` when inheritance or proxies are involved. 2. **Order.** Custom policies are tried in registration order before Serilog's built-in ones, and the first that accepts a value wins. 3. **Scope.** Policies run only for destructuring - `{@Shipment}`, `ForContext(name, value, destructureObjects: true)`, `LogContext.PushProperty(name, value, destructureObjects: true)` or `Enrich.WithProperty(..., destructureObjects: true)`. A plain `{Shipment}` or `{$Shipment}` uses `ToString()`. ## The size limits The three limits protect against graphs nobody planned to log: - `ToMaximumDepth` stops recursion; beyond it the value becomes null and `SelfLog` says "Maximum destructuring depth reached." - `ToMaximumStringLength` truncates each captured string to the limit, ending with an ellipsis character; it applies to strings captured by `@` or `$`, not to a plain `{Name}` string argument. - `ToMaximumCollectionCount` keeps the first N elements of every collection, dictionaries included. They are a safety net, not a privacy control: a truncated phone number is still a phone number. ## A custom policy for cross-cutting rules When many types share a rule, one policy beats dozens of transformations. `IDestructuringPolicy` has a single method: ```csharp sealed class MaskPersonalDataPolicy : IDestructuringPolicy { public bool TryDestructure(object value, ILogEventPropertyValueFactory factory, [NotNullWhen(true)] out LogEventPropertyValue? result) { if (value is not Recipient r) { result = null; return false; } result = new StructureValue([ new LogEventProperty("City", new ScalarValue(r.City)), new LogEventProperty("Name", new ScalarValue("***"))]); return true; } } ``` Register it with `.Destructure.With(new MaskPersonalDataPolicy())`. Returning `false` hands the value to the next policy; returning `true` with a result ends the search. A policy runs on the logging thread for every destructured value, so keep the type test cheap. ## Configuring it from appsettings.json With `Serilog.Settings.Configuration`, the `Destructure` section maps onto the same methods by name, so limits can differ per environment without a rebuild: ```json { "Serilog": { "Destructure": [ { "Name": "ToMaximumDepth", "Args": { "maximumDestructuringDepth": 4 } }, { "Name": "ToMaximumStringLength", "Args": { "maximumStringLength": 200 } }, { "Name": "ToMaximumCollectionCount", "Args": { "maximumCollectionCount": 20 } }, { "Name": "With", "Args": { "policy": "Courier.Logging.MaskPersonalDataPolicy, Courier.Api" } } ] } } ``` A lambda such as the `ByTransforming` projection cannot be written in JSON, so transformations stay in code while the limits and named policy types can live in configuration. ## Belt and braces - Prefer logging identifiers (`{TrackingNumber}`) over whole entities. - Make `ToString()` safe too, because the default capture uses it. - Keep `AsScalar<T>()` for value types such as a `Money` type whose string form is what you want.
- Your ByTransforming<Shipment> policy works in tests but production logs still show recipient data. What is a likely cause?The production object is not exactly `Shipment` - for example a derived type or a lazy-loading proxy generated from it. `ByTransforming<T>` matches only `typeof(T)` exactly, so the derived type falls through to reflection-based destructuring. Switch to `ByTransformingWhere<Shipment>` with an `IsAssignableFrom` predicate.
- Does ToMaximumStringLength(200) truncate a long string passed to a plain {Note} hole?No. The limit is applied when values are destructured or stringified - `@`, `$`, and strings nested inside destructured objects. A string bound to a plain hole is captured as-is, so very long free-text arguments need their own handling.
- ByTransforming<Shipment> also applies to every subclass of Shipment
- Destructuring policies also control what {Shipment} without @ logs
- ToMaximumStringLength is a sufficient way to hide personal data
- The default destructuring depth is unlimited
- A custom IDestructuringPolicy runs once at startup, not per event