来自NetCore Library Project的Nlog日志IP地址

问题描述 投票:0回答:1

我有一个包含多个项目的VS 2017解决方案,我有一个使用NLog方法的独立项目,可以在其他项目中使用它,而不是在所有项目中包含NLog。

  • Net Core Rest API
  • 净核心基础设施
  • Net Core数据库和持久性
  • Net Core Logger
  • 带有帮助程序和ViewModel类的其他NetStandard项目

我想记录客户端IP地址和用户,如果它已登录。我已经看到我必须在NLog.config中使用模板,但它不起作用,并且日志IPAddress字段为空。

这样做的正确方法是什么?

NLog.Config

<extensions>    
  <add assembly="NLog.Web.AspNetCore"/>
</extensions>

<targets>
  <target name="Database" xsi:type="Database">
    <commandText>
      INSERT INTO T_LOG
        (DATE_, APP, IPADDRESS, USER_, CENTRE, LEVEL_, LOGGER,
        METHOD, MESSAGE, EXCEPTION,
        SOURCE_FILE_PATH, LINE_NUMBER)
      VALUES(
        @Date, @App, @IPAddr, @User, @Centre, @Level, @Logger,
        @Method, @Message, @Exception,
        @SourceFilePath, @LineNumber);
    </commandText>

    <parameter name="@App" layout="${AppName}" />
    <parameter name="@IPAddr" layout="${aspnet-request-ip}" />
    <parameter name="@User" layout="" />
    <parameter name="@Centre" layout="" />
    <parameter name="@Date" layout="${longdate}" />
    <parameter name="@Level" layout="${level:upperCase=true}"/>
    <parameter name="@Logger" layout="${logger:shortName=false}"/>
    <parameter name="@Method" layout="${event-context:item=callermember}"/>
    <parameter name="@Message" layout="${message}" />
    <parameter name="@Exception" layout="${exception:format=ToString}"/>
    <parameter name="@SourceFilePath" layout="${event-context:item=callerpath}" />
    <parameter name="@LineNumber" layout="${event-context:item=callerline}" />

</target>

记录器类

using Microsoft.AspNetCore.Http;
using NLog;
using System;
using System.Runtime.CompilerServices;

namespace Project.Log
{
    public class CustomLogger
    {
        private readonly Logger logger;
        private Type type;

        public RhesusLog(Type type)
        {
            this.type = type;
            this.logger = LogManager.GetLogger(type.FullName);
        }

        public void Debug(string msg, Exception ex = null,
            [CallerFilePath] string CallerPath = "",
            [CallerMemberName] string CallerMember = "",
            [CallerLineNumber] int CallerLine = 0, params object[] args)
        {
            this.Log(LogLevel.Debug, msg, ex, CallerPath, CallerMember, CallerLine);
        }

        public void Info(string msg, Exception ex = null,
            [CallerFilePath] string CallerPath = "",
            [CallerMemberName] string CallerMember = "",
            [CallerLineNumber] int CallerLine = 0)
        {
            this.Log(LogLevel.Info, msg, ex, CallerPath, CallerMember, CallerLine);
        }

        // Other Levels logs ....

        private void Log(LogLevel Level, string msg,
            Exception Exception = null, string CallerPath = "",
            string CallerMember = "", int CallerLine = 0, params object[] parameters)
        {
            LogEventInfo LogEvent = new LogEventInfo(Level, this.type.FullName, msg);
            LogEvent.Parameters = parameters;
            LogEvent.Exception = Exception;
            LogEvent.Properties.Add("callerpath", CallerPath);
            LogEvent.Properties.Add("callermember", CallerMember);
            LogEvent.Properties.Add("callerline", CallerLine);

            this.logger.Log(LogEvent);
        }
    }
}

我使用了NLog Log,我可以在Log上看到这条消息

2018-09-06 23:31:44.6183 Debug Setting 'DatabaseParameterInfo.layout' to '${aspnet-request-ip}'
2018-09-06 23:31:44.6183 Debug Missing serviceProvider, so no HttpContext
c# asp.net-core-2.0 nlog asp.net-core-webapi httpcontent
1个回答
1
投票

如果NLog记录“缺少serviceProvider,因此没有HttpContext”,则serviceProvider未正确注册到NLog。

UseNLog()上的IWebHostBuilder将注册ServiceProvider并将HttpContextAccessor添加到DI系统。

因此,您应该仔细检查是否在正确的时间调用UseNLog(),请参阅program.cs的示例:

public static void Main(string[] args)
{
    // NLog: setup the logger first to catch all errors
    var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
    try
    {
        logger.Debug("init main");
        BuildWebHost(args).Run(); 
    }
    catch (Exception ex)
    {
        //NLog: catch setup errors
        logger.Error(ex, "Stopped program because of exception");
        throw;
    }
    finally
    {
        // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
        NLog.LogManager.Shutdown();
    }
}

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
        })
        .UseNLog()  // NLog: setup NLog for Dependency injection
        .Build();

另见https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2

© www.soinside.com 2019 - 2024. All rights reserved.