简体   繁体   中英

Serilog Azure Table Storage and context properties

I'm trying to use AzureTableStorageWithProperties in Serilog.Sinks.AzureTableStorage , and I have a property that's attached to the context; something like this:

using (LogContext.PushProperty("CameraId", camera.Id)
{
  /* ... */
}

So, I was wondering how I can configure the logger to consider this property and create a column for it when it's present on the context.

I tried this, but it doesn't seem to be working:

Log.Logger = new LoggerConfiguration()
  .ReadFrom.Configuration(configuration)
  .WriteTo.AzureTableStorageWithProperties(
    "my-connection-string",
    storageTableName: "mytable",
    propertyColumns: new[] { "CameraId" })
  .CreateLogger();

Also, as you may have noticed, I'm using Serilog.Settings.Configuration , so I was hoping you can tell me how I can put it into my appsettings.json too.

Thank you

I figured out why I wasn't seeing my property: I need to call Enrich.FromLogContext() and the property shows up in the Azure Table Storage.

I tried so hard to see how we can specify the propertyColumns in appsettings.json (or environment variables for that matter), but no luck ... :(

I got it working like:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Async", "Serilog.Sinks.AzureTableStorage" ],
    "WriteTo": [
      {
                "Name": "Async",
                "Args": {
                  "configure": [
                    {
                      "Name": "AzureTableStorageWithProperties",
                      "Args": {
                        "connectionString": "UseDevelopmentStorage=true",
                        "storageTableName": "LogTable",
                        "propertyColumns": [ "CameraId" ]
                      }
                    }

                  ]
                }
              }
            ],          
    "Enrich": [ "FromLogContext" ]
  }
}

For the Async bit use: Serilog.Sinks.Async.

Also don't forget to call Log.CloseAndFlush() at application shutdown ;-)

I have been looking for this solution since I was looking for a log storage that has more structure than blob: This works. Just a note, with the configuration rule in appsettings.json: your solution still works the bare-bone configuration in program.cs in code as below:

Log.Logger = new LoggerConfiguration()
             .ReadFrom.Configuration(Configuration)
             .Enrich.FromLogContext()
             .CreateLogger();

Thanks for posting the solution!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM