【发布时间】:2021-01-01 17:54:29
【问题描述】:
目前我正在使用使用服务堆栈构建的 .NET Core Web 应用程序。目前使用 NLog 提供日志记录,并以 Azure Application Insights 为目标。
目前,当我记录消息和异常时,我遇到了一些奇怪的行为:
Log.Fatal("test not implemented exception", new NotImplementedException()); //this logs under Exceptions in Application Insights
Log.Fatal(new NotImplementedException("test not implemented exception")); //this logs under Trace
我想要的是能够将第二行记录为异常而不是跟踪。有什么办法可以实现吗?
我无法找到这个问题的答案,所以我作为一个问题发布。
NLog exceptions as Trace in Application Insights - 这个没有提到如何将类型从 Trace 更改为 Exception
Application Insights - Logging exceptions - 这个没有提到NLog
https://github.com/Microsoft/ApplicationInsights-dotnet-logging/issues/102 - 这是最接近我需要的,但没有更新
编辑:由于注释标记无法正确显示图像和格式,我一直在使用以下代码行进行测试:
Log.Fatal("test no message - fatal", new NotImplementedException());
Log.Error(new NotImplementedException("test no message - error"));
结果如下:
编辑2:包版本如下:
NLog (4.6.8)
NLog.Web.AspNetCore (4.9.0)
Microsoft.ApplicationInsights.AspNetCore (2.8.2)
Microsoft.ApplicationInsights.NLogTarget (2.11.0)
编辑 3:更多代码:
我们的服务接口层使用此代码。它实现了由 Service Stack 提供的 Service 类之外的东西。通过如上所述定义 LogFactory,我们可以将其传递给我们的服务层。
此服务接口托管在位于同一解决方案下的单独项目中(我们称之为 Api.ServiceInterface)。
AppServiceBase.cs
public abstract class AppServiceBase : Service
{
protected ILog Log { get; set; }
protected ICacheClient CacheClient { get; set; }
protected AppServiceBase()
{
Log = LogManager.GetLogger(GetType());
}
public AppServiceBase(ICacheClient cacheClient) : this()
{
CacheClient = cacheClient;
}
public UserSession UserSession => this.GetSession() as UserSession;
}
HelloService.cs(从 AppServiceBase 扩展的服务,因此可以直接调用上面 AppServiceBase 中的记录器)。
public class HelloService : AppServiceBase
{
public object Any(Hello request)
{
Log.Fatal("test no message - fatal 1", new NotImplementedException());
Log.Error(new NotImplementedException("test no message - error 1"));
return new HelloResponse { Result = $"Hola, {request.Name}!" };
}
}
我们使用以下 URL 调用此函数:
它所做的只是返回一个文本,上面写着“你好,名字!”
很遗憾,我无法附加调试器 - 无论出于何种原因,我都无法让它到达断点。
我不知道我是否也需要在 Api.ServiceInterface 项目上拥有相同的库。请注意,Api.ServiceInterface 是一个类库类型的项目,在 .NET Standard 2.0 上运行。
【问题讨论】:
-
这里
ILog和LogManager的命名空间是什么? -
认为您应该在github.com/microsoft/ApplicationInsights-dotnet 创建一个新问题。 Logging-Frameworks 应该在哪里分配 ExceptionTelemetry.Message-property。另见github.com/microsoft/ApplicationInsights-dotnet/blob/…
-
您的
ILog似乎很特别。 NLog 非常喜欢将异常对象作为第一个参数。不是此处显示的第二个参数。 -
@julian-wen-hsi-lee 已修复 NLog Application-Insights Target,因此它现在在“消息”中生成异常输出。见版本。 2.12.0nuget.org/packages/Microsoft.ApplicationInsights.NLogTarget
标签: azure .net-core servicestack azure-application-insights nlog