dotnet / dotnet/extensions

LogProperties attribute: serialize nested objects in collections instead of ToString

Open
#6,785 9 comments 0 reactions 0 assignees View on GitHub
area-telemetry untriaged
Dominant language
C#
Stars
3.2k
Forks
894
Avg merge
1d 12h
Merged PRs (30d)
23

Description

### Describe the feature or question

**Context:**
When using the LogProperties attribute in @dotnet/extensions (see [README](https://github.com/dotnet/extensions/blob/4270c0080b3b3fa1fbc3b6c083d2b6baeb944166/src/Libraries/Microsoft.Extensions.Telemetry.Abstractions/README.md)), if an object property is a collection of objects, each item is currently rendered using its ToString method. This forces implementing ToString on every object type to get meaningful logging output.

**Request / Question:**
Could the LogProperties attribute serialize nested objects (e.g., as JSON) rather than calling ToString on each element in a collection? This would provide richer logging and eliminate the need for ToString implementations on contained types.

Currently, to obtain this richer logging, I am forced to add boilerplate code like the following:

```csharp
private static readonly Action _logTemperatures = LoggerMessage.Define(
LogLevel.Information,
new EventId(1, nameof(WeatherReport)),
"Request done. payload: {@Payload}"); // message template, not interpolated string

private void LogTemperatures(WeatherReport payload) => _logTemperatures(_logger, payload, null);
```

#### Example
```csharp
public class WeatherReport {
public string City { get; set; }
public List Temperatures { get; set; }
}

public class TemperatureReading {
public DateTime Time { get; set; }
public double Value { get; set; }
}
```
If I log WeatherReport using LogProperties, I'd like the Temperatures property to be logged as an array of objects, not a list of ToString values.

Is there a recommended way to achieve this, or could this be supported in future versions?

**Related File:**
[src/Libraries/Microsoft.Extensions.Telemetry.Abstractions/README.md](https://github.com/dotnet/extensions/blob/4270c0080b3b3fa1fbc3b6c083d2b6baeb944166/src/Libraries/Microsoft.Extensions.Telemetry.Abstractions/README.md)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.