C# 使用NLog在ASP.NET Core中记录异常

C# 使用NLog在ASP.NET Core中记录异常,c#,.net,logging,asp.net-core,nlog,C#,.net,Logging,Asp.net Core,Nlog,我目前正在尝试使用NLog记录异常消息等,目前为止运气不佳,我无法想象为什么 为了设置NLog,我使用了以下指南: 我已经在asp.net核心上设置了这个,并尝试在我的商业项目上登录 业务 using Microsoft.Extensions.Logging; public class FileService { private readonly ILogger<FileService> _logger; public Task<DataResult<

我目前正在尝试使用NLog记录异常消息等,目前为止运气不佳,我无法想象为什么

为了设置NLog,我使用了以下指南:

我已经在asp.net核心上设置了这个,并尝试在我的商业项目上登录

业务

using Microsoft.Extensions.Logging;

public class FileService
{
    private readonly ILogger<FileService> _logger;

    public Task<DataResult<ICollection<BlankDTO>>> Test(Guid appId, Guid fileId)
    {
        try
        {
            throw new DivideByZeroException();
        }
        catch (DivideByZeroException ex)
        {
            _logger.LogError("EventId", ex, "Welp, something went wrong", new object[0]);
        }
    }
}
  • NLog.Web.ASpNetCore(4.4.1)
  • Microsoft.NETCore.App(1.1.2)

我创建了一个日志事件

public class LoggingEvents
{
    public const int GENERATE_ITEMS = 1;
    public const int LIST_ITEMS = 2;
    public const int GET_ITEM = 3;
    public const int INSERT_ITEM = 4;
    public const int UPDATE_ITEM = 5;
    public const int DELETE_ITEM = 6;

    public const int GET_ITEM_NOTFOUND = 7;
    public const int UPDATE_ITEM_NOTFOUND = 8;
}
我可以像这样记录错误:

//Logging example
try
{
    throw new Exception();
}
catch (Exception ex)
{
    _logger.LogError(LoggingEvents.GET_ITEM, ex, "Test({appId}, {fileId} Failed", appId, fileId);
}

希望这对某人有所帮助。

我认为您不需要这些活动:

logger.LogError($“{ex.Message}{{@0}}”,ex,arg0)

logger.LogError(例如消息,例如arg0)

以及:

layout=“[${date:format=yyyy-MM-dd HH:MM:ss.fff-zzz}]${level:uppercase=true:truncate=3}${threadid}${mdlc:CorrelationId}${message}${onexception:${newline}${exception:format=ToString,Data}”/>

请参见示例和使用库:


这里有什么问题?@Julian除了另一个例外,例外情况不会被记录info@Julian,异常是否不应与此一起记录?
public class LoggingEvents
{
    public const int GENERATE_ITEMS = 1;
    public const int LIST_ITEMS = 2;
    public const int GET_ITEM = 3;
    public const int INSERT_ITEM = 4;
    public const int UPDATE_ITEM = 5;
    public const int DELETE_ITEM = 6;

    public const int GET_ITEM_NOTFOUND = 7;
    public const int UPDATE_ITEM_NOTFOUND = 8;
}
//Logging example
try
{
    throw new Exception();
}
catch (Exception ex)
{
    _logger.LogError(LoggingEvents.GET_ITEM, ex, "Test({appId}, {fileId} Failed", appId, fileId);
}