在NLog Wiki页面上,我发现此Page描述了如何记录异常。但是在页面中,他们提到了实现此功能的类似方法。
<nlog>
<targets>
<target name="f" type="File"
layout="${longdate} ${message} ${exception:format=tostring}"/>
</targets>
<rules>
<logger name="*" writeTo="f"/>
</rules>
</nlog>
我正在动态创建配置文件,并且不确定如何在我的代码中实现上述配置。
配置代码为
public class NLogManager : ILogManager
{
public NLogManager()
{
var config = new LoggingConfiguration();
var consoleTarget = new ConsoleTarget();
config.AddTarget("console", consoleTarget);
var consoleRule = new LoggingRule("*", LogLevel.Trace, consoleTarget);
config.LoggingRules.Add(consoleRule);
var fileTarget = new FileTarget();
string folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
fileTarget.FileName = Path.Combine(folder, "Log.txt");
config.AddTarget("file", fileTarget);
var fileRule = new LoggingRule("*", LogLevel.Warn, fileTarget);
config.LoggingRules.Add(fileRule);
LogManager.Configuration = config;
}
public ILogger GetLog([System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = "")
{
string fileName = callerFilePath;
if (fileName.Contains("/"))
{
fileName = fileName.Substring(fileName.LastIndexOf("/", StringComparison.CurrentCultureIgnoreCase) + 1);
}
var logger = LogManager.GetLogger(fileName);
return new NLogLogger(logger);
}
}
有人可以建议我如何动态配置吗?
答案 0 :(得分:3)
您需要在(文件)Layout
上设置Target
属性:
fileTarget.Layout = "${longdate} ${message} ${exception:format=tostring}";
注意:默认布局为${longdate}|${level:uppercase=true}|${logger}|${message}
,并且不包含您所看到的异常。这将在NLog 5或6中更改:https://github.com/NLog/NLog/issues/1292