[英]NLog: Switching from nlog.config to programmatic configuration
以前,我的 ASP .NET MVC5 應用程序在使用 nlog.config 文件時可以很好地記錄錯誤日志。 現在我想擺脫配置文件的方法; 我想以編程方式配置 Nlog 並消除對配置文件的需要。 這些示例很好地向我展示了如何以編程方式設置它,但我對如何實際調用配置類並實際實現它感到困惑。 這是我所擁有的:
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
NALSPrincipal userInfo = (NALSPrincipal)Context.User;
// Step 1. Create configuration object
var config = new LoggingConfiguration();
// Step 2. Create targets and add them to the configuration
var fileTarget = new FileTarget();
config.AddTarget("file", fileTarget);
// Step 3. Set target properties
fileTarget.FileName = "C:/nlogFile.txt";
fileTarget.Layout = "Exception Type: ${exception:format=Type}${newline}
Target Site: ${event-context:TargetSite}${newline}
Message: ${message}";
// Step 4. Define rules
var rule2 = new LoggingRule("*", LogLevel.Trace, fileTarget);
config.LoggingRules.Add(rule2);
// Step 5. Activate the configuration
LogManager.Configuration = config;
Logger logger = LogManager.GetCurrentClassLogger();
LogEventInfo eventInfo = new LogEventInfo(LogLevel.Trace, "", logger.Name);
eventInfo.Properties["TargetSite"] = ex.TargetSite;
eventInfo.Exception = ex;
logger.Log(eventInfo);
}
有誰知道這不起作用? 這是我基於此的文檔: https : //github.com/nlog/NLog/wiki/Configuration-API
如果有幫助,以下是我使用 nlog.config 文件時返回的內容,並且效果很好:
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
NALSPrincipal userInfo = (NALSPrincipal)Context.User;
Logger logger = LogManager.GetCurrentClassLogger();
LogEventInfo eventInfo = new LogEventInfo(LogLevel.Trace, "", logger.Name);
eventInfo.Properties["CUID"] = userInfo.userDetails.ContactID;
eventInfo.Properties["Username"] = Context.User.Identity.Name;
eventInfo.Properties["TargetSite"] = ex.TargetSite;
eventInfo.Exception = ex;
logger.Log(eventInfo);
}
非常感謝任何幫助! 謝謝!
您是否以足夠的權限運行您的應用程序以在 C 驅動器的根目錄中寫入日志文件? 用 ${basedir}/nLogFile.txt 試試看,看看它是否有效。
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
var configuration = new NLog.Config.LoggingConfiguration();
var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "logfile.txt" };
var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
configuration.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logfile);
configuration.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logconsole);
NLog.LogManager.Configuration = configuration;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.