[英]Add custom properties to Serilog
我在我的應用程序中使用 Serilog 和 MS SQL Server 接收器。 讓我們假設我已經定義了以下類......
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
// ... more properties
}
...並創建了一個實例:
var person = new Person
{
FirstName = "John",
LastName = "Doe",
BirthDate = DateTime.UtcNow.AddYears(-25)
};
我在我的代碼中放置了以下日志調用:
Log.Information("New user: {FirstName:l} {LastName:l}",
person.FirstName, person.LastName);
是否也可以記錄BirthDate
屬性而不將其添加到消息模板中,以便在Properties
XML 列中呈現它? 我想稍后在我的應用程序日志查看器的詳細信息視圖中輸出它。
我基本上是在尋找類似於對象解構的行為,但沒有將平面對象打印為日志消息的一部分。
這很簡單:
Log.ForContext("BirthDate", person.BirthDate)
.Information("New user: {FirstName:l} {LastName:l}",
person.FirstName, person.LastName);
您實際上可以通過幾種不同的方式來做到這一點。 在您的情況下,第一種方法可能是最好的:
Log.ForContext("BirthDate", person.BirthDate)
.Information("New user: {FirstName:l} {LastName:l}",
person.FirstName, person.LastName);
但您也可以在其他場景中使用LogContext
:
Log.Logger = new LoggerConfiguration()
// Enrich all log entries with properties from LogContext
.Enrich.FromLogContext();
using (LogContext.PushProperty("BirthDate", person.BirthDate))
{
Log.Information("New user: {FirstName:l} {LastName:l}",
person.FirstName, person.LastName);
}
或者,如果您想記錄“常量”屬性,您可以像這樣添加它:
Log.Logger = new LoggerConfiguration()
// Enrich all log entries with property
.Enrich.WithProperty("Application", "My Application");
有關更多信息,請參閱上下文和相關性 - .NET 中的結構化日志概念 (5) 。
如果您使用的是通用的 Microsoft ILogger 接口,則可以使用 BeginScope;
using (_logger.BeginScope(new Dictionary<string, object> { { "LogEventType", logEventType }, { "UserName", userName } }))
{
_logger.LogInformation(message, args);
}
這在這里討論; https://blog.rsuter.com/logging-with-ilogger-recommendations-and-best-practices/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.