【问题标题】:Unable to log addition Info using LogContext无法使用 LogContext 记录附加信息
【发布时间】:2021-12-28 14:37:19
【问题描述】:

我在 catch 块中使用 serilog.log.error 记录错误。我也想记录 DBName 和 Client name。

这是我的代码:

Startup.cs

using System;
using System.IO;
using Microsoft.Owin;
using Owin;
using System.Web.Http;
using IdentityServer3.AccessTokenValidation;
using System.IdentityModel.Tokens;
using Serilog;
using CincAccounting.Areas.Common.Utils;
using CincAccounting.Middleware;

[assembly: OwinStartup(typeof(CincAccounting.Startup))]

namespace CincAccounting
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var output = "{DBName} {Client} {Exception}";

            // Configure logger
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.File(System.IO.Directory.GetDirectoryRoot(AppDomain.CurrentDomain.BaseDirectory) + "logs\\accounting\\CINC-Accounting.txt", rollingInterval: RollingInterval.Day,outputTemplate: output)
                .Enrich.FromLogContext()
                .CreateLogger();

            Log.Information("Application Started...");
            app.Use<LoggingEnrichmentMiddleware>(Log.Logger);
            //app.Use<SerilogMiddleware>();            
        }
    }
}

LoggingEnrichmentMiddleware.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using CincAccounting.Areas.Common.MultiTenant;
using CincAccounting.Areas.Common.Utils;
using CincAccounting.Areas.UsersManagement.Models;
using CincAccounting.Controllers;
using Microsoft.Owin;
using Serilog;
using Serilog.Context;
using System.Web.Http;
namespace CincAccounting.Middleware
{
    /// <summary>
    /// 
    /// </summary>
    public class LoggingEnrichmentMiddleware : OwinMiddleware
    {
        private readonly ILogger logger;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="next"></param>
        /// <param name="logger"></param>

        public LoggingEnrichmentMiddleware(OwinMiddleware next, ILogger logger)
       : base(next)
        {
            this.logger = logger;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task Invoke(IOwinContext context)
        {
            string txtDBName = "";
            string txtUserName = "";
            if (HttpContext.Current.Session!=null && HttpContext.Current.Session[GlobalConstants.TenantKey] != null)
            {
                ITenant tanent = (ITenant)HttpContext.Current.Session[GlobalConstants.TenantKey];
                if (tanent != null)
                {
                    txtDBName = tanent.DbName;
                }
            }
            if (HttpContext.Current.Session!=null && HttpContext.Current.Session[GlobalConstants.UserProfileCinc] != null)
            {
                UserProfileCINC userProfile = (UserProfileCINC)HttpContext.Current.Session[GlobalConstants.UserProfileCinc];
                if (userProfile != null)
                {
                    txtUserName = userProfile.txtUserName;
                }
            }

            
            // enrich LogContext with user info
            using (LogContext.PushProperty("DBName", txtDBName))
            using (LogContext.PushProperty("Client", txtUserName))
            { 
                try
                {
                   // this.logger.Information("UserName : " + context.Authentication.User.Identity.Name);
                    await this.Next.Invoke(context);

                }
                catch (Exception ex)
                {    
               this.logger.Error(ex, $"{nameof(LoggingEnrichmentMiddleware)} caught exception.");
                    throw;
                }
            }
        }
    }
}

我正在记录来自控制器捕获块 serilog.log.error("error message") 的错误。

我无法看到记录错误的 DBName 和客户端。

请建议我缺少什么。

【问题讨论】:

标签: c# asp.net-core model-view-controller


【解决方案1】:

我看不到serilog.log.error,只有this.logger.Error
如果我没看错,您问为什么在日志中看不到 DbName 和 Client。这是因为你没有记录它。您记录异常(可以是任何内容)以及方法的名称。

可能类似于 `this.logger.Error(ex, $"{nameof(LoggingEnrichmentMiddleware)} 捕获异常。DBName={txtDBName},UserName={txtUserName}");

【讨论】:

  • 我正在从其他控制器方法调用 serilog.log.logger.error。例如: public ActionResult ChartList() { try { return View(); } catch (Exception e) { Serilog.Log.Logger.Error("错误:ChartListController.ChartList:" + e.Message); } }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
  • 2021-04-19
  • 2021-05-26
  • 2012-01-27
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多