gpt4 book ai didi

logging - 将 log4net 与 WebApi 结合使用 - 在整个实例中保持相同的相关 ID

转载 作者:行者123 更新时间:2023-12-01 16:19:14 25 4
gpt4 key购买 nike

我有一个 LoggingHandler 类,用作消息处理程序来记录(使用 log4net)请求和对我的 WebApi 的响应

public class LoggingMessageHandler : DelegatingHandler
{
public ILogManager LogManager { get; set; }

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
var controllerType = GlobalConfiguration.Configuration.Services
.GetHttpControllerSelector()
.SelectController(request)
.ControllerType;

var requestInfo = string.Format("{0} {1}", request.Method, request.RequestUri);
var correlationId = request.GetCorrelationId().ToString();

var requestMessage = await request.Content.ReadAsStringAsync();

await LogIncommingMessageAsync(controllerType, correlationId, requestInfo, requestMessage.Replace("\r\n", ""));

var response = await base.SendAsync(request, cancellationToken);

string responseMessage;

if (response.IsSuccessStatusCode)
responseMessage = await response.Content.ReadAsStringAsync();
else
responseMessage = response.ReasonPhrase;

await OutgoingMessageAsync(controllerType, correlationId, requestInfo, responseMessage);

return response;
}

protected async Task LogIncommingMessageAsync(Type type, string correlationId, string requestInfo, string body)
{
var logger = LogManager.GetLogger(type);
await Task.Run(() => logger.Debug("{0} {1} - API Request: \r\n{2}", correlationId, requestInfo, body));
}

protected async Task OutgoingMessageAsync(Type type, string correlationId, string requestInfo, string body)
{
var logger = LogManager.GetLogger(type);
await Task.Run(() => logger.Debug("{0} {1} - API Response: \r\n{2}", correlationId, requestInfo, body));
}
}

ILogManager 通过 Autofac 注入(inject)(请参阅我们的 Autofac 模块)

我的问题是相关 ID;

如何将其进一步传递到我们的应用程序中?

例如,在另一个包含一些业务逻辑的程序集中,我们希望使用对 LogManager.GetLogger 的调用来获取另一种类型的日志,但由于它源自请求,因此请重新使用相同的相关 ID ,这样我们就可以将日志消息绑定(bind)在一起?

为了清楚起见,我们的 Autofac 模块如下所示:

public class LoggingAutofacModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<LogManager>().As<ILogManager>().InstancePerApiRequest();
}

protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration)
{
registration.Preparing += OnComponentPreparing;

var implementationType = registration.Activator.LimitType;
var injectors = BuildInjectors(implementationType).ToArray();

if (!injectors.Any())
return;

registration.Activated += (s, e) =>
{
foreach (var injector in injectors)
injector(e.Context, e.Instance);
};
}

private static void OnComponentPreparing(object sender, PreparingEventArgs e)
{
var t = e.Component.Activator.LimitType;
e.Parameters =
e.Parameters.Union(new[] { new ResolvedParameter((p, i) => p.ParameterType == typeof(ILogger), (p, i) => e.Context.Resolve<ILogManager>().GetLogger(t)) });
}

private static IEnumerable<Action<IComponentContext, object>> BuildInjectors(Type componentType)
{
var properties =
componentType.GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.PropertyType == typeof(ILogger) && !p.GetIndexParameters().Any())
.Where(p =>
{
var accessors = p.GetAccessors(false);
return accessors.Length != -1 || accessors[0].ReturnType == typeof(void);
});

foreach (var propertyInfo in properties)
{
var propInfo = propertyInfo;
yield return (context, instance) => propInfo.SetValue(instance, context.Resolve<ILogManager>().GetLogger(componentType), null);
}
}
}

最佳答案

最简单的方法是将其添加到 log4net 逻辑线程上下文的属性中:

LogicalThreadContext.Properties["CorrelationId"] = request.GetCorrelationId();

请注意,由于这是一个逻辑线程上下文,因此即使使用不同的线程来恢复请求,它也会在await点上持续存在。

关于logging - 将 log4net 与 WebApi 结合使用 - 在整个实例中保持相同的相关 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21333629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com