Serilog ForContext 未按预期工作

标签 serilog

我在我的项目(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 我想写用户 ID。我在没有“使用”语句的情况下使用了推送属性。
看下面的代码
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() 假设这会将类名写入每条消息。但它不起作用。
   Logger.ForContext<Repo>()

注意:我没有使用asp.net core/.net core

最佳答案

ForContext 返回一个新的 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 感兴趣。为 contextual logger injection ,而不是手动执行。

关于Serilog ForContext 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52712516/

相关文章:

c# - Serilog 自定义接收器 - 使用 appsettings.json 设置最低级别不起作用

c# - Serilog 相当于 log4net.Config.Watch?

Serilog JSON 配置 LoggingLevelSwitch 访问

.net - 关于创建构建器的 Elasticsearch 异常的 Serilog

serilog - 从配置文件配置 AzureTableStorage Serilog 接收器

configuration - 如何使用环境变量覆盖 ASP.NET Core 配置数组设置

c# - Serilog - 覆盖配置值

c# - 强制使用 Serilog 中的特定参数(或通常在外部函数中)

c# - Serilog - 单独的信息文件,使用 appsetting.json 的异常(exception)

asp.net-core - 如何使用 Serilog 抑制 'An unhandled exception has occurred while executing the request.' 日志消息