我有一个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注入(请参阅我们的Autofac模块)
我的问题是关联ID;
如何将其进一步传递到我们的应用程序中?
例如,在包含我们的一些业务逻辑的另一个程序集中,我们希望使用对LogManager.GetLogger的调用来获取另一个类型的日志,但由于它来自请求,因此重新使用相同的相关ID ,我们可以把我们的日志消息绑在一起吗?
为清楚起见,我们的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);
}
}
}
答案 0 :(得分:7)
最简单的方法是将其添加到log4net逻辑线程上下文的属性中:
LogicalThreadContext.Properties["CorrelationId"] = request.GetCorrelationId();
请注意,由于这是一个逻辑线程上下文,它将在await
点之间保持不变,即使使用不同的线程来恢复请求也是如此。