我已将NLog添加到我的MVC Core 2.2项目中,除了应用程序启动日志记录之外,其他一切都正常。日志在控制器中写得很好,但在Program.cs中写得不好。 这是我的主要方法,所有NLog内容都取自NLog文档:
public static void Main(string[] args)
{
// NLog: setup the logger first to catch all errors
var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
logger.Info("Starting app");
CreateWebHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
// NLog: catch setup errors
logger.Error(ex, "App failed to start");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
}
}
NLog自己的日志显示以下内容:
错误已引发错误。异常:System.ArgumentException: 路径不是合法形式。在 NLog.Targets.FileTarget.Write(LogEventInfo logEvent)位于 NLog.Targets.Target.Write(AsyncLogEventInfo logEvent)
这很奇怪,因为日志随后正确地写入了我定义的文件路径。
这是我的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\nlog.log"
throwConfigExceptions="true">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<variable name="logFilePath" value="${configsetting:name=Logging.LogFilePath}"/>
<targets>
<target xsi:type="File"
name="PortailUsagersCore"
fileName="${logFilePath}"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|controller: ${aspnet-mvc-controller}|action: ${aspnet-mvc-action}"
maxArchiveFiles="4"
archiveNumbering="Rolling"
archiveAboveSize="2097152" />
</targets>
<rules>
<logger name="*" writeTo="PortailUsagersCore" />
</rules>
</nlog>
LogFilePath是在日志记录部分的appsettings.json和appsettings.development.json中定义的:
"Logging": {
"LogFilePath": "C:\\Logs\\Portail\\PortailUsagersCore.log",
"IncludeScopes": false,
"LogLevel": {
"Default": "Trace",
"Microsoft": "Information"
}
}
答案 0 :(得分:1)
由于RolfKristensen的建议,我设法使它起作用。 现在可以在NLog初始化之前读取Appsettings,因此NLog现在可以读取其中的文件路径。我使用NLog.GlobalDiagnosticsContext在NLog.config中设置filePath。
string env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
// Load config file to read LogFilePath
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env}.json", optional: true, reloadOnChange: true)
.Build();
// LogFilePath is read in nlog.config
NLog.GlobalDiagnosticsContext.Set("LogFilePath", config["Logging:LogFilePath"]);
// NLog: setup the logger first to catch all errors
var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
在我的NLog.config中,我是这样使用的:
<variable name="logFilePath" value="${gdc:item=LogFilePath}"/>
<targets>
<target xsi:type="File"
name="PortailUsagersCore"
fileName="${logFilePath}"