feat: 增加后台服务生命周期识别

This commit is contained in:
Diego
2025-06-30 10:59:18 +08:00
parent 92bca824e6
commit feb1d0a3c5
17 changed files with 145 additions and 478 deletions

View File

@@ -11,10 +11,12 @@
using BootstrapBlazor.Components;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Reflection;
using System.Text;
using ThingsGateway.NewLife.Log;
using ThingsGateway.Extension;
using ThingsGateway.UnifyResult;
namespace ThingsGateway.Admin.Application;
@@ -65,11 +67,76 @@ public class Startup : AppStartup
services.AddSingleton(typeof(IEventService<>), typeof(EventService<>));
#region
services.AddConsoleFormatter(options =>
{
options.WriteFilter = (logMsg) =>
{
if (App.HostApplicationLifetime.ApplicationStopping.IsCancellationRequested && logMsg.LogLevel >= LogLevel.Warning) return false;
if (string.IsNullOrEmpty(logMsg.Message)) return false;
else return true;
};
options.MessageFormat = (logMsg) =>
{
//如果不是LoggingMonitor日志才格式化
if (logMsg.LogName != "System.Logging.LoggingMonitor")
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine("【日志级别】:" + logMsg.LogLevel);
stringBuilder.AppendLine("【日志类名】:" + logMsg.LogName);
stringBuilder.AppendLine("【日志时间】:" + DateTime.Now.ToDefaultDateTimeFormat());
stringBuilder.AppendLine("【日志内容】:" + logMsg.Message);
if (logMsg.Exception != null)
{
stringBuilder.AppendLine("【异常信息】:" + logMsg.Exception);
}
return stringBuilder.ToString();
}
else
{
return logMsg.Message;
}
};
options.WriteHandler = (logMsg, scopeProvider, writer, fmtMsg, opt) =>
{
ConsoleColor consoleColor = ConsoleColor.White;
switch (logMsg.LogLevel)
{
case LogLevel.Information:
consoleColor = ConsoleColor.DarkGreen;
break;
case LogLevel.Warning:
consoleColor = ConsoleColor.DarkYellow;
break;
case LogLevel.Error:
consoleColor = ConsoleColor.DarkRed;
break;
}
writer.WriteWithColor(fmtMsg, ConsoleColor.Black, consoleColor);
};
});
#endregion
//日志写入数据库配置
services.AddDatabaseLogging<DatabaseLoggingWriter>(options =>
{
options.NameFilter = (name) =>
{
return (
name == "System.Logging.RequestAudit"
);
};
});
}
public void Use(IServiceProvider serviceProvider)
{
XTrace.UnhandledExceptionLogEnable = () => !App.HostApplicationLifetime.ApplicationStopping.IsCancellationRequested;
NewLife.Log.XTrace.UnhandledExceptionLogEnable = () => !App.HostApplicationLifetime.ApplicationStopping.IsCancellationRequested;
//检查ConfigId
var configIdGroup = DbContext.DbConfigs.GroupBy(it => it.ConfigId);

View File

@@ -21,13 +21,11 @@ using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using ThingsGateway.Admin.Application;
using ThingsGateway.Admin.Razor;
using ThingsGateway.Extension;
using ThingsGateway.NewLife.Caching;
using ThingsGateway.VirtualFileServer;
@@ -153,101 +151,9 @@ public class Startup : AppStartup
#region
services.AddConsoleFormatter(options =>
{
options.WriteFilter = (logMsg) =>
{
if (App.HostApplicationLifetime.ApplicationStopping.IsCancellationRequested && logMsg.LogLevel >= LogLevel.Warning) return false;
if (string.IsNullOrEmpty(logMsg.Message)) return false;
else return true;
};
options.MessageFormat = (logMsg) =>
{
//如果不是LoggingMonitor日志才格式化
if (logMsg.LogName != "System.Logging.LoggingMonitor")
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine("【日志级别】:" + logMsg.LogLevel);
stringBuilder.AppendLine("【日志类名】:" + logMsg.LogName);
stringBuilder.AppendLine("【日志时间】:" + DateTime.Now.ToDefaultDateTimeFormat());
stringBuilder.AppendLine("【日志内容】:" + logMsg.Message);
if (logMsg.Exception != null)
{
stringBuilder.AppendLine("【异常信息】:" + logMsg.Exception);
}
return stringBuilder.ToString();
}
else
{
return logMsg.Message;
}
};
options.WriteHandler = (logMsg, scopeProvider, writer, fmtMsg, opt) =>
{
ConsoleColor consoleColor = ConsoleColor.White;
switch (logMsg.LogLevel)
{
case LogLevel.Information:
consoleColor = ConsoleColor.DarkGreen;
break;
case LogLevel.Warning:
consoleColor = ConsoleColor.DarkYellow;
break;
case LogLevel.Error:
consoleColor = ConsoleColor.DarkRed;
break;
}
writer.WriteWithColor(fmtMsg, ConsoleColor.Black, consoleColor);
};
});
#endregion
#region api日志
//Monitor日志配置
//services.AddMonitorLogging(options =>
//{
// options.JsonIndented = true;// 是否美化 JSON
// options.GlobalEnabled = false;//全局启用
// options.ConfigureLogger((logger, logContext, context) =>
// {
// var httpContext = context.HttpContext;//获取httpContext
// //获取客户端信息
// var client = App.GetService<IAppService>().UserAgent;
// // 获取控制器/操作描述器
// var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
// //操作名称默认是控制器名加方法名,自定义操作名称要在action上加Description特性
// var option = $"{controllerActionDescriptor.ControllerName}/{controllerActionDescriptor.ActionName}";
// var desc = App.CreateLocalizerByType(controllerActionDescriptor.ControllerTypeInfo.AsType())[controllerActionDescriptor.MethodInfo.Name];
// //获取特性
// option = desc.Value;//则将操作名称赋值为控制器上写的title
// logContext.Set(LoggingConst.CateGory, option);//传操作名称
// logContext.Set(LoggingConst.Operation, option);//传操作名称
// logContext.Set(LoggingConst.Client, client);//客户端信息
// logContext.Set(LoggingConst.Path, httpContext.Request.Path.Value);//请求地址
// logContext.Set(LoggingConst.Method, httpContext.Request.Method);//请求方法
// });
//});
//日志写入数据库配置
services.AddDatabaseLogging<DatabaseLoggingWriter>(options =>
{
options.WriteFilter = (logMsg) =>
{
return logMsg.LogName == "System.Logging.RequestAudit";
};
});
#endregion api日志
//已添加AddOptions
// 增加多语言支持配置信息

