Skip to content

Commit a2ec48a

Browse files
committed
refactor: 重构日志上下文
1 parent 0650716 commit a2ec48a

File tree

16 files changed

+146
-121
lines changed

16 files changed

+146
-121
lines changed

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

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,11 @@ public class AspNetCoreLogContext : LogContext
2828
/// <summary>
2929
/// 初始化一个<see cref="AspNetCoreLogContext"/>类型的实例
3030
/// </summary>
31-
/// <param name="scopedDictionary">作用域字典</param>
3231
/// <param name="webClientInfoProvider">Web客户端信息提供程序</param>
3332
/// <param name="httpContextAccessor">Http上下文访问器</param>
3433
public AspNetCoreLogContext(
35-
ScopedDictionary scopedDictionary,
36-
IHttpContextAccessor httpContextAccessor,
34+
IHttpContextAccessor httpContextAccessor,
3735
IWebClientInfoProvider webClientInfoProvider)
38-
: base(scopedDictionary)
3936
{
4037
HttpContextAccessor = httpContextAccessor;
4138
WebClientInfoProvider = webClientInfoProvider;
@@ -50,9 +47,10 @@ protected override LogContextInfo CreateInfo()
5047

5148
logContextInfo.Ip = WebClientInfoProvider.ClientIpAddress;
5249
logContextInfo.Browser = WebClientInfoProvider.ClientIpAddress;
53-
5450
logContextInfo.Url = HttpContextAccessor.HttpContext?.Request?.GetDisplayUrl();
55-
51+
logContextInfo.IsWebEnv = HttpContextAccessor.HttpContext?.Request != null;
52+
if (logContextInfo.IsWebEnv)
53+
logContextInfo.TraceId = TraceId;
5654
return logContextInfo;
5755
}
5856

@@ -65,7 +63,7 @@ protected override string GetTraceId()
6563
if (!string.IsNullOrWhiteSpace(correlationId))
6664
return correlationId;
6765
var traceId = HttpContextAccessor.HttpContext?.TraceIdentifier;
68-
return string.IsNullOrWhiteSpace(traceId) ? Guid.NewGuid().ToString() : Guid.TryParse(traceId, out _) ? traceId : Guid.NewGuid().ToString();
66+
return string.IsNullOrWhiteSpace(traceId) ? Guid.NewGuid().ToString("N") : Guid.TryParse(traceId, out _) ? traceId : Guid.NewGuid().ToString("N");
6967
}
7068
}
7169
}

framework/src/Bing.Datas.Dapper/Bing/Data/Sql/Queries/SqlQuery.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using Bing.Data.Sql.Diagnostics;
77
using Bing.Helpers;
88
using Bing.Logs;
9+
using Bing.Logs.Internal;
910
using Dapper;
1011

