NLog:从nlog.config切换到编程配置

9

之前,我的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);     
    }

非常感谢您的帮助!谢谢!

2个回答

4

您的应用程序是否具有足够的权限在C驱动器的根目录中编写日志文件?请尝试使用${basedir}/nLogFile.txt,并查看是否有效。


4
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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接