问题
I write below code to log/store logs with an objects to Azure Table Storage by using SeriLog, But I got the object stored in "RenderedMessage" column (in azure table) or "Data" column, While I need to store each field/property in the class to a separated column in the Table storage. Please see below:
var _simpleTransation = new SimpleTransation(99, "some title9", "type99");
var logger = new LoggerConfiguration()
.WriteTo.AzureTableStorage(storage,LogEventLevel.Information,null, "LogStorage",false,null,null,null,false)
.Enrich.WithProperty("SimpleTransation", "@_simpleTransation", true)
.Enrich.FromLogContext()
.CreateLogger()
.ForContext<SimpleTransation>();
logger.Information<SimpleTransation>("{@SimpleTransation}", _simpleTransation);
So I need to add columns to azure storage table that represent my object fields and not serialize my whole object inside RenderedMessage log?
回答1:
So I need to add columns to azure storage table that represent my object fields and not serialize my whole object inside RenderedMessage log?
You could use propertyColumns
attribute to add a new column when you write to azure table storage.
Note:You need to call Enrich.FromLogContext()
and the property would show up in the Azure Table Storage.
Here is an article about Enrichment. Log events can be enriched with properties in various ways.
You need to use LogContext.PushProperty
to add what property and value you want to add.
You could refer to the following code to have a try:
static void Main(string[] args)
{
var storage = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
string tableName = "table411";
var exampleuser = new User { Id = 1, Name = "joey", Age = 23 };
var _log = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.AzureTableStorageWithProperties(storage, propertyColumns: new string[] { "UserId" });
LogContext.PushProperty("UserId", exampleuser.Id);
var logger = _log.CreateLogger();
logger.Information("{@User}",exampleuser);
}
class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
Screen shot:
来源:https://stackoverflow.com/questions/49802904/log-structured-data-to-azure-storage-table-by-serilog-store-all-object-in-render