具有Application Insights目标的NLog不会记录自定义参数和异常

时间:2019-04-26 04:28:49

标签: c# .net azure nlog azure-application-insights

我在WebJobs项目中使用Nlog和Application Insights作为目标来记录遥测。如果我只记录如下消息,一切似乎都可以正常工作。

_logger.Log(LogLevel.Info, "Job completed");

我可以在应用程序见解中看到跟踪信息,并显示消息“作业已完成”

但是我想记录一些参数以及如下消息。

_logger.Info($"Job created successfully", req.UserId, req.ReportName, jobId, searchString);

或如下所示

catch (Exception ex)
{
    _logger.Error(ex, "Error creating the job", req.UserId, req.ReportName, searchString);
    throw;
}

我期望在应用程序见解中有一个跟踪,其中包含与消息一起传递的参数。但是我只能看到该消息,而看不到任何参数或异常详细信息。

我想念什么?

编辑:

NLog nuget版本4.3.8和 Microsoft.ApplicationInsights.NLogTarget nuget版本2.4.1

更多代码:

try
{
    var jobId = _reportingService.RequestReport(req.ReportName, searchString).Result;

    _logger.Info($"Job created successfully", req.UserId, req.ReportName, jobId, searchString);

    var output = new RetrieveReportDataRequest()
    {
        CreationRequest = new ReportCreationRequest()
        {
            ImmutableUserId = req.UserId,
           ...
        },
        SearchParameters = searchString,
        JobId = jobId,
        Created = DateTime.UtcNow,
    };

    outputQueueMessage = JsonConvert.SerializeObject(output, settings);
}
catch (Exception ex)
{
    log.WriteLine(ex.Message);
    _logger.Error(ex, "Error creating the job", req.UserId, req.ReportName, searchString);
    throw;
}

2 个答案:

答案 0 :(得分:0)

您可以使用LogEventInfo,然后在其属性中添加参数。

示例代码:

有关日志级别的信息:

            LogEventInfo eventInfo = new LogEventInfo(LogLevel.Info, "event1", "this is a info111");
            eventInfo.Properties["myname"]= "myname is ddd";
            eventInfo.Properties["myid"] = "myid is ddd";
            eventInfo.Properties["myjobid"] = "myjobid is ddd";
            log.Log(eventInfo);

对于错误日志级别:

        #in you code, you can change the new Exception() to your own exception
        LogEventInfo eventinfo2 = new LogEventInfo(LogLevel.Error, null,null,null,null,new Exception("anexception222"));
        eventinfo2.Properties["errormessage"] = "thi si a error message";
        eventinfo2.Properties["myname"] = "myname is ddd";
        eventinfo2.Properties["myid"] = "myid is ddd";
        eventinfo2.Properties["myjobid"] = "myjobid is ddd";
        log.Log(eventinfo2);

然后您可以在azure门户中看到参数:

enter image description here

答案 1 :(得分:0)

另一个(也许更容易)的选择是使用结构化日志记录。

例如

_logger.Info("Job {JobId} created successfully for {User} on {ReportName} with {Search}", jobId, req.UserId, req.ReportName, searchString);

这将创建事件属性JobId,User,ReportName和Search。

另请参阅NLog - How to use structured logging

注意:因此,在这种情况下,请勿使用插值字符串。