Erased
Erased

Reputation: 221

Add a custom column to Serilog Table in Azure Table Storage for logging new information

It's possible to add a new column in a Serilog Table in Azure table Storage for logging new extra field like accountID or login Name?

I think it's possible to add a new column but its possible to pass extra fields in Serilog like i said for the new added columns? How i can define that in Startup.cs or web.config? Thanks

This is my configuration in web.config:

<add key="serilog:using:AzureTableStorage" value="Serilog.Sinks.AzureTableStorage" />
    <add key="serilog:write-to:AzureTableStorageWithProperties.connectionString" value="DefaultEndpointsProtocol=https;AccountName=MyAccountName;AccountKey=MyAccountKey;EndpointSuffix=core.windows.net" />
    <add key="serilog:write-to:AzureTableStorage.formatter" value="Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact" />
    <add key="serilog:write-to:AzureTableStorageWithProperties.storageTableName" value="Serilog" />

startup.cs configuration:

Log.Logger = new LoggerConfiguration()
        .ReadFrom.AppSettings()
        .CreateLogger();

Upvotes: 1

Views: 1718

Answers (1)

Jim Xu
Jim Xu

Reputation: 23111

If you want to add additional properties when you write log to azure table storage with Serilog, you need to call Enrich.FromLogContext() and LogContext.PushProperty. With the two methods, your application will add additional properties to Azure table. For more details, please refer to the document

For example

  1. Install SDK
Install-Package Serilog.Sinks.AzureTableStorage 
Install-Package Serilog.Enrichers.Thread
  1. Code
static void Main(string[] args)
        {

            var storage =CloudStorageAccount.Parse("");
            string tableName = "log";



            var _log = new LoggerConfiguration()
                           .Enrich.FromLogContext()
                           .WriteTo.AzureTableStorageWithProperties(storage, LogEventLevel.Information, storageTableName: tableName, propertyColumns: new string[] { "AccountId" , "Name" }) ;
            var logger = _log.CreateLogger();
            var exampleuser = new User { AccountId = 3, Name = "Allen" };
            LogContext.PushProperty("AccountId", exampleuser.AccountId);         
            logger.Information("{@User}", exampleuser);

            exampleuser = new User { AccountId = 1, Name = "Jim" };
            LogContext.PushProperty("AccountId", exampleuser.AccountId);
            logger.Information("{@User}", exampleuser);


            Console.ReadLine();



        }
 class User
    {
        public int AccountId { get; set; }
        public string Name { get; set; }

    }

enter image description here

Upvotes: 4

Related Questions