我在我的应用程序中使用Serilog和MS SQL Server接收器.我们假设我已经定义了以下类......
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
// ... more properties
}
Run Code Online (Sandbox Code Playgroud)
...并创建了一个实例:
var person = new Person
{
FirstName = "John",
LastName = "Doe",
BirthDate = DateTime.UtcNow.AddYears(-25)
};
Run Code Online (Sandbox Code Playgroud)
我在我的代码中放置了以下日志调用:
Log.Information("New user: {FirstName:l} {LastName:l}",
person.FirstName, person.LastName);
Run Code Online (Sandbox Code Playgroud)
是否可以在不将其添加到消息模板的情况下记录该BirthDate属性,以便在PropertiesXML列中呈现它?我想稍后在我的应用程序的日志查看器的详细信息视图中输出它.
我基本上寻找类似于对象解构的行为,但不打印平面对象作为日志消息的一部分.
Nic*_*rdt 21
这很简单:
Log.ForContext("BirthDate", person.BirthDate)
.Information("New user: {FirstName:l} {LastName:l}",
person.FirstName, person.LastName);
Run Code Online (Sandbox Code Playgroud)
Chr*_*vén 19
您实际上可以通过几种不同的方式来做到这一点。在您的情况下,第一种方法可能是最好的:
Log.ForContext("BirthDate", person.BirthDate)
.Information("New user: {FirstName:l} {LastName:l}",
person.FirstName, person.LastName);
Run Code Online (Sandbox Code Playgroud)
但是你也可以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);
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您想记录“常量”属性,您可以像这样添加它:
Log.Logger = new LoggerConfiguration()
// Enrich all log entries with property
.Enrich.WithProperty("Application", "My Application");
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅上下文和相关性 - .NET 中的结构化日志概念 (5)。
Jos*_*osh 18
如果您使用通用的 Microsoft ILogger 接口,则可以使用 BeginScope;
using (_logger.BeginScope(new Dictionary<string, object> { { "LogEventType", logEventType }, { "UserName", userName } }))
{
_logger.LogInformation(message, args);
}
Run Code Online (Sandbox Code Playgroud)
这是在这里讨论的;https://blog.rsuter.com/logging-with-ilogger-recommendations-and-best-practices/
| 归档时间: |
|
| 查看次数: |
7452 次 |
| 最近记录: |