Wednesday, December 20, 2023

.NET 8.0: [LogProperties] Attribute

There are a lot of improvements to Logging in .NET 8.0, and in this post, let's have a look at the new LogProperties attribute.

Now we can use LogProperties attribute in log methods attributed with LoggerMessage attribute (introduced with .NET 6.0). It's available through Microsoft.Extensions.Telemetry.Abstractions NuGet package.

Consider the below sample console application code.

using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

using var channel = new InMemoryChannel();

try
{
// Setup Application Insights
    IServiceCollection services = new ServiceCollection();
    services.Configure<TelemetryConfiguration>(config => config.TelemetryChannel = channel);
    services.AddLogging(builder =>
    {
        builder.AddApplicationInsights(
            configureTelemetryConfiguration: (config) =>
            {
                config.ConnectionString = "<ConnectionString>";
            },
            configureApplicationInsightsLoggerOptions: (options) =>
            {
            }
        );
    });

    IServiceProvider serviceProvider = services.BuildServiceProvider();
    ILogger<Program> logger = serviceProvider.GetRequiredService<ILogger<Program>>();
    User user = new("John""Doe");
    Console.WriteLine($"Hello {user.FirstName}!");     // Structured logging with [LogProperties]
    logger.SaidHello(user.FirstName, user);
}
finally
{
    // Explicitly call Flush() followed by Delay, as required in console apps.
    // This ensures that even if the application terminates, telemetry is sent to the back end.

    channel.Flush();

    await Task.Delay(TimeSpan.FromMilliseconds(1000));
}

public record User(string FirstName, string LastName);

public static partial class LoggerExtensions
{
    [LoggerMessage(EventId = 1,  Level = LogLevel.Information,  Message = "Saying hello to {firstName}.")]
    public static partial void SaidHello(this ILogger logger,  string firstName,  [LogProperties] User user);
}

Here you can see the usage of [LogProperties] inside the LoggerExtensions.SaidHello method.

And this one would get logged in Application Insights as follows (in that case in any telemetry collector):
Structured Logging with LogProperties

More read:
   High-performance logging in .NET
   Watch: Improving your application telemetry using .NET 8 and Open Telemetry | .NET Conf 2023

Hope this helps.

Happy Coding.

Regards.
Jaliya

No comments:

Post a Comment