From b8f4377e618327e0fe6bfb9297a535ad11063a82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?jian=E7=8E=84=E5=86=B0?= Date: Wed, 28 Sep 2022 16:02:45 +0800 Subject: [PATCH 1/2] =?UTF-8?q?refactor:=20=E9=87=8D=E6=9E=84=E6=97=A5?= =?UTF-8?q?=E5=BF=97=E6=A8=A1=E5=9D=97=EF=BC=8C=E6=94=AF=E6=8C=81=E6=97=A5?= =?UTF-8?q?=E5=BF=97=E5=B7=A5=E5=8E=82=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Extensions.ServiceCollection.cs | 30 ++++- .../Bing/Logging/BingLoggingBuilder.cs | 24 ++++ .../Bing/Logging/BingLoggingOptions.cs | 41 ++++++ .../Logging/IBingLoggingOptionsExtension.cs | 16 +++ .../src/Bing.Logging/Bing/Logging/ILog.cs | 34 ++--- .../Bing/Logging/ILogExtensions.cs | 15 +-- .../Bing.Logging/Bing/Logging/ILogFactory.cs | 22 ++++ .../Bing/Logging/ILoggerWrapper.cs | 4 +- .../src/Bing.Logging/Bing/Logging/Log.cs | 37 +++--- .../Bing.Logging/Bing/Logging/LogFactory.cs | 45 +++++++ .../src/Bing.Logging/Bing/Logging/Log`.cs | 115 +++++++++++++++++ .../Bing/Logging/LoggerWrapper.cs | 9 +- .../src/Bing.Logging/Bing/Logging/NullLog.cs | 117 ++++++++++++++++-- .../Logging/ServiceCollectionExtensions.cs | 30 +++++ .../Bing.Logging.Serilog.Tests/Startup.cs | 1 + framework/tests/Bing.Logging.Tests/LogTest.cs | 8 +- .../Bing.Admin.FreeSQL/Modules/LogModule.cs | 1 + .../admin/src/Bing.Admin/Modules/AppModule.cs | 13 +- .../admin/src/Bing.Admin/Modules/LogModule.cs | 1 + .../Bing.Samples.Hangfire.csproj | 3 + .../Bing.Samples.Hangfire/Jobs/DebugLogJob.cs | 16 ++- .../Modules/LogModule.cs | 73 ++++++++++- 22 files changed, 565 insertions(+), 90 deletions(-) create mode 100644 framework/src/Bing.Logging/Bing/Logging/BingLoggingBuilder.cs create mode 100644 framework/src/Bing.Logging/Bing/Logging/BingLoggingOptions.cs create mode 100644 framework/src/Bing.Logging/Bing/Logging/IBingLoggingOptionsExtension.cs create mode 100644 framework/src/Bing.Logging/Bing/Logging/ILogFactory.cs create mode 100644 framework/src/Bing.Logging/Bing/Logging/LogFactory.cs create mode 100644 framework/src/Bing.Logging/Bing/Logging/Log`.cs create mode 100644 framework/src/Bing.Logging/Bing/Logging/ServiceCollectionExtensions.cs diff --git a/framework/src/Bing.AspNetCore/Bing/AspNetCore/Extensions/Extensions.ServiceCollection.cs b/framework/src/Bing.AspNetCore/Bing/AspNetCore/Extensions/Extensions.ServiceCollection.cs index 50a429c4..dea54457 100644 --- a/framework/src/Bing.AspNetCore/Bing/AspNetCore/Extensions/Extensions.ServiceCollection.cs +++ b/framework/src/Bing.AspNetCore/Bing/AspNetCore/Extensions/Extensions.ServiceCollection.cs @@ -45,10 +45,36 @@ public static void AddApiInterfaceService(this IServiceCol /// 服务集合 /// 配置操作 public static void AddRequestResponseLog(this IServiceCollection services, Action setupAction) + { + AddRequestResponseLog(services, setupAction); + } + + /// + /// 注册请求响应日志服务 + /// + /// 请求响应日志记录器 + /// 服务集合 + /// 配置操作 + public static void AddRequestResponseLog(this IServiceCollection services, Action setupAction) + where TLogger : class, IRequestResponseLogger + { + AddRequestResponseLog(services, setupAction); + } + + /// + /// 注册请求响应日志服务 + /// + /// 请求响应日志记录器 + /// 请求响应日志创建器 + /// 服务集合 + /// 配置操作 + public static void AddRequestResponseLog(this IServiceCollection services, Action setupAction) + where TLogger : class, IRequestResponseLogger + where TLogCreator : class, IRequestResponseLogCreator { services.Configure(setupAction); - services.AddSingleton(); - services.AddScoped(); + services.AddSingleton(); + services.AddScoped(); } } } diff --git a/framework/src/Bing.Logging/Bing/Logging/BingLoggingBuilder.cs b/framework/src/Bing.Logging/Bing/Logging/BingLoggingBuilder.cs new file mode 100644 index 00000000..edd4f9b9 --- /dev/null +++ b/framework/src/Bing.Logging/Bing/Logging/BingLoggingBuilder.cs @@ -0,0 +1,24 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace Bing.Logging +{ + /// + /// 日志构建器 + /// + public sealed class BingLoggingBuilder + { + /// + /// 初始化一个类型的实例 + /// + /// 服务集合 + public BingLoggingBuilder(IServiceCollection services) + { + Services = services; + } + + /// + /// 服务集合 + /// + public IServiceCollection Services { get; } + } +} diff --git a/framework/src/Bing.Logging/Bing/Logging/BingLoggingOptions.cs b/framework/src/Bing.Logging/Bing/Logging/BingLoggingOptions.cs new file mode 100644 index 00000000..cdac1ecb --- /dev/null +++ b/framework/src/Bing.Logging/Bing/Logging/BingLoggingOptions.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; + +namespace Bing.Logging +{ + /// + /// Bing 日志选项配置 + /// + public class BingLoggingOptions + { + /// + /// 初始化一个类型的实例 + /// + public BingLoggingOptions() + { + ClearProviders = false; + Extensions = new List(); + } + + /// + /// 日志选项扩展列表 + /// + internal IList Extensions { get; } + + /// + /// 是否清空日志提供程序 + /// + public bool ClearProviders { get; set; } + + /// + /// 注册扩展 + /// + /// 日志选项配置扩展 + public void RegisterExtension(IBingLoggingOptionsExtension extension) + { + if (extension == null) + throw new ArgumentNullException(nameof(extension)); + Extensions.Add(extension); + } + } +} diff --git a/framework/src/Bing.Logging/Bing/Logging/IBingLoggingOptionsExtension.cs b/framework/src/Bing.Logging/Bing/Logging/IBingLoggingOptionsExtension.cs new file mode 100644 index 00000000..f477fc86 --- /dev/null +++ b/framework/src/Bing.Logging/Bing/Logging/IBingLoggingOptionsExtension.cs @@ -0,0 +1,16 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace Bing.Logging +{ + /// + /// Bing 日志选项配置扩展 + /// + public interface IBingLoggingOptionsExtension + { + /// + /// 注册子服务 + /// + /// 服务集合 + void AddServices(IServiceCollection services); + } +} diff --git a/framework/src/Bing.Logging/Bing/Logging/ILog.cs b/framework/src/Bing.Logging/Bing/Logging/ILog.cs index b80e8fbc..e59f6c13 100644 --- a/framework/src/Bing.Logging/Bing/Logging/ILog.cs +++ b/framework/src/Bing.Logging/Bing/Logging/ILog.cs @@ -1,5 +1,4 @@ using System; -using Bing.DependencyInjection; using Microsoft.Extensions.Logging; namespace Bing.Logging @@ -8,45 +7,52 @@ namespace Bing.Logging /// 日志操作 /// /// 日志类别 - public interface ILog : ITransientDependency + public interface ILog : ILog + { + } + + /// + /// 日志操作 + /// + public interface ILog { /// /// 设置日志事件标识 /// /// 日志事件标识 - ILog EventId(EventId eventId); + ILog EventId(EventId eventId); /// /// 设置异常 /// /// 异常 - ILog Exception(Exception exception); + ILog Exception(Exception exception); /// /// 设置自定义扩展属性 /// /// 属性名 /// 属性值 - ILog Property(string propertyName, string propertyValue); + ILog Property(string propertyName, string propertyValue); /// /// 设置标签 /// /// 标签 - ILog Tags(params string[] tags); + ILog Tags(params string[] tags); /// /// 设置日志状态对象 /// /// 状态对象 - ILog State(object state); + ILog State(object state); /// /// 设置日志消息 /// /// 日志消息 /// 日志消息参数 - ILog Message(string message, params object[] args); + ILog Message(string message, params object[] args); /// /// 是否启用 @@ -65,31 +71,31 @@ public interface ILog : ITransientDependency /// /// 写跟踪日志 /// - ILog LogTrace(); + ILog LogTrace(); /// /// 写调试日志 /// - ILog LogDebug(); + ILog LogDebug(); /// /// 写信息日志 /// - ILog LogInformation(); + ILog LogInformation(); /// /// 写警告日志 /// - ILog LogWarning(); + ILog LogWarning(); /// /// 写错误日志 /// - ILog LogError(); + ILog LogError(); /// /// 写致命日志 /// - ILog LogCritical(); + ILog LogCritical(); } } diff --git a/framework/src/Bing.Logging/Bing/Logging/ILogExtensions.cs b/framework/src/Bing.Logging/Bing/Logging/ILogExtensions.cs index 4aa82f96..f94292ab 100644 --- a/framework/src/Bing.Logging/Bing/Logging/ILogExtensions.cs +++ b/framework/src/Bing.Logging/Bing/Logging/ILogExtensions.cs @@ -10,11 +10,10 @@ public static class ILogExtensions /// /// 添加消息 /// - /// 日志类别 /// 日志操作 /// 消息 /// 日志消息参数 - public static ILog Append(this ILog log, string message, params object[] args) + public static ILog Append(this ILog log, string message, params object[] args) { if (log is null) throw new ArgumentNullException(nameof(log)); @@ -25,12 +24,11 @@ public static ILog Append(this ILog /// /// 添加消息,当条件为true时 /// - /// 日志类别 /// 日志操作 /// 消息 /// 条件,值为true时,则添加消息 /// 日志消息参数 - public static ILog AppendIf(this ILog log, string message, bool condition, params object[] args) + public static ILog AppendIf(this ILog log, string message, bool condition, params object[] args) { if (log is null) throw new ArgumentNullException(nameof(log)); @@ -42,11 +40,10 @@ public static ILog AppendIf(this ILog /// 添加消息并换行 /// - /// 日志类别 /// 日志操作 /// 消息 /// 日志消息参数 - public static ILog AppendLine(this ILog log, string message, params object[] args) + public static ILog AppendLine(this ILog log, string message, params object[] args) { if (log is null) throw new ArgumentNullException(nameof(log)); @@ -58,13 +55,12 @@ public static ILog AppendLine(this ILog /// 添加消息并换行,当条件为true时 /// - /// 日志类别 /// 日志操作 /// 消息 /// 条件,值为true时,则添加消息 /// 日志消息参数 /// - public static ILog AppendLineIf(this ILog log, string message, bool condition, params object[] args) + public static ILog AppendLineIf(this ILog log, string message, bool condition, params object[] args) { if (log is null) throw new ArgumentNullException(nameof(log)); @@ -79,9 +75,8 @@ public static ILog AppendLineIf(this ILog /// 消息换行 /// - /// 日志类别 /// 日志操作 - public static ILog Line(this ILog log) + public static ILog Line(this ILog log) { if (log is null) throw new ArgumentNullException(nameof(log)); diff --git a/framework/src/Bing.Logging/Bing/Logging/ILogFactory.cs b/framework/src/Bing.Logging/Bing/Logging/ILogFactory.cs new file mode 100644 index 00000000..6c16e73a --- /dev/null +++ b/framework/src/Bing.Logging/Bing/Logging/ILogFactory.cs @@ -0,0 +1,22 @@ +using System; + +namespace Bing.Logging +{ + /// + /// 日志操作工厂 + /// + public interface ILogFactory + { + /// + /// 创建日志操作 + /// + /// 日志类别 + ILog CreateLog(string categoryName); + + /// + /// 创建日志操作 + /// + /// 日志类别类型 + ILog CreateLog(Type type); + } +} diff --git a/framework/src/Bing.Logging/Bing/Logging/ILoggerWrapper.cs b/framework/src/Bing.Logging/Bing/Logging/ILoggerWrapper.cs index f170410e..53359476 100644 --- a/framework/src/Bing.Logging/Bing/Logging/ILoggerWrapper.cs +++ b/framework/src/Bing.Logging/Bing/Logging/ILoggerWrapper.cs @@ -1,5 +1,4 @@ using System; -using Bing.DependencyInjection; using Microsoft.Extensions.Logging; namespace Bing.Logging @@ -7,8 +6,7 @@ namespace Bing.Logging /// /// 日志记录包装器 /// - /// 日志类别 - public interface ILoggerWrapper : ITransientDependency + public interface ILoggerWrapper { /// /// 是否启用 diff --git a/framework/src/Bing.Logging/Bing/Logging/Log.cs b/framework/src/Bing.Logging/Bing/Logging/Log.cs index d3fb9c89..3e1269f4 100644 --- a/framework/src/Bing.Logging/Bing/Logging/Log.cs +++ b/framework/src/Bing.Logging/Bing/Logging/Log.cs @@ -12,17 +12,16 @@ namespace Bing.Logging /// /// 日志操作 /// - /// 日志类别 - public class Log : ILog + public class Log : ILog { #region 构造函数 /// - /// 初始化一个类型的实例 + /// 初始化一个类型的实例 /// /// 日志记录包装器 /// 日志上下文访问器 - public Log(ILoggerWrapper logger, ILogContextAccessor logContextAccessor = null) + public Log(ILoggerWrapper logger, ILogContextAccessor logContextAccessor = null) { Logger = logger ?? throw new ArgumentNullException(nameof(logger)); LogContext = logContextAccessor?.Context; @@ -38,7 +37,7 @@ public Log(ILoggerWrapper logger, ILogContextAccessor logContextA /// /// 空日志操作实例 /// - public static ILog Null = NullLog.Instance; + public static ILog Null = NullLog.Instance; #endregion @@ -47,7 +46,7 @@ public Log(ILoggerWrapper logger, ILogContextAccessor logContextA /// /// 日志记录包装器 /// - protected ILoggerWrapper Logger { get; } + protected ILoggerWrapper Logger { get; } /// /// 日志上下文 @@ -94,7 +93,7 @@ public Log(ILoggerWrapper logger, ILogContextAccessor logContextA #region EventId(设置日志事件标识) /// - public virtual ILog EventId(EventId eventId) + public virtual ILog EventId(EventId eventId) { LogEventId = eventId; return this; @@ -105,7 +104,7 @@ public virtual ILog EventId(EventId eventId) #region Exception(设置异常) /// - public virtual ILog Exception(Exception exception) + public virtual ILog Exception(Exception exception) { LogException = exception; return this; @@ -116,7 +115,7 @@ public virtual ILog Exception(Exception exception) #region Property(设置自定义扩展属性) /// - public virtual ILog Property(string propertyName, string propertyValue) + public virtual ILog Property(string propertyName, string propertyValue) { if (string.IsNullOrWhiteSpace(propertyName)) return this; @@ -134,7 +133,7 @@ public virtual ILog Property(string propertyName, string property #region Tags(设置标签) /// - public virtual ILog Tags(params string[] tags) + public virtual ILog Tags(params string[] tags) { if (tags == null) return this; @@ -152,7 +151,7 @@ public virtual ILog Tags(params string[] tags) #region State(设置日志状态对象) /// - public virtual ILog State(object state) + public virtual ILog State(object state) { LogState = state; return this; @@ -163,7 +162,7 @@ public virtual ILog State(object state) #region Message(设置日志消息) /// - public virtual ILog Message(string message, params object[] args) + public virtual ILog Message(string message, params object[] args) { LogMessage.Append(message); LogMessageArgs.AddRange(args); @@ -189,7 +188,7 @@ public virtual ILog Message(string message, params object[] args) #region LogTrace(写跟踪日志) /// - public virtual ILog LogTrace() + public virtual ILog LogTrace() { try { @@ -214,7 +213,7 @@ public virtual ILog LogTrace() #region LogDebug(写调试日志) /// - public virtual ILog LogDebug() + public virtual ILog LogDebug() { try { @@ -239,7 +238,7 @@ public virtual ILog LogDebug() #region LogInformation(写信息日志) /// - public virtual ILog LogInformation() + public virtual ILog LogInformation() { try { @@ -264,7 +263,7 @@ public virtual ILog LogInformation() #region LogWarning(写警告日志) /// - public virtual ILog LogWarning() + public virtual ILog LogWarning() { try { @@ -289,7 +288,7 @@ public virtual ILog LogWarning() #region LogError(写错误日志) /// - public virtual ILog LogError() + public virtual ILog LogError() { try { @@ -314,7 +313,7 @@ public virtual ILog LogError() #region LogCritical(写致命日志) /// - public virtual ILog LogCritical() + public virtual ILog LogCritical() { try { @@ -415,7 +414,7 @@ protected virtual object[] GetMessageArgs() /// /// 写日志 /// - protected virtual ILog WriteLog() + protected virtual ILog WriteLog() { Logger.Log(LogLevel, LogEventId, GetContent(), LogException, GetFormatMessage); return this; diff --git a/framework/src/Bing.Logging/Bing/Logging/LogFactory.cs b/framework/src/Bing.Logging/Bing/Logging/LogFactory.cs new file mode 100644 index 00000000..01894505 --- /dev/null +++ b/framework/src/Bing.Logging/Bing/Logging/LogFactory.cs @@ -0,0 +1,45 @@ +using System; +using Microsoft.Extensions.Logging; + +namespace Bing.Logging +{ + /// + /// 日志操作工厂 + /// + public class LogFactory : ILogFactory + { + /// + /// 日志记录器工厂 + /// + private readonly ILoggerFactory _loggerFactory; + + /// + /// 初始化一个类型的实例 + /// + /// 日志记录器工厂 + /// + public LogFactory(ILoggerFactory factory) => _loggerFactory = factory ?? throw new ArgumentNullException(nameof(factory)); + + /// + /// 创建日志操作 + /// + /// 日志类别 + public ILog CreateLog(string categoryName) + { + var logger = _loggerFactory.CreateLogger(categoryName); + var wrapper = new LoggerWrapper(logger); + return new Log(wrapper); + } + + /// + /// 创建日志操作 + /// + /// 日志类别类型 + public ILog CreateLog(Type type) + { + var logger = _loggerFactory.CreateLogger(type); + var wrapper = new LoggerWrapper(logger); + return new Log(wrapper); + } + } +} diff --git a/framework/src/Bing.Logging/Bing/Logging/Log`.cs b/framework/src/Bing.Logging/Bing/Logging/Log`.cs new file mode 100644 index 00000000..bb84251c --- /dev/null +++ b/framework/src/Bing.Logging/Bing/Logging/Log`.cs @@ -0,0 +1,115 @@ +using System; +using Microsoft.Extensions.Logging; + +namespace Bing.Logging +{ + /// + /// 日志操作 + /// + /// 日志类别 + public class Log : ILog + { + /// + /// 日志操作 + /// + private readonly ILog _log; + + /// + /// 初始化一个类型的实例 + /// + /// 日志操作工厂 + public Log(ILogFactory factory) + { + if (factory is null) + throw new ArgumentNullException(nameof(factory)); + _log = factory.CreateLog(typeof(TCategoryName)); + } + + /// + /// 空日志操作实例 + /// + public static ILog Null = NullLog.Instance; + + /// + /// 设置日志事件标识 + /// + /// 日志事件标识 + public virtual ILog EventId(EventId eventId) => _log.EventId(eventId); + + /// + /// 设置异常 + /// + /// 异常 + public virtual ILog Exception(Exception exception) => _log.Exception(exception); + + /// + /// 设置自定义扩展属性 + /// + /// 属性名 + /// 属性值 + public virtual ILog Property(string propertyName, string propertyValue) => _log.Property(propertyName, propertyValue); + + /// + /// 设置标签 + /// + /// 标签 + public virtual ILog Tags(params string[] tags) => _log.Tags(tags); + + /// + /// 设置日志状态对象 + /// + /// 状态对象 + public virtual ILog State(object state) => _log.State(state); + + /// + /// 设置日志消息 + /// + /// 日志消息 + /// 日志消息参数 + public virtual ILog Message(string message, params object[] args) => _log.Message(message, args); + + /// + /// 是否启用 + /// + /// 日志级别 + /// true=启用;false=禁用 + public virtual bool IsEnabled(LogLevel logLevel) => _log.IsEnabled(logLevel); + + /// + /// 开启日志范围 + /// + /// 日志状态类型 + /// 日志状态 + public virtual IDisposable BeginScope(TState state) => _log.BeginScope(state); + + /// + /// 写跟踪日志 + /// + public virtual ILog LogTrace() => _log.LogTrace(); + + /// + /// 写调试日志 + /// + public virtual ILog LogDebug() => _log.LogDebug(); + + /// + /// 写信息日志 + /// + public virtual ILog LogInformation() => _log.LogInformation(); + + /// + /// 写警告日志 + /// + public virtual ILog LogWarning() => _log.LogWarning(); + + /// + /// 写错误日志 + /// + public virtual ILog LogError() => _log.LogError(); + + /// + /// 写致命日志 + /// + public virtual ILog LogCritical() => _log.LogCritical(); + } +} diff --git a/framework/src/Bing.Logging/Bing/Logging/LoggerWrapper.cs b/framework/src/Bing.Logging/Bing/Logging/LoggerWrapper.cs index df81c7f7..a99473b6 100644 --- a/framework/src/Bing.Logging/Bing/Logging/LoggerWrapper.cs +++ b/framework/src/Bing.Logging/Bing/Logging/LoggerWrapper.cs @@ -6,19 +6,18 @@ namespace Bing.Logging /// /// 日志记录包装器 /// - /// 日志类别 - public class LoggerWrapper : ILoggerWrapper + public class LoggerWrapper : ILoggerWrapper { /// - /// 初始化一个类型的实例 + /// 初始化一个类型的实例 /// /// 日志记录器 - public LoggerWrapper(ILogger logger) => Logger = logger ?? throw new ArgumentNullException(nameof(logger)); + public LoggerWrapper(ILogger logger) => Logger = logger ?? throw new ArgumentNullException(nameof(logger)); /// /// 日志记录器 /// - protected ILogger Logger { get; } + protected ILogger Logger { get; } /// public virtual bool IsEnabled(LogLevel logLevel) => Logger.IsEnabled(logLevel); diff --git a/framework/src/Bing.Logging/Bing/Logging/NullLog.cs b/framework/src/Bing.Logging/Bing/Logging/NullLog.cs index f9ecedfa..41eada36 100644 --- a/framework/src/Bing.Logging/Bing/Logging/NullLog.cs +++ b/framework/src/Bing.Logging/Bing/Logging/NullLog.cs @@ -18,39 +18,39 @@ public class NullLog : ILog /// 设置日志事件标识 /// /// 日志事件标识 - public ILog EventId(EventId eventId) => this; + public ILog EventId(EventId eventId) => this; /// /// 设置异常 /// /// 异常 - public ILog Exception(Exception exception) => this; + public ILog Exception(Exception exception) => this; /// /// 设置自定义扩展属性 /// /// 属性名 /// 属性值 - public ILog Property(string propertyName, string propertyValue) => this; + public ILog Property(string propertyName, string propertyValue) => this; /// /// 设置标签 /// /// 标签 - public ILog Tags(params string[] tags) => this; + public ILog Tags(params string[] tags) => this; /// /// 设置日志状态对象 /// /// 状态对象 - public ILog State(object state) => this; + public ILog State(object state) => this; /// /// 设置日志消息 /// /// 日志消息 /// 日志消息参数 - public ILog Message(string message, params object[] args) => this; + public ILog Message(string message, params object[] args) => this; /// /// 是否启用 @@ -69,31 +69,124 @@ public class NullLog : ILog /// /// 写跟踪日志 /// - public ILog LogTrace() => this; + public ILog LogTrace() => this; /// /// 写调试日志 /// - public ILog LogDebug() => this; + public ILog LogDebug() => this; /// /// 写信息日志 /// - public ILog LogInformation() => this; + public ILog LogInformation() => this; /// /// 写警告日志 /// - public ILog LogWarning() => this; + public ILog LogWarning() => this; /// /// 写错误日志 /// - public ILog LogError() => this; + public ILog LogError() => this; /// /// 写致命日志 /// - public ILog LogCritical() => this; + public ILog LogCritical() => this; + } + + /// + /// 空日志操作 + /// + public class NullLog : ILog + { + /// + /// 空日志操作实例 + /// + public static readonly ILog Instance = new NullLog(); + + /// + /// 设置日志事件标识 + /// + /// 日志事件标识 + public ILog EventId(EventId eventId) => this; + + /// + /// 设置异常 + /// + /// 异常 + public ILog Exception(Exception exception) => this; + + /// + /// 设置自定义扩展属性 + /// + /// 属性名 + /// 属性值 + public ILog Property(string propertyName, string propertyValue) => this; + + /// + /// 设置标签 + /// + /// 标签 + public ILog Tags(params string[] tags) => this; + + /// + /// 设置日志状态对象 + /// + /// 状态对象 + public ILog State(object state) => this; + + /// + /// 设置日志消息 + /// + /// 日志消息 + /// 日志消息参数 + public ILog Message(string message, params object[] args) => this; + + /// + /// 是否启用 + /// + /// 日志级别 + /// true=启用;false=禁用 + public bool IsEnabled(LogLevel logLevel) => false; + + /// + /// 开启日志范围 + /// + /// 日志状态类型 + /// 日志状态 + public IDisposable BeginScope(TState state) => new DisposeAction(() => { }); + + /// + /// 写跟踪日志 + /// + public ILog LogTrace() => this; + + /// + /// 写调试日志 + /// + public ILog LogDebug() => this; + + /// + /// 写信息日志 + /// + public ILog LogInformation() => this; + + /// + /// 写警告日志 + /// + public ILog LogWarning() => this; + + /// + /// 写错误日志 + /// + public ILog LogError() => this; + + /// + /// 写致命日志 + /// + public ILog LogCritical() => this; } } diff --git a/framework/src/Bing.Logging/Bing/Logging/ServiceCollectionExtensions.cs b/framework/src/Bing.Logging/Bing/Logging/ServiceCollectionExtensions.cs new file mode 100644 index 00000000..a0220e57 --- /dev/null +++ b/framework/src/Bing.Logging/Bing/Logging/ServiceCollectionExtensions.cs @@ -0,0 +1,30 @@ +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace Bing.Logging +{ + /// + /// 服务集合扩展 + /// + public static class ServiceCollectionExtensions + { + /// + /// 注册日志 + /// + /// 服务集合 + /// 安装配置 + public static BingLoggingBuilder AddBingLogging(this IServiceCollection services, Action setupAction) + { + services.TryAddSingleton(); + services.TryAddTransient(typeof(ILog<>), typeof(Log<>)); + services.TryAddTransient(typeof(ILoggerWrapper), typeof(LoggerWrapper)); + services.TryAddTransient(typeof(ILog), t => t.GetService()?.CreateLog("default") ?? NullLog.Instance); + var options = new BingLoggingOptions(); + setupAction(options); + foreach (var serviceExtension in options.Extensions) + serviceExtension.AddServices(services); + return new BingLoggingBuilder(services); + } + } +} diff --git a/framework/tests/Bing.Logging.Serilog.Tests/Startup.cs b/framework/tests/Bing.Logging.Serilog.Tests/Startup.cs index 38a48cec..ac1b4c49 100644 --- a/framework/tests/Bing.Logging.Serilog.Tests/Startup.cs +++ b/framework/tests/Bing.Logging.Serilog.Tests/Startup.cs @@ -43,6 +43,7 @@ private void CurrentDomain_ProcessExit(object sender, EventArgs e) /// public void ConfigureServices(IServiceCollection services) { + services.AddBingLogging(x => { }); services.AddSingleton(); services.AddLogging(loggingBuilder => { diff --git a/framework/tests/Bing.Logging.Tests/LogTest.cs b/framework/tests/Bing.Logging.Tests/LogTest.cs index 5df76a1d..7f546fbd 100644 --- a/framework/tests/Bing.Logging.Tests/LogTest.cs +++ b/framework/tests/Bing.Logging.Tests/LogTest.cs @@ -10,20 +10,20 @@ public partial class LogTest /// /// 模拟日志 /// - private readonly Mock> _mockLogger; + private readonly Mock _mockLogger; /// /// 日志操作 /// - private readonly ILog _log; + private readonly ILog _log; /// /// 测试初始化 /// public LogTest() { - _mockLogger = new Mock>(); - _log = new Log(_mockLogger.Object); + _mockLogger = new Mock(); + _log = new Log(_mockLogger.Object); } } } diff --git a/modules/admin/src/Bing.Admin.FreeSQL/Modules/LogModule.cs b/modules/admin/src/Bing.Admin.FreeSQL/Modules/LogModule.cs index 3f21db0e..26ce83f3 100644 --- a/modules/admin/src/Bing.Admin.FreeSQL/Modules/LogModule.cs +++ b/modules/admin/src/Bing.Admin.FreeSQL/Modules/LogModule.cs @@ -47,6 +47,7 @@ public override IServiceCollection AddServices(IServiceCollection services) //ExceptionlessClient.Default.Configuration.ApiKey= "ez9jumyxVxjTxqSm0oUQhCML3OGCkDfMGyW1hfmn"; //ExceptionlessClient.Default.Configuration.ServerUrl = "http://10.186.132.40:5100"; //ExceptionlessClient.Default.Startup(); + services.AddBingLogging(x => { }); services.AddSingleton(); services.AddLogging(loggingBuilder => { diff --git a/modules/admin/src/Bing.Admin/Modules/AppModule.cs b/modules/admin/src/Bing.Admin/Modules/AppModule.cs index ab2e8e65..b30f7b44 100644 --- a/modules/admin/src/Bing.Admin/Modules/AppModule.cs +++ b/modules/admin/src/Bing.Admin/Modules/AppModule.cs @@ -19,6 +19,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.AspNetCore.Mvc.Authorization; +using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; using Microsoft.Extensions.DependencyInjection; namespace Bing.Admin.Modules @@ -51,17 +52,7 @@ public override IServiceCollection AddServices(IServiceCollection services) o.Filters.Add(); o.Filters.Add(); o.Conventions.Add(new AuthorizeControllerModelConvention()); - o.ModelBindingMessageProvider.SetMissingBindRequiredValueAccessor((x) => $"没有为属性 '{x}' 指定值"); - o.ModelBindingMessageProvider.SetMissingKeyOrValueAccessor(() => "必须指定值"); - o.ModelBindingMessageProvider.SetMissingRequestBodyRequiredValueAccessor(() => "请求正文不能为空"); - o.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor((x) => $"'{x}' 是无效的值"); - o.ModelBindingMessageProvider.SetAttemptedValueIsInvalidAccessor((x, y) => $"'{x}' 不能作为 {y} 的值"); - o.ModelBindingMessageProvider.SetNonPropertyAttemptedValueIsInvalidAccessor((x) => $"'{x}' 是无效的值"); - o.ModelBindingMessageProvider.SetUnknownValueIsInvalidAccessor((x) => $"为 {x} 指定的值无效"); - o.ModelBindingMessageProvider.SetNonPropertyUnknownValueIsInvalidAccessor(() => "指定的值无效"); - o.ModelBindingMessageProvider.SetValueIsInvalidAccessor((x) => $"值 {x} 无效"); - o.ModelBindingMessageProvider.SetValueMustBeANumberAccessor((x)=>$"字段 {x} 的值应该是数字"); - o.ModelBindingMessageProvider.SetNonPropertyValueMustBeANumberAccessor(() => "字段的值应该是数字"); + o.ModelBindingMessageProvider.UseTranslatedResources(); }) .AddControllersAsServices()// 解决属性注入无法在控制器中注入的问题 .AddNewtonsoftJson(options => diff --git a/modules/admin/src/Bing.Admin/Modules/LogModule.cs b/modules/admin/src/Bing.Admin/Modules/LogModule.cs index 1e5d828a..3d5ed783 100644 --- a/modules/admin/src/Bing.Admin/Modules/LogModule.cs +++ b/modules/admin/src/Bing.Admin/Modules/LogModule.cs @@ -51,6 +51,7 @@ public override IServiceCollection AddServices(IServiceCollection services) //ExceptionlessClient.Default.Configuration.ApiKey= "ez9jumyxVxjTxqSm0oUQhCML3OGCkDfMGyW1hfmn"; //ExceptionlessClient.Default.Configuration.ServerUrl = "http://10.186.132.40:5100"; //ExceptionlessClient.Default.Startup(); + services.AddBingLogging(x => { }); services.AddSingleton(); services.AddLogging(loggingBuilder => { diff --git a/samples/Bing.Samples.Hangfire/Bing.Samples.Hangfire.csproj b/samples/Bing.Samples.Hangfire/Bing.Samples.Hangfire.csproj index 710fd280..4b07e091 100644 --- a/samples/Bing.Samples.Hangfire/Bing.Samples.Hangfire.csproj +++ b/samples/Bing.Samples.Hangfire/Bing.Samples.Hangfire.csproj @@ -9,10 +9,13 @@ + + + diff --git a/samples/Bing.Samples.Hangfire/Jobs/DebugLogJob.cs b/samples/Bing.Samples.Hangfire/Jobs/DebugLogJob.cs index 35aef4ab..521661b7 100644 --- a/samples/Bing.Samples.Hangfire/Jobs/DebugLogJob.cs +++ b/samples/Bing.Samples.Hangfire/Jobs/DebugLogJob.cs @@ -2,6 +2,7 @@ using System.Diagnostics; using Bing.Aspects; using Bing.DependencyInjection; +using Bing.Logging; using Bing.Logs; using Bing.Logs.Abstractions; using Exceptionless; @@ -27,14 +28,17 @@ public class DebugLogJob : IDebugLogJob protected ILogContext LogContext { get; } [Autowired] - protected ILog Logger { get; set; } + protected Bing.Logs.ILog Logger { get; set; } protected ILogger SysLogger { get; set; } - public DebugLogJob(ILogContext logContext, ILogger logger) + protected ILog CurrentLog { get; } + + public DebugLogJob(ILogContext logContext, ILogger logger, ILog currentLog) { LogContext = logContext; SysLogger = logger; + CurrentLog = currentLog; } /// @@ -54,6 +58,8 @@ public void WriteLog() .CreateLog($"隔壁老王的信息-Source【{DateTime.Now:yyyy-MM-dd HH:mm:ss.sss}】 ", LogLevel.Info).Submit(); el.ExceptionlessClient.Default .CreateLog($"隔壁老王的信息-Source-NotLevel【{DateTime.Now:yyyy-MM-dd HH:mm:ss.sss}】 ").Submit(); + Debug.WriteLine($"CurrentLog: {CurrentLog.GetType()}"); + CurrentLog.Message("测试日志信息").LogInformation(); //Logger.Class(GetType().FullName) // .Caption("DebugLogJob") @@ -78,15 +84,15 @@ public void WriteLog() //SysLogger.LogInformation($"4-4、【系统日志】【{DateTime.Now:yyyy-MM-dd HH:mm:ss.sss}】 {nameof(WriteLog)} | 写入日志"); } - private ILog GetLog() + private Bing.Logs.ILog GetLog() { try { - return Log.GetLog("HangfireLog"); + return Bing.Logs.Log.GetLog("HangfireLog"); } catch { - return Log.Null; + return Bing.Logs.Log.Null; } } } diff --git a/samples/Bing.Samples.Hangfire/Modules/LogModule.cs b/samples/Bing.Samples.Hangfire/Modules/LogModule.cs index b5179b64..8572f484 100644 --- a/samples/Bing.Samples.Hangfire/Modules/LogModule.cs +++ b/samples/Bing.Samples.Hangfire/Modules/LogModule.cs @@ -1,9 +1,15 @@ using System.ComponentModel; +using System.Threading; using Bing.AspNetCore; using Bing.Core.Modularity; -using Bing.Logs.Exceptionless; -using Bing.Logs.NLog; +using Bing.Logging; +using Bing.Logging.Serilog; +using Bing.Tracing; +using Exceptionless; using Microsoft.Extensions.DependencyInjection; +using Serilog; +using Serilog.Enrichers.Span; +using serilog = Serilog; namespace Bing.Samples.Hangfire.Modules { @@ -32,12 +38,69 @@ public class LogModule : AspNetCoreBingModule public override IServiceCollection AddServices(IServiceCollection services) { //services.AddNLog(); - services.AddExceptionless(x => + // 同时输出2种方式的日志,可能存在重复 需要陆续兼容 + Logs.Exceptionless.Extensions.AddExceptionless(services, o => { - x.ServerUrl = "http://10.186.135.27:5100"; - x.ApiKey = "yIgaHwtLwbN9VoUCP0UYpSPVzwpmeNSdVSfVIVta"; + o.ApiKey = "N8HOaOLndl0hF7ZhOfiwJ9HmOi6kPwjKEKWLCMzE"; + o.ServerUrl = "http://10.186.132.40:5100"; + }); + services.AddBingLogging(x => { }); + services.AddSingleton(); + services.AddLogging(loggingBuilder => + { + var configuration = services.GetConfiguration(); + serilog.Log.Logger = new serilog.LoggerConfiguration() + .Enrich.FromLogContext() + .Enrich.WithLogContext() + .Enrich.WithLogLevel() + .Enrich.WithSpan() + .WriteTo.Exceptionless(additionalOperation: (builder) => + { + if (builder.Target.Data.TryGetValue("TraceId", out var traceId)) + builder.Target.AddTags(traceId.ToString() ?? string.Empty); + builder.Target.AddTags((TraceIdContext.Current ??= new TraceIdContext(string.Empty)).TraceId); + return builder; + }) + .ReadFrom.Configuration(configuration) + .ConfigLogLevel(configuration) + .CreateLogger(); + loggingBuilder.AddSerilog(); }); return services; } } + + /// + /// 日志上下文访问器 + /// + public class LogContextAccessor : ILogContextAccessor + { + /// + /// 当前日志上下文 + /// + private readonly AsyncLocal _currentLogContext; + + /// + /// 初始化一个类型的实例 + /// + public LogContextAccessor() + { + _currentLogContext = new AsyncLocal(); + } + + /// + /// 日志上下文 + /// + public LogContext Context + { + get + { + return _currentLogContext.Value ??= new LogContext(); + } + set + { + _currentLogContext.Value = value; + } + } + } } From 85c1fc5fb87e19ff6e1134f861f44ee04ef14978 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?jian=E7=8E=84=E5=86=B0?= Date: Wed, 28 Sep 2022 18:48:56 +0800 Subject: [PATCH 2/2] =?UTF-8?q?publish:=20=E5=8F=91=E5=B8=83=202.2.5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- version.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.props b/version.props index ff2d9005..56679bd8 100644 --- a/version.props +++ b/version.props @@ -2,7 +2,7 @@ 2 2 - 4 + 5 20220907-1 $(VersionMajor).$(VersionMinor).$(VersionPatch)