NetCore库项目中的Nlog日志IP地址

时间:2018-09-05 19:19:40

标签: c# asp.net-core-2.0 nlog asp.net-core-webapi httpcontent

我有一个包含多个项目的VS 2017解决方案,我有一个单独的项目,使用NLog方法可以将其与其他项目一起使用,以便不将NLog包含在所有项目中。

  • NetCore Rest API
  • NetCore基础结构
  • NetCore数据库和持久性
  • NetCore记录器
  • 具有帮助程序和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日志,并且可以在日志上看到此消息

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

1 个答案:

答案 0 :(得分: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