在我的 .NET Core 应用程序中,我使用了一些环境,我想为每个环境设置不同的日志文件路径。
例如,
Development - c:\logs
Staging - d\apps\logs
对于每个环境,我在
appsettings.{env}.json
中都有配置部分:"LocalPaths": {
"LogFileRootDirectory": "c:\\logs\\"
}
和
nlog.config
的一部分:<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="Warn"
internalLogFile="${logFileRootDirectory}internal-nlog.txt">
...
</nlog>
实现它的最佳方法是什么?
最佳答案
您可以使用 (NLog) 变量。
例如
<targets>
<target name="file" xsi:type="File"
fileName="${var:mydir}/logfile.txt" ... >
在 C# 中
LogManager.Configuration.Variables["mydir"] = "c:\logs";
当您更改变量时,路径会自动更改 - 无需重新加载。
另见 the docs for ${var}
更新 : 您可以更改
LogManager.Configuration
后:env.ConfigureNLog("nlog.config");
例如您的 startup.cs 可能如下所示:
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
//add NLog to ASP.NET Core
loggerFactory.AddNLog();
//add NLog.Web
app.AddNLogWeb();
//configure nlog.config in your project root.
env.ConfigureNLog("nlog.config");
LogManager.Configuration.Variables["mydir"] = "c:\logs";
...
关于asp.net-core - 动态更改日志文件的文件路径 .NET Core + NLog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42945483/