View File

@@ -93,6 +93,10 @@ public sealed class DatabaseLogger : ILogger, IDisposable
{
// 判断日志级别是否有效
if (!IsEnabled(logLevel)) return;
if (_options.NameFilter?.Invoke(_logName) == false)
{
return;
}
// 检查日志格式化器
if (formatter == null) throw new ArgumentNullException(nameof(formatter));

View File

@@ -51,7 +51,10 @@ public sealed class DatabaseLoggerOptions
/// 是否使用 UTC 时间戳,默认 false
/// </summary>
public bool UseUtcTimestamp { get; set; }
/// <summary>
/// 名称筛选
/// </summary>
public Func<string, bool> NameFilter { get; set; }
/// <summary>
/// 日期格式化
/// </summary>

View File

@@ -1,8 +1,8 @@
<Project>
<PropertyGroup>
<PluginVersion>10.9.6</PluginVersion>
<ProPluginVersion>10.9.6</ProPluginVersion>
<PluginVersion>10.9.7</PluginVersion>
<ProPluginVersion>10.9.7</ProPluginVersion>
<AuthenticationVersion>2.9.4</AuthenticationVersion>
<SourceGeneratorVersion>10.9.4</SourceGeneratorVersion>
<NET8Version>8.0.17</NET8Version>

View File

@@ -102,6 +102,11 @@ internal sealed class ChannelThreadManage : IChannelThreadManage
{
try
{
if (App.HostApplicationLifetime.ApplicationStopping.IsCancellationRequested)
{
return;
}
if (channelRuntime.IsCollect == true)
{
if (!GlobalData.StartCollectChannelEnable)
@@ -148,7 +153,7 @@ internal sealed class ChannelThreadManage : IChannelThreadManage
{
try
{
await NewChannelLock.WaitAsync().ConfigureAwait(false);
await NewChannelLock.WaitAsync(App.HostApplicationLifetime.ApplicationStopping).ConfigureAwait(false);
await PrivateRestartChannelAsync([channelRuntime]).ConfigureAwait(false);
}
finally
@@ -165,7 +170,7 @@ internal sealed class ChannelThreadManage : IChannelThreadManage
try
{
await NewChannelLock.WaitAsync().ConfigureAwait(false);
await NewChannelLock.WaitAsync(App.HostApplicationLifetime.ApplicationStopping).ConfigureAwait(false);
await PrivateRestartChannelAsync(channelRuntimes).ConfigureAwait(false);
}
finally
@@ -174,6 +179,11 @@ internal sealed class ChannelThreadManage : IChannelThreadManage
}
}
public async ValueTask DisposeAsync()
{
await RemoveChannelAsync(DeviceThreadManages.Keys.ToList()).ConfigureAwait(false);
}
#endregion

View File

@@ -12,7 +12,7 @@ using System.Collections.Concurrent;
namespace ThingsGateway.Gateway.Application;
public interface IChannelThreadManage
public interface IChannelThreadManage : IAsyncDisposable
{
ConcurrentDictionary<long, IDeviceThreadManage> DeviceThreadManages { get; }

View File

@@ -179,7 +179,7 @@ internal sealed class DeviceThreadManage : IAsyncDisposable, IDeviceThreadManage
{
try
{
await NewDeviceLock.WaitAsync().ConfigureAwait(false);
await NewDeviceLock.WaitAsync(App.HostApplicationLifetime.ApplicationStopping).ConfigureAwait(false);
await PrivateRestartDeviceAsync([deviceRuntime], deleteCache).ConfigureAwait(false);
}
finally
@@ -196,7 +196,7 @@ internal sealed class DeviceThreadManage : IAsyncDisposable, IDeviceThreadManage
try
{
await NewDeviceLock.WaitAsync().ConfigureAwait(false);
await NewDeviceLock.WaitAsync(App.HostApplicationLifetime.ApplicationStopping).ConfigureAwait(false);
await PrivateRestartDeviceAsync(deviceRuntimes, deleteCache).ConfigureAwait(false);
}
finally
@@ -216,7 +216,10 @@ internal sealed class DeviceThreadManage : IAsyncDisposable, IDeviceThreadManage
{
return;
}
if (App.HostApplicationLifetime.ApplicationStopping.IsCancellationRequested)
{
return;
}
if (deleteCache)
{
var basePath = CacheDBUtil.GetCacheFileBasePath();
@@ -240,6 +243,15 @@ internal sealed class DeviceThreadManage : IAsyncDisposable, IDeviceThreadManage
await deviceRuntimes.ParallelForEachAsync(async (deviceRuntime, cancellationToken) =>
{
if (App.HostApplicationLifetime.ApplicationStopping.IsCancellationRequested)
{
return;
}
if (Disposed)
{
return;
}
//备用设备实时取消
var redundantDeviceId = deviceRuntime.RedundantDeviceId;
if (GlobalData.ReadOnlyIdDevices.TryGetValue(redundantDeviceId ?? 0, out var redundantDeviceRuntime))
@@ -288,6 +300,10 @@ internal sealed class DeviceThreadManage : IAsyncDisposable, IDeviceThreadManage
}
}
DriverBase driver = null;
// 创建令牌并与驱动程序对象的设备ID关联用于取消操作
var cts = new CancellationTokenSource();
var token = cts.Token;
try
{
driver = CreateDriver(deviceRuntime);
@@ -304,7 +320,7 @@ internal sealed class DeviceThreadManage : IAsyncDisposable, IDeviceThreadManage
driver.DeviceThreadManage = this;
// 初始化驱动程序对象,并加载源读取
await driver.InitChannelAsync(Channel, cancellationToken).ConfigureAwait(false);
await driver.InitChannelAsync(Channel, token).ConfigureAwait(false);
}
catch (Exception ex)
@@ -315,38 +331,27 @@ internal sealed class DeviceThreadManage : IAsyncDisposable, IDeviceThreadManage
LogMessage?.LogWarning(ex, string.Format(AppResource.InitFail, CurrentChannel.PluginName, driver?.DeviceName));
}
// 创建令牌并与驱动程序对象的设备ID关联用于取消操作
var cts = new CancellationTokenSource();
var token = cts.Token;
if (!CancellationTokenSources.TryAdd(driver.DeviceId, cts))
if (CancellationTokenSources.TryGetValue(driver.DeviceId, out var oldCts))
{
try
{
cts.Cancel();
cts.SafeDispose();
oldCts.Cancel();
oldCts.SafeDispose();
}
catch
{
}
}
token.Register(driver.Stop);
CancellationTokenSources.TryAdd(driver.DeviceId, cts);
token.Register(driver.Stop);
_ = Task.Factory.StartNew((state) => DriverStart(state, token), driver, token);
}).ConfigureAwait(false);
ThreadPool.GetMaxThreads(out int maxWorkerThreads, out int maxCompletionPortThreads);
var taskCount = GlobalData.IdDevices.Count * Environment.ProcessorCount;
if (taskCount > maxWorkerThreads)
{
var result = ThreadPool.SetMaxThreads(taskCount + maxWorkerThreads, taskCount + maxCompletionPortThreads);
}
}
catch (Exception ex)
{
@@ -807,6 +812,8 @@ internal sealed class DeviceThreadManage : IAsyncDisposable, IDeviceThreadManage
Disposed = true;
try
{
CancellationTokenSource.Cancel();
CancellationTokenSource.SafeDispose();
GlobalData.DeviceStatusChangeEvent -= GlobalData_DeviceStatusChangeEvent;
await NewDeviceLock.WaitAsync().ConfigureAwait(false);
_logger?.TryDispose();
@@ -821,8 +828,6 @@ internal sealed class DeviceThreadManage : IAsyncDisposable, IDeviceThreadManage
}
finally
{
CancellationTokenSource.Cancel();
CancellationTokenSource.SafeDispose();
NewDeviceLock.Release();
}
}

View File

@@ -84,4 +84,9 @@ internal sealed class GatewayMonitorHostedService : BackgroundService, IGatewayM
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
await ChannelThreadManage.DisposeAsync().ConfigureAwait(false);
await base.StopAsync(cancellationToken).ConfigureAwait(false);
}
}

