添加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

@@ -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

@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
autoReload="true"
internalLogLevel="Info"
internalLogFile="internal-nlog.txt">
<targets>
<!-- 文件日志 -->
<target name="logfile"
xsi:type="File"
fileName="logs/${shortdate}.log"
layout="${longdate} ThreadID=${threadid} ${level:uppercase=true} ${logger} ${mdlc:CallerFilePath} ${mdlc:CallerLineNumber:whenEmpty=0} ${mdlc:CallerMember} ${message} ${exception:format=tostring}"
archiveFileName="logs/archives/{#}.log"
archiveEvery="Day"
archiveNumbering="Rolling"
maxArchiveFiles="30"/>
<!-- 控制台日志 -->
<target name="logconsole"
xsi:type="Console"
layout="${date:format=HH\:mm\:ss} ${level} ${threadid} ${message}${exception:format=tostring}"/>
<!-- SQL Server 目标 -->
<!-- 异步写入日志到数据库 -->
<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=dms_test; ">
<commandText>
INSERT INTO dbnlog (
LogTime, Level, ThreadID,ThreadName,Callsite,CallsiteLineNumber,Message,
Logger, Exception, CallerFilePath, CallerLineNumber,CallerMember
) VALUES (
@LogTime, @Level,@ThreadID,@ThreadName,@Callsite,@CallsiteLineNumber,@Message,
@Logger, @Exception, @CallerFilePath, @CallerLineNumber,@CallerMember
)
</commandText>
<!-- 参数映射 -->
<parameter name="@LogTime" layout="${date:format=yyyy-MM-dd HH\:mm\:ss}"/>
<parameter name="@Level" layout="${level}"/>
<parameter name="@ThreadID" layout="${threadid}" dbType="Int32"/>
<parameter name="@ThreadName" layout="${threadname}"/>
<parameter name="@Message" layout="${message}"/>
<parameter name="@Callsite" layout="${callsite}"/>
<parameter name="@Logger" layout="${logger}"/>
<parameter name="@Exception" layout="${exception:format=ToString}"/>
<parameter name="@CallsiteLineNumber" layout="${callsite-linenumber:whenEmpty=0}"/>
<parameter name="@CallerFilePath" layout="${mdlc:CallerFilePath}"/>
<parameter name="@CallerLineNumber" layout="${mdlc:CallerLineNumber:whenEmpty=0}"/>
<parameter name="@CallerMember" layout="${mdlc:CallerMember}"/>
</target>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="logconsole"/>
<logger name="*" minlevel="Info" writeTo="logfile"/>
<!-- 路由日志到数据库 -->
<logger name="*" minlevel="Info" writeTo="database"/>
</rules>
</nlog>

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();