代码之家  ›  专栏  ›  技术社区  ›  Giox

NLog使用类似.NET6的WithProperty方法注入自定义属性

  •  0
  • Giox  · 技术社区  · 2 年前

    我有一个.NET 4.8项目,我以以下方式使用NLog:

    public class ReportsController : ApiController
    {
        private static NLog.Logger logger = NLog.LogManager.GetLogger("Application");
        public void SomeMethod()
        {
           string userID = 'ABC123';
           logger.WithProperty("UserId", userID).Info("UserId {0} has created a new report.", userID);
        }
    }
    

    通过上面的代码,我可以将UserId属性保存在数据库的Logs表中的一个专用字段中,以便按UserId轻松地过滤日志。

    现在,我们已将应用程序升级为 .NET 6 ,使用 依赖项注入

    因此,当前代码如下:

    using Microsoft.Extensions.Logging;
    
    public class AuthorizationManagerService: IAuthorizationManagerService
    {
        private readonly ILogger _logger; //interface in Microsoft.Extensions.Logging
    
        public AuthorizationManagerService(ILogger<AuthorizationManagerService> logger)
        {
            _logger = logger;
        }
    
        public void SomeMethod()
        {
           string userID = 'ABC123';
           _logger.LogInformation("UserId {0} has created a new report.", userID);
        }
    

    在appsettings.json中,我为NLog定义了以下规则:

      "NLog": {
        "throwConfigExceptions": true,
        "internalLogLevel": "Error",
        "internalLogFile": "${CurrentDir}/internal-nlog.txt",
        "extensions": [
          { "assembly": "NLog.Extensions.Logging" },
          { "assembly": "NLog.Web.AspNetCore" }
        ],
        "targets": {
          "async": false,
          "logfile": {
            "type": "File",
            "fileName": "${CurrentDir}/Logs/nlog-${shortdate}.log"
          },
          "logconsole": {
            "type": "Console"
          },
          "logtrace": {
            "type": "Trace"
          },
          "logdatabase": {
            "type": "Database",
            "connectionString": "Data Source=MyDatabaseInstance;Initial Catalog=MyDatabase;Integrated Security=false;user id=TheUser;password=INCORRECT;",
            "keepConnection": "true",
            "commandText": "insert into \"Logs\"(\"LogDate\", \"LogMessage\", \"LogLevel\", \"LogIP\", \"LogUrl\", \"LogException\", \"LogUserId\", \"LogModule\", \"LogCallSite\", \"LogSessionId\") values (@LogDate, @LogMessage, @LogLevel, @LogIP, @LogURL, @LogException, @LogUserId, @LogModule, @LogCallSite, @LogSessionId);",
            "parameters": [
              {
                "name": "@LogDate",
                "layout": "${date}"
              },
              {
                "name": "@LogMessage",
                "layout": "${message}"
              },
              {
                "name": "@LogLevel",
                "layout": "${level:uppercase=true}"
              },
              {
                "name": "@LogIP",
                "layout": "${aspnet-request-ip}"
              },
              {
                "name": "@LogUrl",
                "layout": "${aspnet-request-url}"
              },
              {
                "name": "@LogException",
                "layout": "${exception:format=tostring}"
              },
              {
                "name": "@LogUserID",
                "layout": "${event-properties:UserId}"
              },
              {
                "name": "@LogModule",
                "layout": "${logger}"
              },
              {
                "name": "@LogCallSite",
                "layout": "${callsite:filename=true}"
              },
              {
                "name": "@LogSessionID",
                "layout": "${aspnet-sessionid}"
              }
            ]
          }
        },
        "rules": [
          {
            "logger": "*",
            "minLevel": "Info",
            "writeTo": "logdatabase"
          },
          {
            "logger": "*",
            "minLevel": "Debug",
            "writeTo": "logconsole"
          },
          {
            "logger": "*",
            "minLevel": "Info",
            "writeTo": "logfile"
          },
          {
            "logger": "*",
            "minLevel": "Trace",
            "writeTo": "logtrace"
          }
        ]
      }
    

    我如何传递userID信息,以便像以前那样将其写入数据库字段LogUserId?

    0 回复  |  直到 2 年前