From d3e7a86b0750fba7a236652abd810bec6464fceb Mon Sep 17 00:00:00 2001 From: wenjy Date: Thu, 26 Dec 2024 08:58:45 +0800 Subject: [PATCH] =?UTF-8?q?change=20-=20=E6=B7=BB=E5=8A=A0Serilog=E8=87=AA?= =?UTF-8?q?=E5=AE=9A=E4=B9=89log=E6=96=87=E4=BB=B6=EF=BC=8C=E4=BF=AE?= =?UTF-8?q?=E6=94=B9BaseBusiness=E6=B3=A8=E5=85=A5=E6=96=B9=E5=BC=8F?= =?UTF-8?q?=EF=BC=8C=E7=9B=B4=E6=8E=A5=E6=B3=A8=E5=85=A5IServiceProvider?= =?UTF-8?q?=E5=AE=B9=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SlnMesnac.Business/base/BaseBusiness.cs | 17 ++- .../Templates/Service/IServiceCreate.cs | 2 +- .../Templates/Service/Impl/ServiceCreate.cs | 2 +- SlnMesnac.Mqtt/MqttClient.cs | 25 ++-- SlnMesnac.Quartz/Job/Job2.cs | 7 +- SlnMesnac.Quartz/Job/MyJob.cs | 7 +- SlnMesnac.Quartz/SlnMesnac.Quartz.csproj | 4 + SlnMesnac.Redis/RedisHandler.cs | 9 +- SlnMesnac.Redis/SlnMesnac.Redis.csproj | 1 + .../SlnMesnac.Repository.csproj | 1 + .../service/Impl/BaseMaterialServiceImpl.cs | 13 ++- .../service/Impl/BaseUserServiceImpl.cs | 9 +- SlnMesnac.Rfid/Factory/RflyFactory.cs | 11 +- SlnMesnac.Serilog/SerilogExtensions.cs | 29 ++++- SlnMesnac.Serilog/SerilogHelper.cs | 108 ++++++++++++++++++ SlnMesnac.TouchSocket/TcpServer.cs | 15 +-- .../ViewModel/MainWindowViewModel.cs | 9 +- .../Controllers/BaseMaterialInfoController.cs | 11 +- SlnMesnac/Controllers/BaseUserController.cs | 9 +- 19 files changed, 220 insertions(+), 69 deletions(-) create mode 100644 SlnMesnac.Serilog/SerilogHelper.cs diff --git a/SlnMesnac.Business/base/BaseBusiness.cs b/SlnMesnac.Business/base/BaseBusiness.cs index 644ff4d..4dd7e89 100644 --- a/SlnMesnac.Business/base/BaseBusiness.cs +++ b/SlnMesnac.Business/base/BaseBusiness.cs @@ -1,5 +1,7 @@ -using SlnMesnac.Plc; +using Microsoft.Extensions.DependencyInjection; +using SlnMesnac.Plc; using SlnMesnac.Rfid; +using SlnMesnac.Serilog; using System; using System.Collections.Generic; using System.Linq; @@ -35,10 +37,17 @@ namespace SlnMesnac.Business.@base private readonly List _rfidFactories; - public BaseBusiness(List plcFactories, List rfidFactories) + private IServiceProvider _serviceProvider; + + public BaseBusiness(IServiceProvider serviceProvider) { - _plcFactories = plcFactories; - _rfidFactories = rfidFactories; + _serviceProvider = serviceProvider; + + using (var scope = _serviceProvider.CreateScope()) + { + _plcFactories = scope.ServiceProvider.GetRequiredService>(); + _rfidFactories = scope.ServiceProvider.GetRequiredService>(); + } } /// diff --git a/SlnMesnac.Generate/Templates/Service/IServiceCreate.cs b/SlnMesnac.Generate/Templates/Service/IServiceCreate.cs index 272c376..1306e4c 100644 --- a/SlnMesnac.Generate/Templates/Service/IServiceCreate.cs +++ b/SlnMesnac.Generate/Templates/Service/IServiceCreate.cs @@ -33,7 +33,7 @@ namespace SlnMesnac.Generate.Templates.Service { public class IServiceCreate { - private static readonly string templateDir = @"E:\桌面\SlnMesnac\SlnMesnac.Generate\Templates\Service\"; + private static readonly string templateDir = @"F:\桌面\SlnMesnac\SlnMesnac.Generate\Templates\Service"; public bool Create(string tableName, string NameSpace, string outdir) { diff --git a/SlnMesnac.Generate/Templates/Service/Impl/ServiceCreate.cs b/SlnMesnac.Generate/Templates/Service/Impl/ServiceCreate.cs index 14830ea..0aa6838 100644 --- a/SlnMesnac.Generate/Templates/Service/Impl/ServiceCreate.cs +++ b/SlnMesnac.Generate/Templates/Service/Impl/ServiceCreate.cs @@ -33,7 +33,7 @@ namespace SlnMesnac.Generate.Templates.Service.Impl { public class ServiceCreate { - private static readonly string templateDir = @"E:\桌面\SlnMesnac\SlnMesnac.Generate\Templates\Service\Impl\"; + private static readonly string templateDir = @"F:\桌面\SlnMesnac\SlnMesnac.Generate\Templates\Service\Impl\"; public bool Create(string tableName, string NameSpace, string outdir) { diff --git a/SlnMesnac.Mqtt/MqttClient.cs b/SlnMesnac.Mqtt/MqttClient.cs index 44baecf..c80618e 100644 --- a/SlnMesnac.Mqtt/MqttClient.cs +++ b/SlnMesnac.Mqtt/MqttClient.cs @@ -6,6 +6,7 @@ using MQTTnet.Client; using System.Security.Authentication; using MQTTnet; using Microsoft.Extensions.Logging; +using SlnMesnac.Serilog; #region << 版 本 注 释 >> /*-------------------------------------------------------------------- @@ -36,11 +37,11 @@ namespace SlnMesnac.Mqtt /// public class MqttClient { - private ILogger _logger; + public readonly SerilogHelper _logger; private IMqttClient _client; - public MqttClient(ILogger logger) + public MqttClient(SerilogHelper logger) { _logger = logger; } @@ -78,17 +79,17 @@ namespace SlnMesnac.Mqtt { if (result.ResultCode == MQTTnet.Client.MqttClientConnectResultCode.Success) { - _logger.LogInformation($"连接服务器成功{ip}:{port}"); + _logger.Info($"连接服务器成功{ip}:{port}"); } else { - _logger.LogInformation($"连接服务器失败"); + _logger.Info($"连接服务器失败"); } } } catch (Exception ex) { - _logger.LogError("连接服务器异常",ex); + _logger.Error("连接服务器异常",ex); } } @@ -98,7 +99,7 @@ namespace SlnMesnac.Mqtt public void DisConnect() { _client.DisconnectAsync(); - _logger.LogInformation($"断开连接"); + _logger.Info($"断开连接"); } /// @@ -120,11 +121,11 @@ namespace SlnMesnac.Mqtt MqttClientSubscribeResult result = await _client.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None); - _logger.LogInformation($"订阅主题:{topic}"); + _logger.Info($"订阅主题:{topic}"); } catch (Exception ex) { - _logger.LogError("订阅主题异常",ex); + _logger.Error("订阅主题异常",ex); } } @@ -135,7 +136,7 @@ namespace SlnMesnac.Mqtt public void Unsubscribe(string topic) { _client.UnsubscribeAsync(topic); - _logger.LogInformation($"取消订阅,主题:{topic}"); + _logger.Info($"取消订阅,主题:{topic}"); } /// @@ -150,18 +151,18 @@ namespace SlnMesnac.Mqtt var msg = new MqttApplicationMessageBuilder().WithTopic(topic).WithPayload(message) .Build(); _client.PublishAsync(msg, CancellationToken.None); - _logger.LogInformation($"向服务端推送成功,主题:{topic};内容:{message}"); + _logger.Info($"向服务端推送成功,主题:{topic};内容:{message}"); } catch (Exception ex) { - _logger.LogError("向服务端推送消息异常",ex); + _logger.Error("向服务端推送消息异常",ex); } } private async Task MqttClient_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs eventArgs) { var info = $"接收到主题:{eventArgs.ApplicationMessage.Topic}的消息,内容:{Encoding.UTF8.GetString(eventArgs.ApplicationMessage.Payload)}"; - _logger.LogInformation(info); + _logger.Info(info); } } diff --git a/SlnMesnac.Quartz/Job/Job2.cs b/SlnMesnac.Quartz/Job/Job2.cs index cba1528..cf4623c 100644 --- a/SlnMesnac.Quartz/Job/Job2.cs +++ b/SlnMesnac.Quartz/Job/Job2.cs @@ -1,5 +1,6 @@ using Microsoft.Extensions.Logging; using Quartz; +using SlnMesnac.Serilog; using System; using System.Collections.Generic; using System.Text; @@ -31,16 +32,16 @@ namespace SlnMesnac.Quartz.Job { internal class Job2 : IJob { - private readonly ILogger _logger; + private readonly SerilogHelper _logger; - public Job2(ILogger logger) + public Job2(SerilogHelper logger) { _logger = logger; } public Task Execute(IJobExecutionContext context) { - _logger.LogInformation($"执行Job2:{DateTime.Now.ToString("HH:mm:ss")}"); + _logger.Info($"执行Job2:{DateTime.Now.ToString("HH:mm:ss")}"); return Task.CompletedTask; } } diff --git a/SlnMesnac.Quartz/Job/MyJob.cs b/SlnMesnac.Quartz/Job/MyJob.cs index 735f08c..e12d7ba 100644 --- a/SlnMesnac.Quartz/Job/MyJob.cs +++ b/SlnMesnac.Quartz/Job/MyJob.cs @@ -1,5 +1,6 @@ using Microsoft.Extensions.Logging; using Quartz; +using SlnMesnac.Serilog; using System; using System.Collections.Generic; using System.Text; @@ -31,16 +32,16 @@ namespace SlnMesnac.Quartz.Job { public class MyJob : IJob { - private readonly ILogger _logger; + private readonly SerilogHelper _logger; - public MyJob(ILogger logger) + public MyJob(SerilogHelper logger) { _logger = logger; } public Task Execute(IJobExecutionContext context) { - _logger.LogInformation($"执行MyJob:{DateTime.Now.ToString("HH:mm:ss")}"); + _logger.Info($"执行MyJob:{DateTime.Now.ToString("HH:mm:ss")}"); return Task.CompletedTask; } } diff --git a/SlnMesnac.Quartz/SlnMesnac.Quartz.csproj b/SlnMesnac.Quartz/SlnMesnac.Quartz.csproj index 1040f6c..344e515 100644 --- a/SlnMesnac.Quartz/SlnMesnac.Quartz.csproj +++ b/SlnMesnac.Quartz/SlnMesnac.Quartz.csproj @@ -10,4 +10,8 @@ + + + + diff --git a/SlnMesnac.Redis/RedisHandler.cs b/SlnMesnac.Redis/RedisHandler.cs index 4b0331c..7501351 100644 --- a/SlnMesnac.Redis/RedisHandler.cs +++ b/SlnMesnac.Redis/RedisHandler.cs @@ -1,5 +1,6 @@ using Microsoft.Extensions.Logging; using SlnMesnac.Config; +using SlnMesnac.Serilog; using StackExchange.Redis; using System; using System.Collections.Generic; @@ -31,7 +32,7 @@ namespace SlnMesnac.Redis { public class RedisHandler { - private ILogger _logger; + private SerilogHelper _logger; private readonly AppConfig _appConfig; @@ -39,7 +40,7 @@ namespace SlnMesnac.Redis private readonly ConnectionMultiplexer redis; - public RedisHandler(AppConfig appConfig, ILogger logger) + public RedisHandler(AppConfig appConfig, SerilogHelper logger) { _appConfig = appConfig; @@ -59,7 +60,7 @@ namespace SlnMesnac.Redis { long res = _subscriber.Publish(channel, message); - _logger.LogInformation($"向主题:{channel};推送消息:{message};结果:{res}"); + _logger.Info($"向主题:{channel};推送消息:{message};结果:{res}"); } /// @@ -72,7 +73,7 @@ namespace SlnMesnac.Redis _subscriber.Subscribe(channel, (ch, message) => { onMessageReceived(ch, message); - _logger.LogInformation($"订阅主题:{channel};收到主题:{ch};推送的消息:{message}"); + _logger.Info($"订阅主题:{channel};收到主题:{ch};推送的消息:{message}"); }); } diff --git a/SlnMesnac.Redis/SlnMesnac.Redis.csproj b/SlnMesnac.Redis/SlnMesnac.Redis.csproj index 96001b0..9d4e6d6 100644 --- a/SlnMesnac.Redis/SlnMesnac.Redis.csproj +++ b/SlnMesnac.Redis/SlnMesnac.Redis.csproj @@ -11,6 +11,7 @@ + diff --git a/SlnMesnac.Repository/SlnMesnac.Repository.csproj b/SlnMesnac.Repository/SlnMesnac.Repository.csproj index b733819..50714c1 100644 --- a/SlnMesnac.Repository/SlnMesnac.Repository.csproj +++ b/SlnMesnac.Repository/SlnMesnac.Repository.csproj @@ -14,6 +14,7 @@ + diff --git a/SlnMesnac.Repository/service/Impl/BaseMaterialServiceImpl.cs b/SlnMesnac.Repository/service/Impl/BaseMaterialServiceImpl.cs index 82c5e2f..71e33bc 100644 --- a/SlnMesnac.Repository/service/Impl/BaseMaterialServiceImpl.cs +++ b/SlnMesnac.Repository/service/Impl/BaseMaterialServiceImpl.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Linq.Expressions; using System.Text; using SlnMesnac.Repository.service.@base; +using SlnMesnac.Serilog; #region << 版 本 注 释 >> /*-------------------------------------------------------------------- @@ -33,9 +34,9 @@ namespace SlnMesnac.Repository.service.Impl { public class BaseMaterialServiceImpl : BaseServiceImpl, IBaseMaterialService { - private ILogger _logger; + private SerilogHelper _logger; - public BaseMaterialServiceImpl(Repository repository, ILogger logger):base(repository) + public BaseMaterialServiceImpl(Repository repository, SerilogHelper logger) :base(repository) { _logger = logger; } @@ -54,7 +55,7 @@ namespace SlnMesnac.Repository.service.Impl } catch (Exception ex) { - _logger.LogError($"根据物料编号获取物料信息异常:{ex.Message}"); + _logger.Error($"根据物料编号获取物料信息异常:{ex.Message}"); } return materialInfo; } @@ -73,7 +74,7 @@ namespace SlnMesnac.Repository.service.Impl } catch (Exception ex) { - _logger.LogError($"根据SAP物料编号获取物料信息异常:{ex.Message}"); + _logger.Error($"根据SAP物料编号获取物料信息异常:{ex.Message}"); } return materialInfo; } @@ -91,7 +92,7 @@ namespace SlnMesnac.Repository.service.Impl } catch (Exception ex) { - _logger.LogError($"获取物料信息异常:{ex.Message}"); + _logger.Error($"获取物料信息异常:{ex.Message}"); } return materialInfos; } @@ -122,7 +123,7 @@ namespace SlnMesnac.Repository.service.Impl } catch (Exception ex) { - _logger.LogError($"通过物料类型获取物料信息异常:{ex.Message}"); + _logger.Error($"通过物料类型获取物料信息异常:{ex.Message}"); } return materialInfos; } diff --git a/SlnMesnac.Repository/service/Impl/BaseUserServiceImpl.cs b/SlnMesnac.Repository/service/Impl/BaseUserServiceImpl.cs index ee2b511..1e33e08 100644 --- a/SlnMesnac.Repository/service/Impl/BaseUserServiceImpl.cs +++ b/SlnMesnac.Repository/service/Impl/BaseUserServiceImpl.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.Logging; using SlnMesnac.Model.domain; using SlnMesnac.Repository.service.@base; +using SlnMesnac.Serilog; using System; using System.Collections.Generic; using System.Text; @@ -31,9 +32,9 @@ namespace SlnMesnac.Repository.service.Impl { public class BaseUserServiceImpl : BaseServiceImpl,IBaseUserService { - private readonly ILogger _logger; + private readonly SerilogHelper _logger; - public BaseUserServiceImpl(Repository rep,ILogger logger) :base(rep) + public BaseUserServiceImpl(Repository rep, SerilogHelper logger) :base(rep) { _logger = logger; } @@ -48,7 +49,7 @@ namespace SlnMesnac.Repository.service.Impl } catch (Exception ex) { - _logger.LogError($"获取用户信息异常{ex.Message}"); + _logger.Error($"获取用户信息异常{ex.Message}"); } return users; } @@ -67,7 +68,7 @@ namespace SlnMesnac.Repository.service.Impl catch (Exception ex) { base._rep.AsTenant().RollbackTran(); - _logger.LogError($"用户信息添加异常:{ex.Message}"); + _logger.Error($"用户信息添加异常:{ex.Message}"); } return result; } diff --git a/SlnMesnac.Rfid/Factory/RflyFactory.cs b/SlnMesnac.Rfid/Factory/RflyFactory.cs index 27f015a..5d9e63b 100644 --- a/SlnMesnac.Rfid/Factory/RflyFactory.cs +++ b/SlnMesnac.Rfid/Factory/RflyFactory.cs @@ -9,6 +9,7 @@ using SlnMesnac.Common; using SlnMesnac.Model.dto; using SlnMesnac.Rfid.Dto; using SlnMesnac.Rfid.Enum; +using SlnMesnac.Serilog; using TouchSocket.Core; using TouchSocket.Sockets; @@ -38,11 +39,11 @@ namespace SlnMesnac.Rfid.Factory { public class RflyFactory:RfidAbsractFactory { - private ILogger _logger; + private SerilogHelper _logger; private readonly TcpClient _tcpClient = new TcpClient(); private readonly StringChange _stringChange; - public RflyFactory(ILogger logger,StringChange stringChange) + public RflyFactory(SerilogHelper logger,StringChange stringChange) { _logger = logger; _stringChange = stringChange; @@ -106,7 +107,7 @@ namespace SlnMesnac.Rfid.Factory byte[] reciveBuffer = waitClient.SendThenReturn(pMessagePack.m_pData, timeout); - _logger.LogInformation($"接收原始报文:{_stringChange.bytesToHexStr(reciveBuffer,reciveBuffer.Length)}"); + _logger.Info($"接收原始报文:{_stringChange.bytesToHexStr(reciveBuffer,reciveBuffer.Length)}"); byte[] resultBuffer = PareReceiveBufferData(reciveBuffer,reciveBuffer.Length); @@ -417,12 +418,12 @@ namespace SlnMesnac.Rfid.Factory iFirstPC = iFirstAnt + 1; iFirstLeftBarcketPos = iFirstLeftBarcketPos + iBarcodeLength + 5; - _logger.LogInformation("----函数调用:Device_DealTagInfoList 第[" + (iCommonSecondFlag + 1) + "]次数据解析为:" + tag.EPCstring + ",读取标签次数:[" + tempDataCount + "],标签信号强度:[" + tempDataRSSI + "],天线号:[" + tempDataANT + "]"); + _logger.Info("----函数调用:Device_DealTagInfoList 第[" + (iCommonSecondFlag + 1) + "]次数据解析为:" + tag.EPCstring + ",读取标签次数:[" + tempDataCount + "],标签信号强度:[" + tempDataRSSI + "],天线号:[" + tempDataANT + "]"); iCommonSecondFlag++; if (iCommonSecondFlag == iBarcodeGroupCount) { mutauto.ReleaseMutex(); - _logger.LogInformation("《《《返回标签数据!"); + _logger.Info("《《《返回标签数据!"); return tagInfoList; } } diff --git a/SlnMesnac.Serilog/SerilogExtensions.cs b/SlnMesnac.Serilog/SerilogExtensions.cs index 6f9b303..f332ac4 100644 --- a/SlnMesnac.Serilog/SerilogExtensions.cs +++ b/SlnMesnac.Serilog/SerilogExtensions.cs @@ -42,15 +42,32 @@ namespace SlnMesnac.Serilog #region 通过配置文件读取日志存放位置 var appConfig = app.ApplicationServices.GetService(); - var logPath = $"{appConfig.logPath}/Logs/{DateTime.UtcNow:yyyy-MM-dd}/"; + var logPath = $"{appConfig.logPath}/Logs/"; + #endregion + //Log.Logger = new LoggerConfiguration().MinimumLevel.Information().WriteTo.Console() + // .WriteTo.File(Path.Combine(logPath, "Info.log"), LogEventLevel.Information) + // .WriteTo.File(Path.Combine(logPath, "Error.log"), LogEventLevel.Error) + // .WriteTo.File(Path.Combine(logPath, "Warn.log"), LogEventLevel.Warning) + // //.WriteTo.File(Path.Combine(logPath, "Debug.log"), LogEventLevel.Debug, fileSizeLimitBytes: 5 * 1024) + // .CreateLogger(); + Log.Logger = new LoggerConfiguration().MinimumLevel.Information().WriteTo.Console() - .WriteTo.File(Path.Combine(logPath, "Info.log"), LogEventLevel.Information) - .WriteTo.File(Path.Combine(logPath, "Error.log"), LogEventLevel.Error) - .WriteTo.File(Path.Combine(logPath, "Warn.log"), LogEventLevel.Warning) - //.WriteTo.File(Path.Combine(logPath, "Debug.log"), LogEventLevel.Debug, fileSizeLimitBytes: 5 * 1024) - .CreateLogger(); + .WriteTo.Logger(lc => lc + .Filter.ByIncludingOnly(logEvent => logEvent.Properties.ContainsKey("Module") && logEvent.Properties["Module"].ToString().Contains("Info")) + .WriteTo.File(Path.Combine($"{logPath}/Info/", "Info.log"), rollingInterval: RollingInterval.Day)) + .WriteTo.Logger(lc => lc + .Filter.ByIncludingOnly(logEvent => logEvent.Properties.ContainsKey("Module") && logEvent.Properties["Module"].ToString().Contains("Plc")) + .WriteTo.File(Path.Combine($"{logPath}/Plc/", "Plc.log"), rollingInterval: RollingInterval.Day)) + .WriteTo.Logger(lc => lc + .Filter.ByIncludingOnly(logEvent => logEvent.Properties.ContainsKey("Module") && logEvent.Properties["Module"].ToString().Contains("Camera")) + .WriteTo.File(Path.Combine($"{logPath}/Camera/", "Camera.log"), rollingInterval: RollingInterval.Day)) + .WriteTo.Logger(lc => lc + .Filter.ByIncludingOnly(logEvent => logEvent.Properties.ContainsKey("Module") && logEvent.Properties["Module"].ToString().Contains("Error")) + .WriteTo.File(Path.Combine($"{logPath}/Error/", "Error.log"), rollingInterval: RollingInterval.Day)) + .CreateLogger(); + app.UseSerilogRequestLogging(); return app; diff --git a/SlnMesnac.Serilog/SerilogHelper.cs b/SlnMesnac.Serilog/SerilogHelper.cs new file mode 100644 index 0000000..fc542a8 --- /dev/null +++ b/SlnMesnac.Serilog/SerilogHelper.cs @@ -0,0 +1,108 @@ +using Serilog; +using System; +using System.Collections.Generic; +using System.Text; + +#region << 版 本 注 释 >> +/*-------------------------------------------------------------------- +* 版权所有 (c) 2024 WenJY 保留所有权利。 +* CLR版本:4.0.30319.42000 +* 机器名称:T14-GEN3-7895 +* 命名空间:SlnMesnac.Serilog +* 唯一标识:fae9d68d-1992-4a03-b299-19edd9fc786d +* +* 创建者:WenJY +* 电子邮箱: +* 创建时间:2024-12-26 8:46:21 +* 版本:V1.0.0 +* 描述: +* +*-------------------------------------------------------------------- +* 修改人: +* 时间: +* 修改说明: +* +* 版本:V1.0.0 +*--------------------------------------------------------------------*/ +#endregion << 版 本 注 释 >> +namespace SlnMesnac.Serilog +{ + /// + /// Serilog日志类 + /// + public class SerilogHelper + { + private readonly ILogger? Info_logger = Log.ForContext("Module", "Info"); + private readonly ILogger? Plc_logger = Log.ForContext("Module", "Plc"); + private readonly ILogger? Error_logger = Log.ForContext("Module", "Error"); + private readonly ILogger? Camera_logger = Log.ForContext("Module", "Camera"); + + /// + /// Info日志 + /// + /// + public void Info(string msg) + { + if (Info_logger != null) + { + this.Info_logger.Information(msg); + } + } + + /// + /// Plc日志 + /// + /// + public void Plc(string msg) + { + if (Plc_logger != null) + { + this.Plc_logger.Information(msg); + } + } + + /// + /// 相机日志 + /// + /// + public void Camera(string msg) + { + if (Camera_logger != null) + { + this.Camera_logger.Information(msg); + } + } + + /// + /// Error日志 + /// + /// + /// + public void Error(string msg, Exception ex = null) + { + if (!string.IsNullOrEmpty(msg) && ex == null) + { + this.Error_logger.Information("【附加信息】 : {0}
", new object[] { msg }); + } + else if (!string.IsNullOrEmpty(msg) && ex != null) + { + string errorMsg = BeautyErrorMsg(ex); + this.Error_logger.Information("【附加信息】 : {0}
{1}", new object[] { msg, errorMsg }); + } + else if (string.IsNullOrEmpty(msg) && ex != null) + { + string errorMsg = BeautyErrorMsg(ex); + this.Error_logger.Information(errorMsg); + } + } + + private string BeautyErrorMsg(Exception ex) + { + string errorMsg = string.Format("【异常类型】:{0}
【异常信息】:{1}
【堆栈调用】:{2}", new object[] { ex.GetType().Name, ex.Message, ex.StackTrace }); + errorMsg = errorMsg.Replace("\r\n", "
"); + errorMsg = errorMsg.Replace("位置", "位置"); + return errorMsg; + } + + } +} \ No newline at end of file diff --git a/SlnMesnac.TouchSocket/TcpServer.cs b/SlnMesnac.TouchSocket/TcpServer.cs index 70f8afc..f62e138 100644 --- a/SlnMesnac.TouchSocket/TcpServer.cs +++ b/SlnMesnac.TouchSocket/TcpServer.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.Logging; +using SlnMesnac.Serilog; using System; using System.Collections.Generic; using System.Text; @@ -31,7 +32,7 @@ namespace SlnMesnac.TouchSocket { public class TcpServer { - private ILogger _logger; + private SerilogHelper _logger; private readonly TcpService _service; /// /// 接收客户端指令委托 @@ -42,7 +43,7 @@ namespace SlnMesnac.TouchSocket public delegate void RefreshClientInfo(TcpService tcpService); public event RefreshClientInfo? RefreshClientInfoEvent; - public TcpServer(ILogger logger,TcpService tcpService) + public TcpServer(SerilogHelper logger, TcpService tcpService) { _logger = logger; _service = tcpService; @@ -53,16 +54,16 @@ namespace SlnMesnac.TouchSocket try { _service.Connecting = (client, e) => { - _logger.LogInformation($"客户端{client.IP}正在接入服务"); + _logger.Info($"客户端{client.IP}正在接入服务"); return EasyTask.CompletedTask; }; _service.Connected = (client, e) => { - _logger.LogInformation($"客户端{client.IP}接入服务成功"); + _logger.Info($"客户端{client.IP}接入服务成功"); RefreshClientInfoEvent?.Invoke(_service); return EasyTask.CompletedTask; }; _service.Disconnected = (client, e) => { - _logger.LogInformation($"客户端{client.IP}断开连接"); + _logger.Info($"客户端{client.IP}断开连接"); RefreshClientInfoEvent?.Invoke(_service); return EasyTask.CompletedTask; }; @@ -89,12 +90,12 @@ namespace SlnMesnac.TouchSocket //自定义插件 })); _service.Start(); - _logger.LogInformation($"TcpServer启动成功,监听端口:{serverPort}"); + _logger.Info($"TcpServer启动成功,监听端口:{serverPort}"); } catch (Exception ex) { //throw new InvalidOperationException($"TcpServer启动异常:{ex.Message}"); - _logger.LogError($"TcpServer启动异常:{ex.Message}"); + _logger.Error($"TcpServer启动异常:{ex.Message}"); } } diff --git a/SlnMesnac.WPF/ViewModel/MainWindowViewModel.cs b/SlnMesnac.WPF/ViewModel/MainWindowViewModel.cs index 104526c..c6f6a2b 100644 --- a/SlnMesnac.WPF/ViewModel/MainWindowViewModel.cs +++ b/SlnMesnac.WPF/ViewModel/MainWindowViewModel.cs @@ -2,6 +2,7 @@ using GalaSoft.MvvmLight.Command; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using SlnMesnac.Serilog; using SlnMesnac.WPF.Page.Generate; using System; using System.Windows; @@ -10,7 +11,7 @@ namespace SlnMesnac.WPF.ViewModel { public class MainWindowViewModel: ViewModelBase { - private readonly ILogger _logger; + public readonly SerilogHelper _logger; //代码生成 private readonly GenerateControl generateControl = new GenerateControl(); @@ -79,7 +80,7 @@ namespace SlnMesnac.WPF.ViewModel public MainWindowViewModel() { - _logger = App.ServiceProvider.GetService>(); + _logger = App.ServiceProvider.GetService(); ControlOnClickCommand = new RelayCommand(obj => ControlOnClick(obj)); FormControlCommand = new RelayCommand(x => FormControl(x)); @@ -129,7 +130,7 @@ namespace SlnMesnac.WPF.ViewModel } catch (Exception ex) { - _logger.LogError("窗体控制逻辑异常", ex); + _logger.Error("窗体控制逻辑异常", ex); } } @@ -145,7 +146,7 @@ namespace SlnMesnac.WPF.ViewModel } catch (Exception ex) { - _logger.LogError("界面跳转逻辑异常", ex); + _logger.Error("界面跳转逻辑异常", ex); } } diff --git a/SlnMesnac/Controllers/BaseMaterialInfoController.cs b/SlnMesnac/Controllers/BaseMaterialInfoController.cs index 57d541b..1f016b0 100644 --- a/SlnMesnac/Controllers/BaseMaterialInfoController.cs +++ b/SlnMesnac/Controllers/BaseMaterialInfoController.cs @@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Mvc; using SlnMesnac.Model.domain; using SlnMesnac.Repository.service; +using SlnMesnac.Serilog; namespace SlnMesnac.Controllers { @@ -12,7 +13,7 @@ namespace SlnMesnac.Controllers [ApiController] public class BaseMaterialInfoController { - private ILogger _logger; + public readonly SerilogHelper _logger; private IBaseMaterialService _service; @@ -21,7 +22,7 @@ namespace SlnMesnac.Controllers /// /// /// - public BaseMaterialInfoController(ILogger logger, IBaseMaterialService service) + public BaseMaterialInfoController(SerilogHelper logger, IBaseMaterialService service) { _logger = logger; _service = service; @@ -41,7 +42,7 @@ namespace SlnMesnac.Controllers } catch (Exception ex) { - _logger.LogError($"获取物料信息接口调用异常:{ex.Message}"); + _logger.Error($"获取物料信息接口调用异常:{ex.Message}"); } return materialInfos; } @@ -61,7 +62,7 @@ namespace SlnMesnac.Controllers } catch (Exception ex) { - _logger.LogError($"根据物料编号获取物料信息接口调用异常:{ex.Message}"); + _logger.Error($"根据物料编号获取物料信息接口调用异常:{ex.Message}"); } return materialInfo; } @@ -82,7 +83,7 @@ namespace SlnMesnac.Controllers } catch (Exception ex) { - _logger.LogError($"通过物料类别获取物料信息接口调用异常:{ex.Message}"); + _logger.Error($"通过物料类别获取物料信息接口调用异常:{ex.Message}"); } return materialInfos; } diff --git a/SlnMesnac/Controllers/BaseUserController.cs b/SlnMesnac/Controllers/BaseUserController.cs index 3cdd7e0..b6d6b40 100644 --- a/SlnMesnac/Controllers/BaseUserController.cs +++ b/SlnMesnac/Controllers/BaseUserController.cs @@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc; using SlnMesnac.Model.domain; using SlnMesnac.Plc; using SlnMesnac.Repository.service; +using SlnMesnac.Serilog; namespace SlnMesnac.Controllers { @@ -13,7 +14,7 @@ namespace SlnMesnac.Controllers [ApiController] public class BaseUserController : ControllerBase { - private readonly ILogger _logger; + public readonly SerilogHelper _logger; private readonly IBaseUserService _service; @@ -22,7 +23,7 @@ namespace SlnMesnac.Controllers /// /// /// - public BaseUserController(ILogger logger, IBaseUserService service) + public BaseUserController(SerilogHelper logger, IBaseUserService service) { _logger = logger; _service = service; @@ -42,7 +43,7 @@ namespace SlnMesnac.Controllers } catch (Exception ex) { - _logger.LogError($"获取用户信息接口调用异常:{ex.Message}"); + _logger.Error($"获取用户信息接口调用异常:{ex.Message}"); } return users; } @@ -62,7 +63,7 @@ namespace SlnMesnac.Controllers } catch (Exception ex) { - _logger.LogError($"获取用户信息接口调用异常:{ex.Message}"); + _logger.Error($"获取用户信息接口调用异常:{ex.Message}"); } return users; }