View File

@@ -55,13 +55,13 @@ public class Startup : AppStartup
//运行日志写入数据库配置
services.AddDatabaseLogging<BackendLogDatabaseLoggingWriter>(options =>
{
options.WriteFilter = (logMsg) =>
options.NameFilter = (name) =>
{
return (
!logMsg.LogName.StartsWith("System") &&
!logMsg.LogName.StartsWith("Microsoft") &&
!logMsg.LogName.StartsWith("Blazor") &&
!logMsg.LogName.StartsWith("BootstrapBlazor")
!name.StartsWith("System") &&
!name.StartsWith("Microsoft") &&
!name.StartsWith("Blazor") &&
!name.StartsWith("BootstrapBlazor")
);
};
});

View File

@@ -21,6 +21,15 @@ public partial class ModbusMaster : DtuServiceDeviceBase, IModbusAddress
RegisterByteLength = 2;
channel.MaxSign = ushort.MaxValue;
}
protected override void SetChannel()
{
if (ModbusType != ModbusTypeEnum.ModbusTcp)
{
Channel.ChannelOptions.MaxConcurrentCount = 1;
}
}
public override IThingsGatewayBitConverter ThingsGatewayBitConverter { get; protected set; } = new ThingsGatewayBitConverter(EndianType.Big) { };
/// <summary>

