无法将用户信息输入Serilog纯文本日志

时间:2018-05-17 16:20:38

标签: asp.net-mvc httpcontext serilog

我试图在应用程序中实现一些简单的日志记录。我正在使用Serilog,但由于我无法控制的情况,我无法使用Seq作为接收器。现在,我被告知只需将日志写入本地文件即可。

我能够成功记录基本信息,但是无法将用户的信息记录到日志中。 Serilog.Enrichers.Environments包获取信息很好,但这些方法只会丰富日志,而这些日志在纯文本日志中看不到。当我使用Seq作为接收器(我不能用于我的最终实现)时,我可以看到记录的丰富度很好。

目前我正在尝试从HttpContext获取用户信息,但它正在返回null。以下是我尝试过的代码示例:

public static class HTMLHelperExtensions
{
    public static string CurrentUser
    {
        get
        {
            HttpContext httpContext = HttpContext.Current;
            if (httpContext == null || httpContext.User == null)
                return null;

            return httpContext.User.Identity.Name;
        }
    }
}

以下是我Global.asax中的日志记录配置:

Log.Logger = new LoggerConfiguration()
            .Enrich.WithEnvironmentUserName()
            .WriteTo.File(
                "fileLocation.txt",
                restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information,
                rollingInterval: RollingInterval.Infinite,
                fileSizeLimitBytes: 10485760, //10MiB
                retainedFileCountLimit: 50 )                
            .WriteTo.Seq("http://localhost:5341")
            .CreateLogger();

我从以下地方调用代码:

public class HomeController : Controller
{
    public ActionResult Index()
    {

        Log.Information("Application initial load. Included in Audit Log: {auditLog}. User: {User}", true, HTMLHelperExtensions.CurrentUser);
        //other code

        return View();
    }
}

.Enrich.WithEnvironmentUserName()方法效果很好,但我不知道如何将这些信息放入日志的实际主体而不是浓缩。

2 个答案:

答案 0 :(得分:1)

我现在想通了。如果我使用httpContext.Request.LogonUserIdentity.Name代替httpContext.User.Identity.Name,它会向我提供我想要的信息。

如果有办法使用Serilog配置将此信息附加到日志主体而不是我的方式,我会接受这个答案。

答案 1 :(得分:1)

不确定您要找的是什么,但您可以使用以下内容构建自定义内容:

class CurrentUserEnricher : Serilog.Core.ILogEventEnricher
{
    public void Enrich(Serilog.Events.LogEvent logEvent, Serilog.Core.ILogEventPropertyFactory lepf) =>
        logEvent.AddPropertyIfAbsent(lepf.CreateProperty("CurrentUser", HTMLHelperExtensions.CurrentUser));
}

并在管道中包含:

.Enrich.With<CurrentUserEnricher>()

然后只要{Properties}{CurrentUser}采用您的渲染格式,您就会获得包含的值吗?

相关问题