Serilog ForContext 未按预期工作
Serilog ForContext not working as expected
我在我的项目(MVC/web api 等)中使用 serilog & SEQ 和 Autofac (DI)。虽然它工作正常
但不确定这是正确的方法。
我有几个问题。请帮忙
Q1) 如何让 LoggerConfiguration 通过 Web.config(appsetting)管理,例如 Verbose/Debug 等
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.Enrich.FromLogContext()
.WriteTo.Seq(serilogUrl)
.CreateLogger();
Q2) 对于 Everymessage,我想写 userid。我使用了 push 属性 with out "using" 语句。
见下面的代码
public partial class Repo : BaseRepo<db>
{
public Repo(ILogger logger) : base(logger)
{
var currentuser = GetUserName();
LogContext.PushProperty("User Name", currentuser);
Logger.ForContext<Repo>();
}
public void somefunction()
{
try{}
catch(exception e){
Logger.Error(e, "Message");
}
}
}
Q3) 在构造函数中,我使用了 Logger.ForContext() 假设这将为每条消息写入 class 名称。但它不起作用。
Logger.ForContext<Repo>()
注意:我没有使用asp.net core/.Net core
ForContext
returns 一个新的 ILogger
引用,其中包含添加到记录器的上下文信息,因此您必须捕获该引用并将其用于日志记录。
例如
public class YourClass
{
private readonly ILogger _log;
public YourClass(ILogger log)
{
_log = log
.ForContext<YourClass>()
.ForContext("CurrentUserName", GetUserName());
// ...
}
public void Somefunction()
{
try
{
// ...
}
catch(exception ex)
{
_log.Error(ex, "Message...");
}
}
}
ps:鉴于您正在使用 Autofac,您可能有兴趣使用 Autofac-Serilog integration for contextual logger injection,而不是手动操作。
我在我的项目(MVC/web api 等)中使用 serilog & SEQ 和 Autofac (DI)。虽然它工作正常 但不确定这是正确的方法。
我有几个问题。请帮忙
Q1) 如何让 LoggerConfiguration 通过 Web.config(appsetting)管理,例如 Verbose/Debug 等
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.Enrich.FromLogContext()
.WriteTo.Seq(serilogUrl)
.CreateLogger();
Q2) 对于 Everymessage,我想写 userid。我使用了 push 属性 with out "using" 语句。 见下面的代码
public partial class Repo : BaseRepo<db>
{
public Repo(ILogger logger) : base(logger)
{
var currentuser = GetUserName();
LogContext.PushProperty("User Name", currentuser);
Logger.ForContext<Repo>();
}
public void somefunction()
{
try{}
catch(exception e){
Logger.Error(e, "Message");
}
}
}
Q3) 在构造函数中,我使用了 Logger.ForContext() 假设这将为每条消息写入 class 名称。但它不起作用。
Logger.ForContext<Repo>()
注意:我没有使用asp.net core/.Net core
ForContext
returns 一个新的 ILogger
引用,其中包含添加到记录器的上下文信息,因此您必须捕获该引用并将其用于日志记录。
例如
public class YourClass
{
private readonly ILogger _log;
public YourClass(ILogger log)
{
_log = log
.ForContext<YourClass>()
.ForContext("CurrentUserName", GetUserName());
// ...
}
public void Somefunction()
{
try
{
// ...
}
catch(exception ex)
{
_log.Error(ex, "Message...");
}
}
}
ps:鉴于您正在使用 Autofac,您可能有兴趣使用 Autofac-Serilog integration for contextual logger injection,而不是手动操作。