1112
namespace Bing.Data.Sql.Queries
@@ -264,7 +265,7 @@ protected override void WriteTraceLog(string sql, IReadOnlyDictionary<string, ob
264265
if (IsEnabled(log) == false)
265266
return;
266267
log.Class(GetType().FullName)
267-
.Caption("SqlQuery查询调试:")
268+
.Caption($"SqlQuery查询调试: {sql}")
268269
.Sql("原始Sql:")
269270
.Sql($"{sql}{Common.Line}")
270271
.Sql("调试Sql:")

framework/src/Bing.Datas.EntityFramework/Core/UnitOfWorkBase.cs

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
using Bing.Exceptions;
2121
using Bing.Extensions;
2222
using Bing.Logs;
23+
using Bing.Logs.Core;
2324
using Bing.Uow;
2425
using Bing.Users;
2526
using Microsoft.EntityFrameworkCore;
@@ -68,6 +69,11 @@ public abstract class UnitOfWorkBase : DbContext, IUnitOfWork, IDatabase, IEntit
6869
[Autowired]
6970
public virtual ILazyServiceProvider LazyServiceProvider { get; set; }
7071

72+
/// <summary>
73+
/// 日志
74+
/// </summary>
75+
public ILog Log => LazyServiceProvider.LazyGetService<ILog>() ?? NullLog.Instance;
76+
7177
/// <summary>
7278
/// 当前用户
7379
/// </summary>
@@ -158,7 +164,7 @@ protected virtual string GetUserName()
158164
protected void EnableLog(DbContextOptionsBuilder builder)
159165
{
160166
ConfiguringIgnoreEvent(builder);
161-
var log = GetLog();
167+
var log = Log;
162168
if (IsEnabled(log) == false)
163169
return;
164170
builder.EnableSensitiveDataLogging();
@@ -170,6 +176,7 @@ protected void EnableLog(DbContextOptionsBuilder builder)
170176
/// 配置忽略事件
171177
/// </summary>
172178
/// <param name="builder">配置事件</param>
179+
/// <remarks>参考:https://docs.microsoft.com/zh-cn/ef/core/logging-events-diagnostics </remarks>
173180
protected virtual void ConfiguringIgnoreEvent(DbContextOptionsBuilder builder)
174181
{
175182
builder.ConfigureWarnings(x => x.Ignore(
@@ -196,21 +203,6 @@ protected virtual void ConfiguringIgnoreEvent(DbContextOptionsBuilder builder)
196203
));
197204
}
198205

199-
/// <summary>
200-
/// 获取日志操作
201-
/// </summary>
202-
protected virtual ILog GetLog()
203-
{
204-
try
205-
{
206-
return Log.GetLog(EfLog.TraceLogName);
207-
}
208-
catch
209-
{
210-
return Log.Null;
211-
}
212-
}
213-
214206
/// <summary>
215207
/// 是否启用EF日志
216208
/// </summary>

framework/src/Bing.Datas.EntityFramework/Logs/EfLog.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,16 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except
3838
Func<TState, Exception, string> formatter)
3939
{
4040
var config = GetConfig();
41-
var log = Bing.Logs.Log.GetLog(TraceLogName);
41+
var log = GetUnitOfWork()?.Log;
42+
if (log == null)
43+
return;
4244
if (IsEnabled(eventId, config, exception) == false)
4345
return;
4446
if (!string.IsNullOrWhiteSpace(GetUnitOfWork().TraceId))
4547
log.Tag(GetUnitOfWork()?.TraceId);
48+
log.Tag(TraceLogName);
4649
log
47-
.Caption("执行EF操作:")
50+
.Caption($"执行EF操作:{formatter(state, exception)}")
4851
.Content($"工作单元跟踪号:{GetUnitOfWork()?.TraceId}")
4952
.Content($"事件ID:{eventId.Id}")
5053
.Content($"事件名称:{eventId.Name}");

framework/src/Bing.Events/Cap/MessageEventBus.cs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,24 @@ public class MessageEventBus : IMessageEventBus
2525
/// </summary>
2626
public ITransactionActionManager TransactionActionManager { get; set; }
2727

28+
/// <summary>
29+
/// 日志操作
30+
/// </summary>
31+
protected ILog Log { get; set; }
32+
2833
/// <summary>
2934
/// 初始化一个<see cref="MessageEventBus"/>类型的实例
3035
/// </summary>
3136
/// <param name="publisher">事件发布器</param>
3237
/// <param name="transactionActionManager">事务操作管理器</param>
33-
public MessageEventBus(ICapPublisher publisher, ITransactionActionManager transactionActionManager)
38+
/// <param name="log">日志操作</param>
39+
public MessageEventBus(ICapPublisher publisher,
40+
ITransactionActionManager transactionActionManager,
41+
ILog log)
3442
{
3543
Publisher = publisher ?? throw new ArgumentNullException(nameof(publisher));
3644
TransactionActionManager = transactionActionManager ?? throw new ArgumentNullException(nameof(transactionActionManager));
45+
Log = log;
3746
}
3847

3948
/// <summary>
@@ -86,7 +95,7 @@ private async Task InternalPublishAsync(string name, object data, IDictionary<st
8695
/// <param name="callback">回调名称</param>
8796
private void WriteLog(string name, object data, string callback)
8897
{
89-
var log = Log.GetLog(this);
98+
var log = Log;
9099
if (log.IsDebugEnabled == false)
91100
return;
92101
log.Tag(name)

framework/src/Bing.Logs.Exceptionless/Bing/Logs/Exceptionless/ExceptionlessProvider.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System;
1+
using System.Diagnostics;
22
using System.Linq;
33
using Bing.Configuration;
44
using Bing.Extensions;
@@ -72,6 +72,7 @@ public void WriteLog(LogLevel level, ILogContent content)
7272
// 致命错误
7373
if (level == LogLevel.Fatal || level == LogLevel.Error)
7474
builder.MarkAsCritical();
75+
Debug.WriteLine($"【Exceptionless】Thread: {content.ThreadId}, LogId: {content.LogId}, TraceId: {content.TraceId}, Message: {GetMessage(content)}, Tags: [{content.Tags.ExpandAndToString()}]");
7576
SetUser(content);
7677
SetSource(builder, content);
7778
SetReferenceId(builder, content);

framework/src/Bing.Logs/Bing/Logs/Aspects/LogAttributeBase.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using AspectCore.DynamicProxy.Parameters;
44
using Bing.Aspects.Base;
55
using Bing.Extensions;
6+
using Microsoft.Extensions.DependencyInjection;
67

78
namespace Bing.Logs.Aspects
89
{
@@ -17,7 +18,7 @@ public abstract class LogAttributeBase : InterceptorBase
1718
public override async Task Invoke(AspectContext context, AspectDelegate next)
1819
{
1920
var methodName = GetMethodName(context);
20-
var log = Log.GetLog(methodName);
21+
var log = context.ServiceProvider.GetService<ILog>();
2122
if (!Enabled(log))
2223
return;
2324
ExecuteBefore(log, context, methodName);

framework/src/Bing.Logs/Bing/Logs/Extensions/LogExtensions.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ public static ILog BusinessId(this ILog log, string businessId)
2525
{
2626
return log.Set<LogContent>(content =>
2727
{
28-
if (string.IsNullOrWhiteSpace(content.BusinessId) == false)
28+
if (string.IsNullOrWhiteSpace(content.BusinessId) == false)
2929
content.BusinessId += ",";
3030
content.BusinessId += businessId;
3131
});
@@ -90,7 +90,7 @@ public static ILog Params(this ILog log, IDictionary<string, object> dictionary)
9090
{
9191
if (dictionary == null || dictionary.Count == 0)
9292
return log;
93-
foreach (var item in dictionary)
93+
foreach (var item in dictionary)
9494
Params(log, item.Key, item.Value.SafeString());
9595
return log;
9696
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -245,10 +245,10 @@ public void Fatal(string message)
245245
/// <param name="content">日志内容</param>
246246
protected virtual void Init(TContent content)
247247
{
248-
Context.InitLogId();
249248
content.LogName = Provider.LogName;
250249
content.TraceId = Context.TraceId;
251-
content.LogId = Context.LogId;
250+
if (string.IsNullOrWhiteSpace(content.LogId))
251+
content.LogId = Context.LogId;
252252
content.OperationTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
253253
content.Duration = Context.Stopwatch.Elapsed.Description();
254254
content.Ip = Context.Ip;

framework/src/Bing/Logs/Abstractions/ILogContext.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,9 @@ public interface ILogContext
4444
/// </summary>
4545
string Url { get; }
4646

47-
/// <summary>
48-
/// 初始化日志标识
49-
/// </summary>
50-
void InitLogId();
47+
///// <summary>
48+
///// 初始化日志标识
49+
///// </summary>
50+
//void InitLogId();
5151
}
5252
}

0 commit comments

Comments
 (0)