View File

@@ -27,6 +27,11 @@ public partial class SiemensS7Master : DeviceBase
RegisterByteLength = 1;
}
protected override void SetChannel()
{
}
public override IThingsGatewayBitConverter ThingsGatewayBitConverter { get; protected set; } = new S7BitConverter(EndianType.Big) { };
/// <summary>

View File

@@ -20,13 +20,11 @@ using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using ThingsGateway.Admin.Application;
using ThingsGateway.Admin.Razor;
using ThingsGateway.Extension;
using ThingsGateway.NewLife.Caching;
using ThingsGateway.Razor;
using ThingsGateway.VirtualFileServer;
@@ -152,60 +150,6 @@ public class Startup : AppStartup
});
#region
services.AddConsoleFormatter(options =>
{
options.WriteFilter = (logMsg) =>
{
if (App.HostApplicationLifetime.ApplicationStopping.IsCancellationRequested && logMsg.LogLevel >= LogLevel.Warning) return false;
if (string.IsNullOrEmpty(logMsg.Message)) return false;
else return true;
};
options.MessageFormat = (logMsg) =>
{
//如果不是LoggingMonitor日志才格式化
if (logMsg.LogName != "System.Logging.LoggingMonitor")
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine("【日志级别】:" + logMsg.LogLevel);
stringBuilder.AppendLine("【日志类名】:" + logMsg.LogName);
stringBuilder.AppendLine("【日志时间】:" + DateTime.Now.ToDefaultDateTimeFormat());
stringBuilder.AppendLine("【日志内容】:" + logMsg.Message);
if (logMsg.Exception != null)
{
stringBuilder.AppendLine("【异常信息】:" + logMsg.Exception);
}
return stringBuilder.ToString();
}
else
{
return logMsg.Message;
}
};
options.WriteHandler = (logMsg, scopeProvider, writer, fmtMsg, opt) =>
{
ConsoleColor consoleColor = ConsoleColor.White;
switch (logMsg.LogLevel)
{
case LogLevel.Information:
consoleColor = ConsoleColor.DarkGreen;
break;
case LogLevel.Warning:
consoleColor = ConsoleColor.DarkYellow;
break;
case LogLevel.Error:
consoleColor = ConsoleColor.DarkRed;
break;
}
writer.WriteWithColor(fmtMsg, ConsoleColor.Black, consoleColor);
};
});
#endregion
#region api日志
@@ -237,14 +181,7 @@ public class Startup : AppStartup
// });
//});
//日志写入数据库配置
services.AddDatabaseLogging<DatabaseLoggingWriter>(options =>
{
options.WriteFilter = (logMsg) =>
{
return logMsg.LogName == "System.Logging.RequestAudit";
};
});
#endregion api日志

