动态更改日志文件的文件路径 .NET Core + NLog [英] Change dynamically file path for log files .NET Core + NLog
问题描述
在我的 .NET Core 应用程序中,我使用了一些环境,我想为每个环境设置不同的日志文件路径.
In my .NET Core app I use some environments and I want to do different paths to log files for every environment.
例如,
Development - c:\logs
Staging - d\apps\logs
对于每个环境,我在 appsettings.{env}.json
中有配置部分:
For every environment I have config section in 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>
实现这一目标的最佳方法是什么?
What's the best way to implement that?
推荐答案
您可以使用 (NLog) 变量.
You could use (NLog) variables.
例如
<targets>
<target name="file" xsi:type="File"
fileName="${var:mydir}/logfile.txt" ... >
在 C# 中
LogManager.Configuration.Variables["mydir"] = "c:\logs";
当您更改变量时,路径会自动更改 - 无需重新加载.
When you change the variable, the path is automatically changed - no reload needed.
另见 ${var} 的文档
更新:您可以在以下时间更改LogManager.Configuration
:
Update: you could change the LogManager.Configuration
after:
env.ConfigureNLog("nlog.config");
例如您的 startup.cs 可能如下所示:
e.g. your startup.cs could look like this:
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";
...
这篇关于动态更改日志文件的文件路径 .NET Core + NLog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!