添加Nlog服务

This commit is contained in:
2025-09-04 14:46:50 +08:00
parent bc8bc58d9b
commit 653a1d8749
9 changed files with 399 additions and 38 deletions

View File

@@ -6,16 +6,9 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<None Update="Configurations\nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.5" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="NLog" Version="6.0.0" />
<PackageReference Include="NLog.Database" Version="6.0.0" />

View File

@@ -1,5 +1,5 @@
<Application
x:Class="DMS.App"
x:Class="DMS.WPF.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

View File

@@ -3,31 +3,30 @@ using AutoMapper.Internal;
using DMS.Application.Interfaces;
using DMS.Application.Services;
using DMS.Application.Services.Processors;
using DMS.Core.Enums;
using DMS.Core.Interfaces;
using DMS.Core.Interfaces.Repositories;
using DMS.Core.Interfaces.Services;
using DMS.Helper;
using DMS.WPF.ViewModels;
using DMS.WPF.Views;
using iNKORE.UI.WPF.Modern.Common.IconKeys;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using DMS.Extensions;
using DMS.Infrastructure.Configurations;
using DMS.Infrastructure.Data;
using DMS.Infrastructure.Interfaces.Services;
using DMS.Infrastructure.Repositories;
using DMS.Infrastructure.Services;
using Microsoft.Extensions.Hosting;
using DMS.WPF.Helper;
using DMS.WPF.Services;
using DMS.WPF.ViewModels.Dialogs;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
using DMS.Core.Interfaces.Services;
using DMS.Infrastructure.Interfaces.Services;
using DMS.WPF.Interfaces;
using DMS.WPF.Logging;
using DMS.WPF.Services;
using DMS.WPF.ViewModels;
using DMS.WPF.ViewModels.Dialogs;
using DMS.WPF.Views;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog;
using ILogger = Microsoft.Extensions.Logging.ILogger;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
namespace DMS;
namespace DMS.WPF;
/// <summary>
/// Interaction logic for App.xaml
@@ -65,10 +64,6 @@ public partial class App : System.Windows.Application
try
{
// var databaseInitializer = Host.Services.GetRequiredService<DatabaseInitializerService>();
// databaseInitializer.InitializeDataBase();
// await databaseInitializer.InitializeMenu();
// Settings = AppSettings.Load();
Host.Services.GetRequiredService<GrowlNotificationService>();
// 初始化数据处理链
@@ -110,17 +105,14 @@ public partial class App : System.Windows.Application
private void ConfigureServices(IServiceCollection services)
{
// services.AddTransient<IDbContext,SqlSugarDbContext>();
// 注册NLogLogger作为Microsoft.Extensions.Logging.ILogger的实现
services.AddSingleton<ILogger, NLogLogger>();
services.AddSingleton<ILoggerFactory, NLogLoggerFactory>();
//
//
// services.AddSingleton<IDeviceDataService, DeviceDataService>();
// services.AddSingleton<NavgatorServices>();
// //services.AddSingleton<IDialogService, DialogService>();
services.AddSingleton<GrowlNotificationService>();
// services.AddHostedService<S7BackgroundService>();
// services.AddHostedService<OpcUaBackgroundService>();
// services.AddHostedService<DMS.Infrastructure.Services.MqttBackgroundService>();
//
// --- 核心配置 ---
services.AddAutoMapper(cfg =>
@@ -204,7 +196,7 @@ public partial class App : System.Windows.Application
private void ConfigureLogging(ILoggingBuilder loggingBuilder)
{
LogManager.Setup().LoadConfigurationFromFile("Config/nlog.config");
LogManager.Setup().LoadConfigurationFromFile("Configurations/nlog.config");
loggingBuilder.ClearProviders();
loggingBuilder.SetMinimumLevel(LogLevel.Trace);
// loggingBuilder.AddNLog();

View File

@@ -26,9 +26,9 @@
<target name="database"
xsi:type="Database"
dbProvider="MySql.Data.MySqlClient.MySqlConnection, MySql.Data"
connectionString="server=127.0.0.1;port=3306;user=root;password=Pgw15221236646; database=pmswpf; ">
connectionString="server=127.0.0.1;port=3306;user=root;password=Pgw15221236646; database=dms_test; ">
<commandText>
INSERT INTO nlog (
INSERT INTO dbnlog (
LogTime, Level, ThreadID,ThreadName,Callsite,CallsiteLineNumber,Message,
Logger, Exception, CallerFilePath, CallerLineNumber,CallerMember
) VALUES (

View File

@@ -154,6 +154,8 @@
<PackageReference Include="Hardcodet.NotifyIcon.Wpf" Version="2.0.1" />
<PackageReference Include="iNKORE.UI.WPF.Modern" Version="0.10.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.5" />
<PackageReference Include="NLog" Version="6.0.0" />
<PackageReference Include="ObservableCollections" Version="3.3.4" />
</ItemGroup>
@@ -168,4 +170,11 @@
<Folder Include="ViewModels\Items\" />
</ItemGroup>
<ItemGroup>
<None Update="Configurations\nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,210 @@
using System;
using System.Collections.Concurrent;
using System.Threading;
using Microsoft.Extensions.Logging;
using NLog;
using ILogger = Microsoft.Extensions.Logging.ILogger;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
using NLogLevel = NLog.LogLevel;
namespace DMS.WPF.Logging;
/// <summary>
/// NLog日志服务实现直接使用NLog记录日志并实现Microsoft.Extensions.Logging.ILogger接口
/// </summary>
public class NLogLogger : ILogger
{
/// <summary>
/// 获取当前类的 NLog 日志实例。
/// </summary>
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
/// <summary>
/// 日志记录器名称
/// </summary>
private readonly string _name;
public NLogLogger()
{
_name = nameof(NLogLogger);
}
public NLogLogger(string name)
{
_name = name;
}
/// <summary>
/// 内部类,用于存储节流日志的状态信息。
/// </summary>
private class ThrottledLogInfo
{
/// <summary>
/// 日志在节流时间窗口内的调用次数。
/// 使用 int 类型,并通过 Interlocked.Increment 进行原子性递增,确保线程安全。
/// </summary>
public int Count;
/// <summary>
/// 用于在节流时间结束后执行操作的计时器。
/// </summary>
public Timer Timer;
}
/// <summary>
/// 线程安全的字典,用于存储正在被节流的日志。
/// 键 (string) 是根据日志消息生成的唯一标识。
/// 值 (ThrottledLogInfo) 是该日志的节流状态信息。
/// </summary>
private static readonly ConcurrentDictionary<string, ThrottledLogInfo> ThrottledLogs = new ConcurrentDictionary<string, ThrottledLogInfo>();
/// <summary>
/// 定义节流的时间窗口(单位:秒)。
/// </summary>
private const int ThrottleTimeSeconds = 30;
/// <summary>
/// 内部核心日志记录方法,包含了节流逻辑。
/// </summary>
/// <param name="msg">日志消息内容。</param>
/// <param name="level">NLog 的日志级别。</param>
/// <param name="exception">可选的异常对象。</param>
/// <param name="throttle">是否启用节流。</param>
private void LogInternal(string msg, NLogLevel level, Exception exception, bool throttle)
{
// 如果不启用节流,则直接记录日志并返回。
if (!throttle)
{
Logger.Log(level, exception, msg);
return;
}
// 使用消息内容生成唯一键,以区分不同的日志来源。
var key = msg;
// 使用 AddOrUpdate 实现原子操作,确保线程安全。
// 它会尝试添加一个新的节流日志条目,如果键已存在,则更新现有条目。
ThrottledLogs.AddOrUpdate(
key,
// --- 添加逻辑 (addValueFactory):当日志第一次被节流时执行 ---
_ =>
{
// 1. 首次出现,立即记录一次原始日志。
Logger.Log(level, exception, msg);
// 2. 创建一个新的节流信息对象。
var newThrottledLog = new ThrottledLogInfo
{
Count = 1
};
// 3. 创建并启动一个一次性计时器。
newThrottledLog.Timer = new Timer(s =>
{
// --- 计时器回调在指定时间例如30秒后触发 ---
// 尝试从字典中移除当前日志条目。
if (ThrottledLogs.TryRemove(key, out var finishedLog))
{
// 释放计时器资源。
finishedLog.Timer.Dispose();
// 如果在节流期间有后续调用Count > 1则记录一条摘要日志。
if (finishedLog.Count > 1)
{
var summaryMsg = $"日志 '{msg}' 在过去 {ThrottleTimeSeconds} 秒内被调用 {finishedLog.Count} 次。";
Logger.Log(level, summaryMsg);
}
}
}, null, ThrottleTimeSeconds * 1000, Timeout.Infinite); // 设置30秒后触发且不重复。
return newThrottledLog;
},
// --- 更新逻辑 (updateValueFactory):当日志在节流窗口内再次被调用时执行 ---
(_, existingLog) =>
{
// 只需将调用次数加一。使用 Interlocked.Increment 保证原子操作,避免多线程下的竞态条件。
Interlocked.Increment(ref existingLog.Count);
return existingLog;
});
}
public IDisposable BeginScope<TState>(TState state)
{
return null; // NLog不直接支持作用域
}
public bool IsEnabled(LogLevel logLevel)
{
return Logger.IsEnabled(ToNLogLevel(logLevel));
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
return;
var message = formatter(state, exception);
var nlogLevel = ToNLogLevel(logLevel);
switch (logLevel)
{
case LogLevel.Trace:
LogInternal(message, nlogLevel, exception, false);
break;
case LogLevel.Debug:
LogInternal(message, nlogLevel, exception, false);
break;
case LogLevel.Information:
LogInternal(message, nlogLevel, exception, false);
break;
case LogLevel.Warning:
LogInternal(message, nlogLevel, exception, false);
break;
case LogLevel.Error:
LogInternal(message, nlogLevel, exception, false);
break;
case LogLevel.Critical:
LogInternal($"[Critical] {message}", nlogLevel, exception, false);
break;
}
}
private NLogLevel ToNLogLevel(LogLevel logLevel)
{
return logLevel switch
{
LogLevel.Trace => NLogLevel.Trace,
LogLevel.Debug => NLogLevel.Debug,
LogLevel.Information => NLogLevel.Info,
LogLevel.Warning => NLogLevel.Warn,
LogLevel.Error => NLogLevel.Error,
LogLevel.Critical => NLogLevel.Fatal,
_ => NLogLevel.Debug
};
}
// 保持原有的自定义方法以提供向后兼容性
public void LogError(string message, Exception exception = null)
{
LogInternal(message, NLogLevel.Error, exception, true);
}
public void LogInfo(string message)
{
LogInternal(message, NLogLevel.Info, null, true);
}
public void LogWarning(string message)
{
LogInternal(message, NLogLevel.Warn, null, true);
}
public void LogDebug(string message)
{
LogInternal(message, NLogLevel.Debug, null, true);
}
public void LogTrace(string message)
{
LogInternal(message, NLogLevel.Trace, null, true);
}
}

View File

@@ -0,0 +1,38 @@
using Microsoft.Extensions.Logging;
namespace DMS.WPF.Logging;
/// <summary>
/// NLog ILoggerFactory实现用于创建命名的NLogLogger实例
/// 这个工厂类允许通过类别名称创建不同的Logger实例
/// 从而可以区分不同组件或模块的日志输出
/// </summary>
public class NLogLoggerFactory : ILoggerFactory
{
/// <summary>
/// 添加日志提供程序NLog不使用此机制保留为空实现
/// </summary>
/// <param name="provider">日志提供程序</param>
public void AddProvider(ILoggerProvider provider)
{
// NLog不使用providers机制所以这里留空
}
/// <summary>
/// 创建指定类别的Logger实例
/// </summary>
/// <param name="categoryName">日志类别名称(通常是类的全名)</param>
/// <returns>ILogger实例</returns>
public ILogger CreateLogger(string categoryName)
{
return new NLogLogger(categoryName);
}
/// <summary>
/// 释放资源
/// </summary>
public void Dispose()
{
// 清理资源(如果需要)
}
}

View File

@@ -7,8 +7,10 @@ using DMS.WPF.Services;
using System;
using System.Threading.Tasks;
using DMS.Application.Services;
using DMS.WPF.Helper;
using DMS.WPF.Views;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace DMS.WPF.ViewModels;
@@ -17,6 +19,7 @@ namespace DMS.WPF.ViewModels;
/// </summary>
public partial class SplashViewModel : ObservableObject
{
private readonly ILogger _logger;
private readonly IServiceProvider _serviceProvider;
private readonly IInitializeService _initializeService;
private readonly IDataCenterService _dataCenterService;
@@ -25,9 +28,10 @@ public partial class SplashViewModel : ObservableObject
[ObservableProperty]
private string _loadingMessage = "正在加载...";
public SplashViewModel(IServiceProvider serviceProvider, IInitializeService initializeService,
public SplashViewModel( ILogger logger,IServiceProvider serviceProvider, IInitializeService initializeService,
IDataCenterService dataCenterService, DataServices dataServices)
{
_logger = logger;
_serviceProvider = serviceProvider;
_initializeService = initializeService;
this._dataCenterService = dataCenterService;
@@ -41,6 +45,8 @@ public partial class SplashViewModel : ObservableObject
{
try
{
_logger.LogInformation("正在初始化数据库...");
LoadingMessage = "正在初始化数据库...";
_initializeService.InitializeTables();
_initializeService.InitializeMenus();

View File

@@ -0,0 +1,113 @@
# DMS日志服务使用说明
## 概述
DMS项目现在支持Microsoft.Extensions.Logging.ILogger接口的日志服务
1. NLogLogger类直接实现Microsoft.Extensions.Logging.ILogger接口位于DMS.WPF项目中
2. 提供ILoggerFactory用于创建命名的Logger实例位于DMS.WPF项目中
## 如何注册日志服务
`Startup.cs`或程序的依赖注入配置中,使用以下扩展方法注册日志服务:
```csharp
using DMS.Application;
// 在ConfigureServices方法中
services.AddDmsServices();
```
这将注册以下服务:
- `Microsoft.Extensions.Logging.ILogger` 接口及其实现 `NLogLogger`单例位于DMS.WPF.Logging命名空间
- `Microsoft.Extensions.Logging.ILoggerFactory` 接口及其实现 `NLogLoggerFactory`单例位于DMS.WPF.Logging命名空间
## 如何使用日志服务
### 1. 使用构造函数注入ILogger推荐
```csharp
using Microsoft.Extensions.Logging;
public class MyService
{
private readonly ILogger<MyService> _logger;
public MyService(ILogger<MyService> logger)
{
_logger = logger;
}
public void DoSomething()
{
_logger.LogInformation("正在执行操作...");
try
{
// 业务逻辑
}
catch (Exception ex)
{
_logger.LogError(ex, "操作失败");
}
}
}
```
### 2. 使用ILoggerFactory创建命名的Logger
```csharp
using Microsoft.Extensions.Logging;
public class MyService
{
private readonly ILogger _logger;
public MyService(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger("MyService");
}
public void DoSomething()
{
_logger.LogInformation("正在执行操作...");
try
{
// 业务逻辑
}
catch (Exception ex)
{
_logger.LogError(ex, "操作失败");
}
}
}
```
## NLogLoggerFactory的作用
`NLogLoggerFactory``ILoggerFactory`接口的实现,主要作用是:
1. **创建命名的Logger实例**:通过`CreateLogger(string categoryName)`方法可以为不同的类或模块创建具有特定名称的Logger实例
2. **支持依赖注入**:作为服务注册后,其他类可以通过构造函数注入`ILoggerFactory`来创建Logger实例
3. **符合标准**实现Microsoft.Extensions.Logging标准确保与其他.NET日志组件兼容
## 日志级别映射
Microsoft.Extensions.Logging与NLog之间的日志级别映射如下
| Microsoft.Extensions.Logging | NLog |
|-----------------------------|----------|
| Trace | Trace |
| Debug | Debug |
| Information | Info |
| Warning | Warn |
| Error | Error |
| Critical | Fatal |
## 节流功能
NLogLogger提供了节流功能以防止在短时间内产生大量重复的日志日志风暴。默认情况下所有日志都会启用节流节流时间窗口为30秒。
## 配置
NLog的配置文件位于 `DMS.Core\Configurations\nlog.config`,可以根据需要进行修改。