Skip to content

Commit b96829e

Browse files
committed
fix: 优化日志跟踪上下文方法
1 parent e85aaf3 commit b96829e

File tree

8 files changed

+120
-37
lines changed

8 files changed

+120
-37
lines changed

framework/src/Bing.AspNetCore/Bing/AspNetCore/Logs/AspNetCoreLogContext.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,10 @@ public class AspNetCoreLogContext : LogContext
3131
/// <param name="scopedDictionary">作用域字典</param>
3232
/// <param name="webClientInfoProvider">Web客户端信息提供程序</param>
3333
/// <param name="httpContextAccessor">Http上下文访问器</param>
34-
public AspNetCoreLogContext(ScopedDictionary scopedDictionary
35-
, IHttpContextAccessor httpContextAccessor
36-
, IWebClientInfoProvider webClientInfoProvider)
34+
public AspNetCoreLogContext(
35+
ScopedDictionary scopedDictionary,
36+
IHttpContextAccessor httpContextAccessor,
37+
IWebClientInfoProvider webClientInfoProvider)
3738
: base(scopedDictionary)
3839
{
3940
HttpContextAccessor = httpContextAccessor;

framework/src/Bing.AspNetCore/Bing/AspNetCore/Logs/RequestLogMiddleware.cs

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
using System.IO;
44
using System.Threading.Tasks;
55
using Bing.Logs;
6+
using Bing.Logs.Core;
67
using Microsoft.AspNetCore.Http;
8+
using Microsoft.Extensions.DependencyInjection;
79

810
namespace Bing.AspNetCore.Logs
911
{
@@ -76,19 +78,23 @@ private async Task WriteLogAsync(HttpContext context, Stopwatch stopwatch)
7678
context.Response.Body.Seek(0, SeekOrigin.Begin);
7779
return;
7880
}
79-
var log = Log.GetLog(this).Caption("请求日志中间件");
80-
log.Content(new Dictionary<string, string>()
81-
{
82-
{"请求方法", context.Request.Method},
81+
82+
var log = context?.RequestServices?.GetService<ILog>() ?? NullLog.Instance;
83+
log
84+
.Class(this.GetType().FullName)
85+
.Caption("请求日志中间件")
86+
.Content(new Dictionary<string, string>
8387
{
84-
"请求地址",
85-
$"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}"
86-
},
87-
{"IP", context.Connection.RemoteIpAddress.ToString()},
88-
{"请求耗时", $"{stopwatch.Elapsed.TotalMilliseconds} 毫秒"},
89-
{"请求内容", await FormatRequestAsync(context.Request)},
90-
{"响应内容", await FormatResponseAsync(context.Response)}
91-
});
88+
{ "请求方法", context.Request.Method },
89+
{
90+
"请求地址",
91+
$"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}"
92+
},
93+
{ "IP", context.Connection.RemoteIpAddress.ToString() },
94+
{ "请求耗时", $"{stopwatch.Elapsed.TotalMilliseconds} 毫秒" },
95+
{ "请求内容", await FormatRequestAsync(context.Request) },
96+
{ "响应内容", await FormatResponseAsync(context.Response) }
97+
});
9298
log.Trace();
9399
}
94100

framework/src/Bing.Logs/Bing/Logs/Formats/ContentFormat.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ public string Format(ILogContent logContent)
2828
/// <summary>
2929
/// 内容格式化器实例
3030
/// </summary>
31+
// ReSharper disable once InconsistentNaming
3132
public static readonly ILogFormat Instance = new ContentFormat();
3233

3334
/// <summary>

