我一直Microsoft.Extensions.Logging
在使用 ASP.NET Core 8 Web API 项目日志记录实现,最近决定切换到 Serilog。迁移过程很成功,除了更新Microsoft.Extensions.Logging
.
尝试更新时,我遇到一条错误消息,其中指出:
“ILogger”不包含“BeginScope”的定义,并且找不到接受“ILogger”类型的第一个参数的可访问扩展方法“BeginScope”。
我尝试自行解决该问题,但到目前为止尚未找到解决方案。我希望这里有人可以阐明可能导致此错误的原因以及如何解决它。
任何有关在 ASP.NET Core 8 Web API 项目中从 Microsoft.Extensions.Logging 迁移到 Serilog 时如何正确更新“BeginScope”功能的指导将不胜感激。
代码
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Serilog;
using Demo.Exceptions;
using Demo.GuardClauses;
namespace Demo.Middlewares;
internal class GlobalExceptionHandler(ILogger logger, IWebHostEnvironment env) : IExceptionHandler
{
private readonly ILogger _logger = logger.ForContext<GlobalExceptionHandler>();
private readonly IWebHostEnvironment _env = env.IsNotNull();
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
var errorResult = exception switch
{
FluentValidation.ValidationException fluentException => ExceptionDetails.HandleFluentValidationException(fluentException),
UnauthorizedException unauthorizedException => ExceptionDetails.HandleUnauthorizedException(unauthorizedException),
ForbiddenException forbiddenException => ExceptionDetails.HandleForbiddenException(forbiddenException),
NotFoundException notFoundException => ExceptionDetails.HandleNotFoundException(notFoundException),
TimeOutException timeOutException => ExceptionDetails.HandleTimeOutException(timeOutException),
_ => ExceptionDetails.HandleDefaultException(exception),
};
var errorLogLevel = exception switch
{
FluentValidation.ValidationException or UnauthorizedException => LogEventLevel.Warning,
_ => LogEventLevel.Error
};
LogErrorMessage(errorLogLevel, exception, errorResult);
var response = httpContext.Response;
if (!response.HasStarted)
{
response.ContentType = "application/problem+json";
response.StatusCode = errorResult.Status!.Value;
await response.WriteAsJsonAsync(errorResult, cancellationToken).ConfigureAwait(false);
}
else
{
_logger.Warning("Can't write error response. Response has already started.");
}
return true;
}
private void LogErrorMessage1(LogEventLevel errorLogLevel, Exception exception, ExceptionDetails details)
{
var properties = new Dictionary<string, object>
{
{
"TraceId",
details.TraceId
}
};
if (details.Errors != null)
{
properties.Add("Errors", details.Errors);
}
if (_env.IsDevelopment())
{
properties.Add("StackTrace", exception.StackTrace!.Trim());
}
using (_logger.BeginScope(properties))
{
_logger.Write(errorLogLevel, "{title} | {details} | {traceId}", details.Title, details.Detail, details.TraceId);
}
}
}
任何人都可以通过提供指导来帮助我吗?任何帮助将不胜感激。
Serilog的具体类似功能是
LogContext
:您需要在配置中启用它:
并使用
LogContext.PushProperty
: