Search code examples
.net-coreloggingasp.net-core-webapiserilog

Serilog .NET with Azure Table Storage


I hear great things about Serilog and I would like to utilize it in my .NET Core API.

Due to the low cost of Azure Table Storage, it is my preferred "database". I see Serilog has a sink for that.

My question is the following:

In my current iteration I have a custom class (LogDetail) which contains the calling method, the authenticated user (from the HttpContext) if any, the stack trace, the calling application etc.

How can I incorporate my custom object to be logged alongside the columns that Serilog will create in Azure Table Storage? Preferably not as a JSON string but instead, each property of the object should be in its own column.

Is this doable or do I need to write a custom sink?

Thank you for your answers in advance!


Solution

  • I try to add custom property in azure table storage when using Serilog 2.x. I found no direct way to add properties in LogEventEntity.

    Soultion: If you want implement it, you should use SDK to do it.


    What I have tried.

    Just the test result, not the solution, solution is the link above

    AzureTableStorageTableResolver.cs

    using Microsoft.Azure.Cosmos.Table;
    using Microsoft.Azure.Documents;
    using Microsoft.Extensions.Primitives;
    using Serilog.Core;
    using Serilog.Events;
    
    namespace AspCore7_Web_Identity
    {
        public class AzureTableStorageTableResolver : ILogEventEnricher
        {
            private readonly IConfiguration _configuration;
    
            public AzureTableStorageTableResolver(IConfiguration configuration)
            {
                _configuration = configuration;
            }
    
            public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
            {
                var tableName = logEvent.Properties["TableName"]?.ToString() ?? "default";
    
                var myArray = _configuration.GetSection("Table1").Get<string[]>(); 
    
                for (int i = 0; i < myArray.Length; i++)
                {
                    var myProperty = new LogEventProperty(myArray[i], new ScalarValue("DefaultValue"));
                    logEvent.AddPropertyIfAbsent(myProperty);
                }
    
            }
        }
    
    }
    

    Program.cs

    builder.Services.AddSingleton<ILogger>(sp =>
            {
                return new LoggerConfiguration()
                .ReadFrom.Configuration(builder.Configuration)
                .Enrich.With(new AzureTableStorageTableResolver(builder.Configuration))
                .CreateLogger();
            });
    

    And I found the properties added to Data column.

    enter image description here