[英]ILogger<> doesn't cause NLog to log in File
I'm using NLog and I'm trying to log events using ILogger<> from Microsoft.Extensions.Logging qssembly. 我正在使用NLog,并且尝试使用Microsoft.Extensions.Logging qssembly中的ILogger <>记录事件。 According to the documentations everything is all correct eg nlog.config and Ilogger injection etc. but ILogger's methods don't work at all.
根据文档,一切都正确,例如nlog.config和Ilogger注入等。但是ILogger的方法根本不起作用。
These are some pieces of code which works and I can see the result in file: 这些是一些有效的代码,我可以在文件中看到结果:
using NLog;
Logger logger = LogManager.GetLogger("foo");
logger.Info("Program started");
But I'm trying this(which doesn't work): 但是我正在尝试这个(不起作用):
using Microsoft.Extensions.Logging;
public class UserController : ControllerBase
{
public UserController(ILogger<UserController> logger)
{
_logger = logger;
}
public async Task<User> Create()
{
_logger.LogInformation("Create Method's called");
}
}
This is nlog.config : 这是nlog.config :
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="info"
internalLogFile="C:\temp\internal-nlog.log">
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<targets async="true">
<target xsi:type="File"
name="LogFile"
fileName="${basedir}\temp\nlog-${shortdate}.log"
layout="${longdate} | ${uppercase:${level}} | ${message} | ${exception:format=tostring} | ${logger} | url: ${aspnet-request-url} | action: ${aspnet-mvc-action}" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="LogFile" />
</rules>
</nlog>
This is inside of Program.cs : 这是在Program.cs内部:
public static void Main(string[] args)
{
Logger loggerN = LogManager.GetLogger("foo");
loggerN.Info("Program started");
var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
logger.Debug("init Main");
CreateWebHostBuilder(args).Build().Run();
}
catch (Exception e)
{
logger.Error(e, "Program Shuted down");
throw;
}
finally
{
LogManager.Shutdown();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseNLog()
.ConfigureLogging(options => { options.ClearProviders(); })
.UseStartup<Startup>();
}
here just two first lines of Main works. 这里只是主要作品的前两行。
Move UseNLog()
to be after ConfigureLogging(options => { options.ClearProviders(); })
. 将
UseNLog()
移到ConfigureLogging(options => { options.ClearProviders(); })
。 For example: 例如:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(options => { options.ClearProviders(); })
.UseNLog();
If you call options.ClearProviders()
after UseNLog()
, it causes NLog to be removed as a logging provider. 如果在
UseNLog()
options.ClearProviders()
之后调用options.ClearProviders()
,它将导致NLog作为日志记录提供程序被删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.