View File

@@ -20,20 +20,17 @@ using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using ThingsGateway.Admin.Application;
using ThingsGateway.Admin.Razor;
using ThingsGateway.Debug;
using ThingsGateway.Extension;
using ThingsGateway.Gateway.Application;
using ThingsGateway.NewLife.Caching;
using ThingsGateway.VirtualFileServer;
@@ -130,102 +127,9 @@ public class Startup : AppStartup
#region
services.AddConsoleFormatter(options =>
{
options.WriteFilter = (logMsg) =>
{
if (App.HostApplicationLifetime.ApplicationStopping.IsCancellationRequested && logMsg.LogLevel >= LogLevel.Warning) return false;
if (string.IsNullOrEmpty(logMsg.Message)) return false;
else return true;
};
options.MessageFormat = (logMsg) =>
{
//如果不是LoggingMonitor日志才格式化
if (logMsg.LogName != "System.Logging.LoggingMonitor")
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine("【日志级别】:" + logMsg.LogLevel);
stringBuilder.AppendLine("【日志类名】:" + logMsg.LogName);
stringBuilder.AppendLine("【日志时间】:" + DateTime.Now.ToDefaultDateTimeFormat());
stringBuilder.AppendLine("【日志内容】:" + logMsg.Message);
if (logMsg.Exception != null)
{
stringBuilder.AppendLine("【异常信息】:" + logMsg.Exception);
}
return stringBuilder.ToString();
}
else
{
return logMsg.Message;
}
};
options.WriteHandler = (logMsg, scopeProvider, writer, fmtMsg, opt) =>
{
ConsoleColor consoleColor = ConsoleColor.White;
switch (logMsg.LogLevel)
{
case LogLevel.Information:
consoleColor = ConsoleColor.DarkGreen;
break;
case LogLevel.Warning:
consoleColor = ConsoleColor.DarkYellow;
break;
case LogLevel.Error:
consoleColor = ConsoleColor.DarkRed;
break;
}
writer.WriteWithColor(fmtMsg, ConsoleColor.Black, consoleColor);
};
});
#endregion
#region api日志
//Monitor日志配置
//services.AddMonitorLogging(options =>
//{
// options.JsonIndented = true;// 是否美化 JSON
// options.GlobalEnabled = false;//全局启用
// options.ConfigureLogger((logger, logContext, context) =>
// {
// var httpContext = context.HttpContext;//获取httpContext
// //获取客户端信息
// var client = App.GetService<IAppService>().UserAgent;
// // 获取控制器/操作描述器
// var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
// //操作名称默认是控制器名加方法名,自定义操作名称要在action上加Description特性
// var option = $"{controllerActionDescriptor.ControllerName}/{controllerActionDescriptor.ActionName}";
// var desc = App.CreateLocalizerByType(controllerActionDescriptor.ControllerTypeInfo.AsType())[controllerActionDescriptor.MethodInfo.Name];
// //获取特性
// option = desc.Value;//则将操作名称赋值为控制器上写的title
// logContext.Set(LoggingConst.CateGory, option);//传操作名称
// logContext.Set(LoggingConst.Operation, option);//传操作名称
// logContext.Set(LoggingConst.Client, client);//客户端信息
// logContext.Set(LoggingConst.Path, httpContext.Request.Path.Value);//请求地址
// logContext.Set(LoggingConst.Method, httpContext.Request.Method);//请求方法
// });
//});
//日志写入数据库配置
services.AddDatabaseLogging<DatabaseLoggingWriter>(options =>
{
options.WriteFilter = (logMsg) =>
{
return logMsg.LogName == "System.Logging.RequestAudit";
};
});
#endregion api日志
//已添加AddOptions
// 增加多语言支持配置信息

