Skip to content

Commit

Permalink
Merge pull request #57 from bing-framework/dev_3.1
Browse files Browse the repository at this point in the history
publish: 发布 2.2.2
  • Loading branch information
jianxuanbing authored Feb 18, 2022
2 parents e4f425e + ffb3eef commit e1728e5
Show file tree
Hide file tree
Showing 26 changed files with 364 additions and 170 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,11 @@ public class AspNetCoreLogContext : LogContext
/// <summary>
/// 初始化一个<see cref="AspNetCoreLogContext"/>类型的实例
/// </summary>
/// <param name="scopedDictionary">作用域字典</param>
/// <param name="webClientInfoProvider">Web客户端信息提供程序</param>
/// <param name="httpContextAccessor">Http上下文访问器</param>
public AspNetCoreLogContext(
ScopedDictionary scopedDictionary,
IHttpContextAccessor httpContextAccessor,
IHttpContextAccessor httpContextAccessor,
IWebClientInfoProvider webClientInfoProvider)
: base(scopedDictionary)
{
HttpContextAccessor = httpContextAccessor;
WebClientInfoProvider = webClientInfoProvider;
Expand All @@ -50,9 +47,10 @@ protected override LogContextInfo CreateInfo()

logContextInfo.Ip = WebClientInfoProvider.ClientIpAddress;
logContextInfo.Browser = WebClientInfoProvider.ClientIpAddress;

logContextInfo.Url = HttpContextAccessor.HttpContext?.Request?.GetDisplayUrl();

logContextInfo.IsWebEnv = HttpContextAccessor.HttpContext?.Request != null;
if (logContextInfo.IsWebEnv)
logContextInfo.TraceId = TraceId;
return logContextInfo;
}