framework/src/Bing.Logs/Bing/Logs/Log.cs

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
using System;
2-
using System.Linq;
1+
using System.Linq;
32
using Bing.DependencyInjection;
43
using Bing.Logs.Abstractions;
54
using Bing.Logs.Contents;
@@ -32,7 +31,11 @@ public class Log : LogBase<LogContent>
3231
/// <param name="context">日志上下文</param>
3332
/// <param name="format">日志格式器</param>
3433
/// <param name="currentUser">当前用户</param>
35-
public Log(ILogProviderFactory providerFactory, ILogContext context, ILogFormat format, ICurrentUser currentUser)
34+
public Log(
35+
ILogProviderFactory providerFactory,
36+
ILogContext context,
37+
ILogFormat format,
38+
ICurrentUser currentUser)
3639
: base(providerFactory.Create("", format), context, currentUser)
3740
{
3841
}
@@ -44,7 +47,11 @@ public Log(ILogProviderFactory providerFactory, ILogContext context, ILogFormat
4447
/// <param name="context">日志上下文</param>
4548
/// <param name="currentUser">当前用户</param>
4649
/// <param name="class">类名</param>
47-
public Log(ILogProvider provider, ILogContext context, ICurrentUser currentUser, string @class)
50+
public Log(
51+
ILogProvider provider,
52+
ILogContext context,
53+
ICurrentUser currentUser,
54+
string @class)
4855
: base(provider, context, currentUser) => _class = @class;
4956

5057
/// <summary>
@@ -55,7 +62,12 @@ public Log(ILogProvider provider, ILogContext context, ICurrentUser currentUser,
5562
/// <param name="context">日志上下文</param>
5663
/// <param name="currentUser">当前用户</param>
5764
/// <param name="class">类名</param>
58-
public Log(string name, ILogProvider provider, ILogContext context, ICurrentUser currentUser, string @class)
65+
public Log(
66+
string name,
67+
ILogProvider provider,
68+
ILogContext context,
69+
ICurrentUser currentUser,
70+
string @class)
5971
: base(name, provider, context, currentUser) => _class = @class;
6072

6173
/// <summary>

framework/src/Bing.Logs/Bing/Logs/LogBase.cs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,10 @@ public abstract class LogBase<TContent> : ILog where TContent : class, ILogConte
6565
/// <param name="provider">日志提供程序</param>
6666
/// <param name="context">日志上下文</param>
6767
/// <param name="currentUser">当前用户</param>
68-
protected LogBase(ILogProvider provider
69-
, ILogContext context
70-
, ICurrentUser currentUser)
68+
protected LogBase(
69+
ILogProvider provider,
70+
ILogContext context,
71+
ICurrentUser currentUser)
7172
{
7273
Provider = provider;
7374
Context = context;
@@ -81,10 +82,11 @@ protected LogBase(ILogProvider provider
8182
/// <param name="provider">日志提供程序</param>
8283
/// <param name="context">日志上下文</param>
8384
/// <param name="currentUser">当前用户</param>
84-
protected LogBase(string name
85-
, ILogProvider provider
86-
, ILogContext context
87-
, ICurrentUser currentUser)
85+
protected LogBase(
86+
string name,
87+
ILogProvider provider,
88+
ILogContext context,
89+
ICurrentUser currentUser)
8890
{
8991
Provider = provider;
9092
Context = context;

framework/src/Bing/Logs/Core/LogContext.cs

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,25 @@ public class LogContext : ILogContext
3434
/// <summary>
3535
/// 日志标识
3636
/// </summary>
37-
public string LogId => $"{TraceId}-{_orderId}";
37+
public string LogId => $"{TraceId}-{GetInfo().GetOrderId()}";
3838

3939
/// <summary>
4040
/// 跟踪号
4141
/// </summary>
4242
public string TraceId => $"{TraceIdContext.Current?.TraceId ?? GetInfo().TraceId}";
4343

44+
///// <summary>
45+
///// 跟踪号
46+
///// </summary>
47+
//public string TraceId
48+
//{
49+
// get
50+
// {
51+
// TraceIdContext.Current ??= new TraceIdContext(string.Empty);
52+
// return TraceIdContext.Current.TraceId;
53+
// }
54+
//}
55+
4456
/// <summary>
4557
/// 计时器
4658
/// </summary>
@@ -90,20 +102,31 @@ public void InitLogId()
90102
var key = "Bing.Logs.LogContext_orderId";
91103
_scopedDictionary[key] = _scopedDictionary.ContainsKey(key) ? ++_orderId : _orderId;
92104
}
105+
106+
///// <summary>
107+
///// 获取日志上下文信息
108+
///// </summary>
109+
//private LogContextInfo GetInfo()
110+
//{
111+
// if (_info != null)
112+
// return _info;
113+
// var key = "Bing.Logs.LogContext";
114+
// _info = _scopedDictionary.ContainsKey(key) ? _scopedDictionary[key] as LogContextInfo : null;
115+
// if (_info != null)
116+
// return _info;
117+
// _info = CreateInfo();
118+
// _scopedDictionary[key] = _info;
119+
// return _info;
120+
//}
121+
93122
/// <summary>
94123
/// 获取日志上下文信息
95124
/// </summary>
96125
private LogContextInfo GetInfo()
97126
{
98-
if (_info != null)
99-
return _info;
100-
var key = "Bing.Logs.LogContext";
101-
_info = _scopedDictionary.ContainsKey(key) ? _scopedDictionary[key] as LogContextInfo : null;
102-
if (_info != null)
103-
return _info;
104-
_info = CreateInfo();
105-
_scopedDictionary[key] = _info;
106-
return _info;
127+
if (LogContextInfo.Current == null)
128+
LogContextInfo.Current = CreateInfo();
129+
return LogContextInfo.Current;
107130
}
108131

109132
/// <summary>

framework/src/Bing/Logs/Internal/LogContextInfo.cs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System.Diagnostics;
2+
using System.Threading;
23

34
namespace Bing.Logs.Internal
45
{
@@ -9,6 +10,11 @@ public class LogContextInfo
910
{
1011
#region 属性
1112

13+
/// <summary>
14+
/// 序号
15+
/// </summary>
16+
private int _orderId;
17+
1218
/// <summary>
1319
/// 跟踪号
1420
/// </summary>
@@ -39,7 +45,31 @@ public class LogContextInfo
3945
/// </summary>
4046
public string Url { get; set; }
4147

48+
/// <summary>
49+
/// 当前日志上下文信息
50+
/// </summary>
51+
// ReSharper disable once InconsistentNaming
52+
private static readonly AsyncLocal<LogContextInfo> _current = new AsyncLocal<LogContextInfo>();
53+
54+
/// <summary>
55+
/// 当前日志上下文信息
56+
/// </summary>
57+
public static LogContextInfo Current
58+
{
59+
get => _current.Value;
60+
set => _current.Value = value;
61+
}
62+
4263
#endregion
4364

65+
/// <summary>
66+
/// 初始化一个<see cref="LogContextInfo"/>类型的实例
67+
/// </summary>
68+
public LogContextInfo() => _orderId = 0;
69+
70+
/// <summary>
71+
/// 获取序号
72+
/// </summary>
73+
public int GetOrderId() => _orderId++;
4474
}
4575
}

modules/admin/src/Bing.Admin/Modules/AppModule.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
using Bing.Domain.Entities.Events;
1010
using Bing.Helpers;
1111
using Bing.Security.Claims;
12+
using Bing.Tracing;
1213
using Microsoft.AspNetCore.Builder;
1314
using Microsoft.AspNetCore.Http;
1415
using Microsoft.AspNetCore.Mvc;
@@ -56,6 +57,12 @@ public override IServiceCollection AddServices(IServiceCollection services)
5657
});
5758
services.AddDomainEventDispatcher();
5859
//services.AddAudit();
60+
// 添加跟踪ID
61+
services.Configure<CorrelationIdOptions>(x =>
62+
{
63+
x.HttpHeaderName = "X-Correlation-Id";
64+
x.SetResponseHeader = true;
65+
});
5966
return services;
6067
}
6168

@@ -66,6 +73,7 @@ public override IServiceCollection AddServices(IServiceCollection services)
6673
public override void UseModule(IApplicationBuilder app)
6774
{
6875
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
76+
app.UseCorrelationId();
6977
app.UseBingExceptionHandling();
7078
// 初始化Http上下文访问器
7179
Web.HttpContextAccessor = app.ApplicationServices.GetService<IHttpContextAccessor>();

0 commit comments

Comments
 (0)