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

问题描述 投票:0回答:2

我在WebJobs项目中使用Nlog和Application Insights作为Target来记录遥测。如果我只记录下面的消息,一切似乎都有效。

_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;
}
c# .net azure nlog azure-application-insights
2个回答
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 portal中看到参数:

enter image description here


0
投票

另一个可能更简单的选择是使用结构化日志记录。

EG

_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

注意:所以在这种情况下不要使用插值字符串。

© www.soinside.com 2019 - 2024. All rights reserved.