Expand All @@ -65,7 +63,7 @@ protected override string GetTraceId()
if (!string.IsNullOrWhiteSpace(correlationId))
return correlationId;
var traceId = HttpContextAccessor.HttpContext?.TraceIdentifier;
return string.IsNullOrWhiteSpace(traceId) ? Guid.NewGuid().ToString() : Guid.TryParse(traceId, out _) ? traceId : Guid.NewGuid().ToString();
return string.IsNullOrWhiteSpace(traceId) ? Guid.NewGuid().ToString("N") : Guid.TryParse(traceId, out _) ? traceId : Guid.NewGuid().ToString("N");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,6 @@ public DateSegmentCondition(Expression<Func<TEntity, TProperty>> propertyExpress
{
}

/// <summary>
/// 最小值是否大于最大值
/// </summary>
/// <param name="min">最小值</param>
/// <param name="max">最大值</param>
protected override bool IsMinGreaterMax(DateTime? min, DateTime? max) => min > max;

/// <summary>
/// 获取最小值表达式
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Bing.Data.Sql.Diagnostics;
using Bing.Helpers;
using Bing.Logs;
using Bing.Logs.Internal;
using Dapper;

namespace Bing.Data.Sql.Queries
Expand Down Expand Up @@ -264,7 +265,7 @@ protected override void WriteTraceLog(string sql, IReadOnlyDictionary<string, ob
if (IsEnabled(log) == false)
return;
log.Class(GetType().FullName)
.Caption("SqlQuery查询调试:")
.Caption($"SqlQuery查询调试: {sql}")
.Sql("原始Sql:")
.Sql($"{sql}{Common.Line}")
.Sql("调试Sql:")
Expand Down
24 changes: 8 additions & 16 deletions framework/src/Bing.Datas.EntityFramework/Core/UnitOfWorkBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
using Bing.Exceptions;
using Bing.Extensions;
using Bing.Logs;
using Bing.Logs.Core;
using Bing.Uow;
using Bing.Users;
using Microsoft.EntityFrameworkCore;
Expand Down Expand Up @@ -68,6 +69,11 @@ public abstract class UnitOfWorkBase : DbContext, IUnitOfWork, IDatabase, IEntit
[Autowired]
public virtual ILazyServiceProvider LazyServiceProvider { get; set; }

/// <summary>
/// 日志
/// </summary>
public ILog Log => LazyServiceProvider.LazyGetService<ILog>() ?? NullLog.Instance;

/// <summary>
/// 当前用户
/// </summary>
Expand Down Expand Up @@ -158,7 +164,7 @@ protected virtual string GetUserName()
protected void EnableLog(DbContextOptionsBuilder builder)
{
ConfiguringIgnoreEvent(builder);
var log = GetLog();
var log = Log;
if (IsEnabled(log) == false)
return;
builder.EnableSensitiveDataLogging();
Expand All @@ -170,6 +176,7 @@ protected void EnableLog(DbContextOptionsBuilder builder)
/// 配置忽略事件
/// </summary>
/// <param name="builder">配置事件</param>
/// <remarks>参考:https://docs.microsoft.com/zh-cn/ef/core/logging-events-diagnostics </remarks>
protected virtual void ConfiguringIgnoreEvent(DbContextOptionsBuilder builder)
{
builder.ConfigureWarnings(x => x.Ignore(
Expand All @@ -196,21 +203,6 @@ protected virtual void ConfiguringIgnoreEvent(DbContextOptionsBuilder builder)
));
}

/// <summary>
/// 获取日志操作
/// </summary>
protected virtual ILog GetLog()
{
try
{
return Log.GetLog(EfLog.TraceLogName);
}
catch
{
return Log.Null;
}
}

/// <summary>
/// 是否启用EF日志
/// </summary>
Expand Down
7 changes: 5 additions & 2 deletions framework/src/Bing.Datas.EntityFramework/Logs/EfLog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,16 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except
Func<TState, Exception, string> formatter)
{
var config = GetConfig();
var log = Bing.Logs.Log.GetLog(TraceLogName);
var log = GetUnitOfWork()?.Log;
if (log == null)
return;
if (IsEnabled(eventId, config, exception) == false)
return;
if (!string.IsNullOrWhiteSpace(GetUnitOfWork().TraceId))
log.Tag(GetUnitOfWork()?.TraceId);
log.Tag(TraceLogName);
log
.Caption("执行EF操作:")
.Caption($"执行EF操作:{formatter(state, exception)}")
.Content($"工作单元跟踪号:{GetUnitOfWork()?.TraceId}")
.Content($"事件ID:{eventId.Id}")
.Content($"事件名称:{eventId.Name}");
Expand Down
13 changes: 11 additions & 2 deletions framework/src/Bing.Events/Cap/MessageEventBus.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,24 @@ public class MessageEventBus : IMessageEventBus
/// </summary>
public ITransactionActionManager TransactionActionManager { get; set; }

/// <summary>
/// 日志操作
/// </summary>
protected ILog Log { get; set; }

/// <summary>
/// 初始化一个<see cref="MessageEventBus"/>类型的实例
/// </summary>
/// <param name="publisher">事件发布器</param>
/// <param name="transactionActionManager">事务操作管理器</param>
public MessageEventBus(ICapPublisher publisher, ITransactionActionManager transactionActionManager)
/// <param name="log">日志操作</param>
public MessageEventBus(ICapPublisher publisher,
ITransactionActionManager transactionActionManager,
ILog log)
{
Publisher = publisher ?? throw new ArgumentNullException(nameof(publisher));
TransactionActionManager = transactionActionManager ?? throw new ArgumentNullException(nameof(transactionActionManager));
Log = log;
}

/// <summary>
Expand Down Expand Up @@ -86,7 +95,7 @@ private async Task InternalPublishAsync(string name, object data, IDictionary<st
/// <param name="callback">回调名称</param>
private void WriteLog(string name, object data, string callback)
{
var log = Log.GetLog(this);
var log = Log;
if (log.IsDebugEnabled == false)
return;
log.Tag(name)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System.Diagnostics;
using System.Linq;
using Bing.Configuration;
using Bing.Extensions;
Expand Down Expand Up @@ -72,6 +72,7 @@ public void WriteLog(LogLevel level, ILogContent content)
// 致命错误
if (level == LogLevel.Fatal || level == LogLevel.Error)
builder.MarkAsCritical();
Debug.WriteLine($"【Exceptionless】Thread: {content.ThreadId}, LogId: {content.LogId}, TraceId: {content.TraceId}, Message: {GetMessage(content)}, Tags: [{content.Tags.ExpandAndToString()}]");
SetUser(content);
SetSource(builder, content);
SetReferenceId(builder, content);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using AspectCore.DynamicProxy.Parameters;
using Bing.Aspects.Base;
using Bing.Extensions;
using Microsoft.Extensions.DependencyInjection;

namespace Bing.Logs.Aspects
{
Expand All @@ -17,7 +18,7 @@ public abstract class LogAttributeBase : InterceptorBase
public override async Task Invoke(AspectContext context, AspectDelegate next)
{
var methodName = GetMethodName(context);
var log = Log.GetLog(methodName);
var log = context.ServiceProvider.GetService<ILog>();
if (!Enabled(log))
return;
ExecuteBefore(log, context, methodName);
Expand Down
4 changes: 2 additions & 2 deletions framework/src/Bing.Logs/Bing/Logs/Extensions/LogExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public static ILog BusinessId(this ILog log, string businessId)
{
return log.Set<LogContent>(content =>
{
if (string.IsNullOrWhiteSpace(content.BusinessId) == false)
if (string.IsNullOrWhiteSpace(content.BusinessId) == false)
content.BusinessId += ",";
content.BusinessId += businessId;
});
Expand Down Expand Up @@ -90,7 +90,7 @@ public static ILog Params(this ILog log, IDictionary<string, object> dictionary)
{
if (dictionary == null || dictionary.Count == 0)
return log;
foreach (var item in dictionary)
foreach (var item in dictionary)
Params(log, item.Key, item.Value.SafeString());
return log;
}
Expand Down
4 changes: 2 additions & 2 deletions framework/src/Bing.Logs/Bing/Logs/LogBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -245,10 +245,10 @@ public void Fatal(string message)
/// <param name="content">日志内容</param>
protected virtual void Init(TContent content)
{
Context.InitLogId();
content.LogName = Provider.LogName;
content.TraceId = Context.TraceId;
content.LogId = Context.LogId;
if (string.IsNullOrWhiteSpace(content.LogId))
content.LogId = Context.LogId;
content.OperationTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
content.Duration = Context.Stopwatch.Elapsed.Description();
content.Ip = Context.Ip;
Expand Down
81 changes: 81 additions & 0 deletions framework/src/Bing/Bing/Logging/LoggerExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
using System;
using Microsoft.Extensions.Logging;

namespace Bing.Logging
{
/// <summary>
/// 日志(<see cref="ILogger"/>) 扩展
/// </summary>
public static class LoggerExtensions
{
/// <summary>
/// 基于日志级别输出日志
/// </summary>
/// <param name="logger">日志</param>
/// <param name="logLevel">日志级别</param>
/// <param name="message">消息</param>
/// <param name="args">参数</param>
public static void LogWithLevel(this ILogger logger, LogLevel logLevel, string message, params object[] args)
{
switch (logLevel)
{
case LogLevel.Trace:
logger.LogTrace(message, args);
break;
case LogLevel.Debug:
logger.LogDebug(message, args);
break;
case LogLevel.Information:
logger.LogInformation(message, args);
break;
case LogLevel.Warning:
logger.LogWarning(message, args);
break;
case LogLevel.Error:
logger.LogError(message, args);
break;
case LogLevel.Critical:
logger.LogCritical(message, args);
break;
default:
logger.LogDebug(message, args);
break;
}
}

/// <summary>
/// 基于日志级别输出日志
/// </summary>
/// <param name="logger">日志</param>
/// <param name="logLevel">日志级别</param>
/// <param name="message">消息</param>
/// <param name="exception">异常</param>
public static void LogWithLevel(this ILogger logger, LogLevel logLevel, string message, Exception exception)
{
switch (logLevel)
{
case LogLevel.Trace:
logger.LogTrace(exception, message);
break;
case LogLevel.Debug:
logger.LogDebug(exception, message);
break;
case LogLevel.Information:
logger.LogInformation(exception, message);
break;
case LogLevel.Warning:
logger.LogWarning(exception, message);
break;
case LogLevel.Error:
logger.LogError(exception, message);
break;
case LogLevel.Critical:
logger.LogCritical(exception, message);
break;
default:
logger.LogDebug(exception, message);
break;
}
}
}
}
8 changes: 4 additions & 4 deletions framework/src/Bing/Logs/Abstractions/ILogContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ public interface ILogContext
/// </summary>
string Url { get; }

/// <summary>
/// 初始化日志标识
/// </summary>
void InitLogId();
///// <summary>
///// 初始化日志标识
///// </summary>
//void InitLogId();
}
}
Loading

0 comments on commit e1728e5

Please sign in to comment.