View File

@@ -21,13 +21,11 @@ using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using ThingsGateway.Admin.Application;
using ThingsGateway.Admin.Razor;
using ThingsGateway.Extension;
using ThingsGateway.NewLife.Caching;
using ThingsGateway.Razor;
using ThingsGateway.VirtualFileServer;
@@ -154,101 +152,9 @@ public class Startup : AppStartup
#region
services.AddConsoleFormatter(options =>
{
options.WriteFilter = (logMsg) =>
{
if (App.HostApplicationLifetime.ApplicationStopping.IsCancellationRequested && logMsg.LogLevel >= LogLevel.Warning) return false;
if (string.IsNullOrEmpty(logMsg.Message)) return false;
else return true;
};
options.MessageFormat = (logMsg) =>
{
//如果不是LoggingMonitor日志才格式化
if (logMsg.LogName != "System.Logging.LoggingMonitor")
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine("【日志级别】:" + logMsg.LogLevel);
stringBuilder.AppendLine("【日志类名】:" + logMsg.LogName);
stringBuilder.AppendLine("【日志时间】:" + DateTime.Now.ToDefaultDateTimeFormat());
stringBuilder.AppendLine("【日志内容】:" + logMsg.Message);
if (logMsg.Exception != null)
{
stringBuilder.AppendLine("【异常信息】:" + logMsg.Exception);
}
return stringBuilder.ToString();
}
else
{
return logMsg.Message;
}
};
options.WriteHandler = (logMsg, scopeProvider, writer, fmtMsg, opt) =>
{
ConsoleColor consoleColor = ConsoleColor.White;
switch (logMsg.LogLevel)
{
case LogLevel.Information:
consoleColor = ConsoleColor.DarkGreen;
break;
case LogLevel.Warning:
consoleColor = ConsoleColor.DarkYellow;
break;
case LogLevel.Error:
consoleColor = ConsoleColor.DarkRed;
break;
}
writer.WriteWithColor(fmtMsg, ConsoleColor.Black, consoleColor);
};
});
#endregion
#region api日志
//Monitor日志配置
//services.AddMonitorLogging(options =>
//{
// options.JsonIndented = true;// 是否美化 JSON
// options.GlobalEnabled = false;//全局启用
// options.ConfigureLogger((logger, logContext, context) =>
// {
// var httpContext = context.HttpContext;//获取httpContext
// //获取客户端信息
// var userAgent = App.GetService<IAppService>().UserAgent;
// // 获取控制器/操作描述器
// var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
// //操作名称默认是控制器名加方法名,自定义操作名称要在action上加Description特性
// var option = $"{controllerActionDescriptor.ControllerName}/{controllerActionDescriptor.ActionName}";
// var desc = App.CreateLocalizerByType(controllerActionDescriptor.ControllerTypeInfo.AsType())[controllerActionDescriptor.MethodInfo.Name];
// //获取特性
// option = desc.Value;//则将操作名称赋值为控制器上写的title
// logContext.Set(LoggingConst.CateGory, option);//传操作名称
// logContext.Set(LoggingConst.Operation, option);//传操作名称
// logContext.Set(LoggingConst.Client, userAgent);//客户端信息
// logContext.Set(LoggingConst.Path, httpContext.Request.Path.Value);//请求地址
// logContext.Set(LoggingConst.Method, httpContext.Request.Method);//请求方法
// });
//});
//日志写入数据库配置
services.AddDatabaseLogging<DatabaseLoggingWriter>(options =>
{
options.WriteFilter = (logMsg) =>
{
return logMsg.LogName == "System.Logging.RequestAudit";
};
});
#endregion api日志
//已添加AddOptions
// 增加多语言支持配置信息

View File

@@ -21,11 +21,9 @@ using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using ThingsGateway.Extension;
using ThingsGateway.VirtualFileServer;
namespace ThingsGateway.UpgradeServer;
@@ -148,101 +146,9 @@ public class Startup : AppStartup
#region
services.AddConsoleFormatter(options =>
{
options.WriteFilter = (logMsg) =>
{
if (App.HostApplicationLifetime.ApplicationStopping.IsCancellationRequested && logMsg.LogLevel >= LogLevel.Warning) return false;
if (string.IsNullOrEmpty(logMsg.Message)) return false;
else return true;
};
options.MessageFormat = (logMsg) =>
{
//如果不是LoggingMonitor日志才格式化
if (logMsg.LogName != "System.Logging.LoggingMonitor")
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine("【日志级别】:" + logMsg.LogLevel);
stringBuilder.AppendLine("【日志类名】:" + logMsg.LogName);
stringBuilder.AppendLine("【日志时间】:" + DateTime.Now.ToDefaultDateTimeFormat());
stringBuilder.AppendLine("【日志内容】:" + logMsg.Message);
if (logMsg.Exception != null)
{
stringBuilder.AppendLine("【异常信息】:" + logMsg.Exception);
}
return stringBuilder.ToString();
}
else
{
return logMsg.Message;
}
};
options.WriteHandler = (logMsg, scopeProvider, writer, fmtMsg, opt) =>
{
ConsoleColor consoleColor = ConsoleColor.White;
switch (logMsg.LogLevel)
{
case LogLevel.Information:
consoleColor = ConsoleColor.DarkGreen;
break;
case LogLevel.Warning:
consoleColor = ConsoleColor.DarkYellow;
break;
case LogLevel.Error:
consoleColor = ConsoleColor.DarkRed;
break;
}
writer.WriteWithColor(fmtMsg, ConsoleColor.Black, consoleColor);
};
});
#endregion
#region api日志
//Monitor日志配置
//services.AddMonitorLogging(options =>
//{
// options.JsonIndented = true;// 是否美化 JSON
// options.GlobalEnabled = false;//全局启用
// options.ConfigureLogger((logger, logContext, context) =>
// {
// var httpContext = context.HttpContext;//获取httpContext
// //获取客户端信息
// var client = App.GetService<IAppService>().UserAgent;
// // 获取控制器/操作描述器
// var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
// //操作名称默认是控制器名加方法名,自定义操作名称要在action上加Description特性
// var option = $"{controllerActionDescriptor.ControllerName}/{controllerActionDescriptor.ActionName}";
// var desc = App.CreateLocalizerByType(controllerActionDescriptor.ControllerTypeInfo.AsType())[controllerActionDescriptor.MethodInfo.Name];
// //获取特性
// option = desc.Value;//则将操作名称赋值为控制器上写的title
// logContext.Set(LoggingConst.CateGory, option);//传操作名称
// logContext.Set(LoggingConst.Operation, option);//传操作名称
// logContext.Set(LoggingConst.Client, client);//客户端信息
// logContext.Set(LoggingConst.Path, httpContext.Request.Path.Value);//请求地址
// logContext.Set(LoggingConst.Method, httpContext.Request.Method);//请求方法
// });
//});
//日志写入数据库配置
services.AddDatabaseLogging<DatabaseLoggingWriter>(options =>
{
options.WriteFilter = (logMsg) =>
{
return logMsg.LogName == "System.Logging.RequestAudit";
};
});
#endregion api日志
//已添加AddOptions
// 增加多语言支持配置信息

View File

@@ -1,6 +1,6 @@
<Project>
<PropertyGroup>
<Version>10.9.6</Version>
<Version>10.9.7</Version>
</PropertyGroup>
<ItemGroup>