Merge pull request 'change - 添加Serilog自定义log文件,修改BaseBusiness注入方式,直接注入IServiceProvider容器' (#7) from dev into master

Reviewed-on: #7
master
wenjy 4 weeks ago
commit ff4fb949e6

@ -1,5 +1,7 @@
using SlnMesnac.Plc; using Microsoft.Extensions.DependencyInjection;
using SlnMesnac.Plc;
using SlnMesnac.Rfid; using SlnMesnac.Rfid;
using SlnMesnac.Serilog;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -35,10 +37,17 @@ namespace SlnMesnac.Business.@base
private readonly List<RfidAbsractFactory> _rfidFactories; private readonly List<RfidAbsractFactory> _rfidFactories;
public BaseBusiness(List<PlcAbsractFactory> plcFactories, List<RfidAbsractFactory> rfidFactories) private IServiceProvider _serviceProvider;
public BaseBusiness(IServiceProvider serviceProvider)
{ {
_plcFactories = plcFactories; _serviceProvider = serviceProvider;
_rfidFactories = rfidFactories;
using (var scope = _serviceProvider.CreateScope())
{
_plcFactories = scope.ServiceProvider.GetRequiredService<List<PlcAbsractFactory>>();
_rfidFactories = scope.ServiceProvider.GetRequiredService<List<RfidAbsractFactory>>();
}
} }
/// <summary> /// <summary>

@ -33,7 +33,7 @@ namespace SlnMesnac.Generate.Templates.Service
{ {
public class IServiceCreate 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) public bool Create(string tableName, string NameSpace, string outdir)
{ {

@ -33,7 +33,7 @@ namespace SlnMesnac.Generate.Templates.Service.Impl
{ {
public class ServiceCreate 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) public bool Create(string tableName, string NameSpace, string outdir)
{ {

@ -6,6 +6,7 @@ using MQTTnet.Client;
using System.Security.Authentication; using System.Security.Authentication;
using MQTTnet; using MQTTnet;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SlnMesnac.Serilog;
#region << 版 本 注 释 >> #region << 版 本 注 释 >>
/*-------------------------------------------------------------------- /*--------------------------------------------------------------------
@ -36,11 +37,11 @@ namespace SlnMesnac.Mqtt
/// </summary> /// </summary>
public class MqttClient public class MqttClient
{ {
private ILogger<MqttClient> _logger; public readonly SerilogHelper _logger;
private IMqttClient _client; private IMqttClient _client;
public MqttClient(ILogger<MqttClient> logger) public MqttClient(SerilogHelper logger)
{ {
_logger = logger; _logger = logger;
} }
@ -78,17 +79,17 @@ namespace SlnMesnac.Mqtt
{ {
if (result.ResultCode == MQTTnet.Client.MqttClientConnectResultCode.Success) if (result.ResultCode == MQTTnet.Client.MqttClientConnectResultCode.Success)
{ {
_logger.LogInformation($"连接服务器成功{ip}:{port}"); _logger.Info($"连接服务器成功{ip}:{port}");
} }
else else
{ {
_logger.LogInformation($"连接服务器失败"); _logger.Info($"连接服务器失败");
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError("连接服务器异常",ex); _logger.Error("连接服务器异常",ex);
} }
} }
@ -98,7 +99,7 @@ namespace SlnMesnac.Mqtt
public void DisConnect() public void DisConnect()
{ {
_client.DisconnectAsync(); _client.DisconnectAsync();
_logger.LogInformation($"断开连接"); _logger.Info($"断开连接");
} }
/// <summary> /// <summary>
@ -120,11 +121,11 @@ namespace SlnMesnac.Mqtt
MqttClientSubscribeResult result = await _client.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None); MqttClientSubscribeResult result = await _client.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None);
_logger.LogInformation($"订阅主题:{topic}"); _logger.Info($"订阅主题:{topic}");
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError("订阅主题异常",ex); _logger.Error("订阅主题异常",ex);
} }
} }
@ -135,7 +136,7 @@ namespace SlnMesnac.Mqtt
public void Unsubscribe(string topic) public void Unsubscribe(string topic)
{ {
_client.UnsubscribeAsync(topic); _client.UnsubscribeAsync(topic);
_logger.LogInformation($"取消订阅,主题:{topic}"); _logger.Info($"取消订阅,主题:{topic}");
} }
/// <summary> /// <summary>
@ -150,18 +151,18 @@ namespace SlnMesnac.Mqtt
var msg = new MqttApplicationMessageBuilder().WithTopic(topic).WithPayload(message) var msg = new MqttApplicationMessageBuilder().WithTopic(topic).WithPayload(message)
.Build(); .Build();
_client.PublishAsync(msg, CancellationToken.None); _client.PublishAsync(msg, CancellationToken.None);
_logger.LogInformation($"向服务端推送成功,主题:{topic};内容:{message}"); _logger.Info($"向服务端推送成功,主题:{topic};内容:{message}");
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError("向服务端推送消息异常",ex); _logger.Error("向服务端推送消息异常",ex);
} }
} }
private async Task MqttClient_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs eventArgs) private async Task MqttClient_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs eventArgs)
{ {
var info = $"接收到主题:{eventArgs.ApplicationMessage.Topic}的消息,内容:{Encoding.UTF8.GetString(eventArgs.ApplicationMessage.Payload)}"; var info = $"接收到主题:{eventArgs.ApplicationMessage.Topic}的消息,内容:{Encoding.UTF8.GetString(eventArgs.ApplicationMessage.Payload)}";
_logger.LogInformation(info); _logger.Info(info);
} }
} }

@ -1,5 +1,6 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Quartz; using Quartz;
using SlnMesnac.Serilog;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@ -31,16 +32,16 @@ namespace SlnMesnac.Quartz.Job
{ {
internal class Job2 : IJob internal class Job2 : IJob
{ {
private readonly ILogger<Job2> _logger; private readonly SerilogHelper _logger;
public Job2(ILogger<Job2> logger) public Job2(SerilogHelper logger)
{ {
_logger = logger; _logger = logger;
} }
public Task Execute(IJobExecutionContext context) 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; return Task.CompletedTask;
} }
} }

@ -1,5 +1,6 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Quartz; using Quartz;
using SlnMesnac.Serilog;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@ -31,16 +32,16 @@ namespace SlnMesnac.Quartz.Job
{ {
public class MyJob : IJob public class MyJob : IJob
{ {
private readonly ILogger<MyJob> _logger; private readonly SerilogHelper _logger;
public MyJob(ILogger<MyJob> logger) public MyJob(SerilogHelper logger)
{ {
_logger = logger; _logger = logger;
} }
public Task Execute(IJobExecutionContext context) 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; return Task.CompletedTask;
} }
} }

@ -10,4 +10,8 @@
<PackageReference Include="Quartz.AspNetCore" Version="3.8.0" /> <PackageReference Include="Quartz.AspNetCore" Version="3.8.0" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SlnMesnac.Serilog\SlnMesnac.Serilog.csproj" />
</ItemGroup>
</Project> </Project>

@ -1,5 +1,6 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SlnMesnac.Config; using SlnMesnac.Config;
using SlnMesnac.Serilog;
using StackExchange.Redis; using StackExchange.Redis;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -31,7 +32,7 @@ namespace SlnMesnac.Redis
{ {
public class RedisHandler public class RedisHandler
{ {
private ILogger<RedisHandler> _logger; private SerilogHelper _logger;
private readonly AppConfig _appConfig; private readonly AppConfig _appConfig;
@ -39,7 +40,7 @@ namespace SlnMesnac.Redis
private readonly ConnectionMultiplexer redis; private readonly ConnectionMultiplexer redis;
public RedisHandler(AppConfig appConfig, ILogger<RedisHandler> logger) public RedisHandler(AppConfig appConfig, SerilogHelper logger)
{ {
_appConfig = appConfig; _appConfig = appConfig;
@ -59,7 +60,7 @@ namespace SlnMesnac.Redis
{ {
long res = _subscriber.Publish(channel, message); long res = _subscriber.Publish(channel, message);
_logger.LogInformation($"向主题:{channel};推送消息:{message};结果:{res}"); _logger.Info($"向主题:{channel};推送消息:{message};结果:{res}");
} }
/// <summary> /// <summary>
@ -72,7 +73,7 @@ namespace SlnMesnac.Redis
_subscriber.Subscribe(channel, (ch, message) => _subscriber.Subscribe(channel, (ch, message) =>
{ {
onMessageReceived(ch, message); onMessageReceived(ch, message);
_logger.LogInformation($"订阅主题:{channel};收到主题:{ch};推送的消息:{message}"); _logger.Info($"订阅主题:{channel};收到主题:{ch};推送的消息:{message}");
}); });
} }

@ -11,6 +11,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\SlnMesnac.Config\SlnMesnac.Config.csproj" /> <ProjectReference Include="..\SlnMesnac.Config\SlnMesnac.Config.csproj" />
<ProjectReference Include="..\SlnMesnac.Serilog\SlnMesnac.Serilog.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

@ -14,6 +14,7 @@
<ProjectReference Include="..\SlnMesnac.Common\SlnMesnac.Common.csproj" /> <ProjectReference Include="..\SlnMesnac.Common\SlnMesnac.Common.csproj" />
<ProjectReference Include="..\SlnMesnac.Config\SlnMesnac.Config.csproj" /> <ProjectReference Include="..\SlnMesnac.Config\SlnMesnac.Config.csproj" />
<ProjectReference Include="..\SlnMesnac.Model\SlnMesnac.Model.csproj" /> <ProjectReference Include="..\SlnMesnac.Model\SlnMesnac.Model.csproj" />
<ProjectReference Include="..\SlnMesnac.Serilog\SlnMesnac.Serilog.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

@ -6,6 +6,7 @@ using System.Collections.Generic;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Text; using System.Text;
using SlnMesnac.Repository.service.@base; using SlnMesnac.Repository.service.@base;
using SlnMesnac.Serilog;
#region << 版 本 注 释 >> #region << 版 本 注 释 >>
/*-------------------------------------------------------------------- /*--------------------------------------------------------------------
@ -33,9 +34,9 @@ namespace SlnMesnac.Repository.service.Impl
{ {
public class BaseMaterialServiceImpl : BaseServiceImpl<BaseMaterialInfo>, IBaseMaterialService public class BaseMaterialServiceImpl : BaseServiceImpl<BaseMaterialInfo>, IBaseMaterialService
{ {
private ILogger<BaseMaterialServiceImpl> _logger; private SerilogHelper _logger;
public BaseMaterialServiceImpl(Repository<BaseMaterialInfo> repository, ILogger<BaseMaterialServiceImpl> logger):base(repository) public BaseMaterialServiceImpl(Repository<BaseMaterialInfo> repository, SerilogHelper logger) :base(repository)
{ {
_logger = logger; _logger = logger;
} }
@ -54,7 +55,7 @@ namespace SlnMesnac.Repository.service.Impl
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"根据物料编号获取物料信息异常:{ex.Message}"); _logger.Error($"根据物料编号获取物料信息异常:{ex.Message}");
} }
return materialInfo; return materialInfo;
} }
@ -73,7 +74,7 @@ namespace SlnMesnac.Repository.service.Impl
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"根据SAP物料编号获取物料信息异常:{ex.Message}"); _logger.Error($"根据SAP物料编号获取物料信息异常:{ex.Message}");
} }
return materialInfo; return materialInfo;
} }
@ -91,7 +92,7 @@ namespace SlnMesnac.Repository.service.Impl
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"获取物料信息异常:{ex.Message}"); _logger.Error($"获取物料信息异常:{ex.Message}");
} }
return materialInfos; return materialInfos;
} }
@ -122,7 +123,7 @@ namespace SlnMesnac.Repository.service.Impl
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"通过物料类型获取物料信息异常:{ex.Message}"); _logger.Error($"通过物料类型获取物料信息异常:{ex.Message}");
} }
return materialInfos; return materialInfos;
} }

@ -1,6 +1,7 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SlnMesnac.Model.domain; using SlnMesnac.Model.domain;
using SlnMesnac.Repository.service.@base; using SlnMesnac.Repository.service.@base;
using SlnMesnac.Serilog;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@ -31,9 +32,9 @@ namespace SlnMesnac.Repository.service.Impl
{ {
public class BaseUserServiceImpl : BaseServiceImpl<BaseUser>,IBaseUserService public class BaseUserServiceImpl : BaseServiceImpl<BaseUser>,IBaseUserService
{ {
private readonly ILogger<BaseUser> _logger; private readonly SerilogHelper _logger;
public BaseUserServiceImpl(Repository<BaseUser> rep,ILogger<BaseUser> logger) :base(rep) public BaseUserServiceImpl(Repository<BaseUser> rep, SerilogHelper logger) :base(rep)
{ {
_logger = logger; _logger = logger;
} }
@ -48,7 +49,7 @@ namespace SlnMesnac.Repository.service.Impl
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"获取用户信息异常{ex.Message}"); _logger.Error($"获取用户信息异常{ex.Message}");
} }
return users; return users;
} }
@ -67,7 +68,7 @@ namespace SlnMesnac.Repository.service.Impl
catch (Exception ex) catch (Exception ex)
{ {
base._rep.AsTenant().RollbackTran(); base._rep.AsTenant().RollbackTran();
_logger.LogError($"用户信息添加异常:{ex.Message}"); _logger.Error($"用户信息添加异常:{ex.Message}");
} }
return result; return result;
} }

@ -9,6 +9,7 @@ using SlnMesnac.Common;
using SlnMesnac.Model.dto; using SlnMesnac.Model.dto;
using SlnMesnac.Rfid.Dto; using SlnMesnac.Rfid.Dto;
using SlnMesnac.Rfid.Enum; using SlnMesnac.Rfid.Enum;
using SlnMesnac.Serilog;
using TouchSocket.Core; using TouchSocket.Core;
using TouchSocket.Sockets; using TouchSocket.Sockets;
@ -38,11 +39,11 @@ namespace SlnMesnac.Rfid.Factory
{ {
public class RflyFactory:RfidAbsractFactory public class RflyFactory:RfidAbsractFactory
{ {
private ILogger<RflyFactory> _logger; private SerilogHelper _logger;
private readonly TcpClient _tcpClient = new TcpClient(); private readonly TcpClient _tcpClient = new TcpClient();
private readonly StringChange _stringChange; private readonly StringChange _stringChange;
public RflyFactory(ILogger<RflyFactory> logger,StringChange stringChange) public RflyFactory(SerilogHelper logger,StringChange stringChange)
{ {
_logger = logger; _logger = logger;
_stringChange = stringChange; _stringChange = stringChange;
@ -106,7 +107,7 @@ namespace SlnMesnac.Rfid.Factory
byte[] reciveBuffer = waitClient.SendThenReturn(pMessagePack.m_pData, timeout); 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); byte[] resultBuffer = PareReceiveBufferData(reciveBuffer,reciveBuffer.Length);
@ -417,12 +418,12 @@ namespace SlnMesnac.Rfid.Factory
iFirstPC = iFirstAnt + 1; iFirstPC = iFirstAnt + 1;
iFirstLeftBarcketPos = iFirstLeftBarcketPos + iBarcodeLength + 5; 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++; iCommonSecondFlag++;
if (iCommonSecondFlag == iBarcodeGroupCount) if (iCommonSecondFlag == iBarcodeGroupCount)
{ {
mutauto.ReleaseMutex(); mutauto.ReleaseMutex();
_logger.LogInformation("《《《返回标签数据!"); _logger.Info("《《《返回标签数据!");
return tagInfoList; return tagInfoList;
} }
} }

@ -42,15 +42,32 @@ namespace SlnMesnac.Serilog
#region 通过配置文件读取日志存放位置 #region 通过配置文件读取日志存放位置
var appConfig = app.ApplicationServices.GetService<AppConfig>(); var appConfig = app.ApplicationServices.GetService<AppConfig>();
var logPath = $"{appConfig.logPath}/Logs/{DateTime.UtcNow:yyyy-MM-dd}/"; var logPath = $"{appConfig.logPath}/Logs/";
#endregion #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() Log.Logger = new LoggerConfiguration().MinimumLevel.Information().WriteTo.Console()
.WriteTo.File(Path.Combine(logPath, "Info.log"), LogEventLevel.Information) .WriteTo.Logger(lc => lc
.WriteTo.File(Path.Combine(logPath, "Error.log"), LogEventLevel.Error) .Filter.ByIncludingOnly(logEvent => logEvent.Properties.ContainsKey("Module") && logEvent.Properties["Module"].ToString().Contains("Info"))
.WriteTo.File(Path.Combine(logPath, "Warn.log"), LogEventLevel.Warning) .WriteTo.File(Path.Combine($"{logPath}/Info/", "Info.log"), rollingInterval: RollingInterval.Day))
//.WriteTo.File(Path.Combine(logPath, "Debug.log"), LogEventLevel.Debug, fileSizeLimitBytes: 5 * 1024) .WriteTo.Logger(lc => lc
.CreateLogger(); .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(); app.UseSerilogRequestLogging();
return app; return app;

@ -0,0 +1,108 @@
using Serilog;
using System;
using System.Collections.Generic;
using System.Text;
#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* (c) 2024 WenJY
* CLR4.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
{
/// <summary>
/// Serilog日志类
/// </summary>
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");
/// <summary>
/// Info日志
/// </summary>
/// <param name="msg"></param>
public void Info(string msg)
{
if (Info_logger != null)
{
this.Info_logger.Information(msg);
}
}
/// <summary>
/// Plc日志
/// </summary>
/// <param name="msg"></param>
public void Plc(string msg)
{
if (Plc_logger != null)
{
this.Plc_logger.Information(msg);
}
}
/// <summary>
/// 相机日志
/// </summary>
/// <param name="msg"></param>
public void Camera(string msg)
{
if (Camera_logger != null)
{
this.Camera_logger.Information(msg);
}
}
/// <summary>
/// Error日志
/// </summary>
/// <param name="msg"></param>
/// <param name="ex"></param>
public void Error(string msg, Exception ex = null)
{
if (!string.IsNullOrEmpty(msg) && ex == null)
{
this.Error_logger.Information("【附加信息】 : {0}<br>", new object[] { msg });
}
else if (!string.IsNullOrEmpty(msg) && ex != null)
{
string errorMsg = BeautyErrorMsg(ex);
this.Error_logger.Information("【附加信息】 : {0}<br>{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} <br>【异常信息】:{1} <br>【堆栈调用】:{2}", new object[] { ex.GetType().Name, ex.Message, ex.StackTrace });
errorMsg = errorMsg.Replace("\r\n", "<br>");
errorMsg = errorMsg.Replace("位置", "<strong style=\"color:red\">位置</strong>");
return errorMsg;
}
}
}

@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SlnMesnac.Serilog;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@ -31,7 +32,7 @@ namespace SlnMesnac.TouchSocket
{ {
public class TcpServer public class TcpServer
{ {
private ILogger<TcpServer> _logger; private SerilogHelper _logger;
private readonly TcpService _service; private readonly TcpService _service;
/// <summary> /// <summary>
/// 接收客户端指令委托 /// 接收客户端指令委托
@ -42,7 +43,7 @@ namespace SlnMesnac.TouchSocket
public delegate void RefreshClientInfo(TcpService tcpService); public delegate void RefreshClientInfo(TcpService tcpService);
public event RefreshClientInfo? RefreshClientInfoEvent; public event RefreshClientInfo? RefreshClientInfoEvent;
public TcpServer(ILogger<TcpServer> logger,TcpService tcpService) public TcpServer(SerilogHelper logger, TcpService tcpService)
{ {
_logger = logger; _logger = logger;
_service = tcpService; _service = tcpService;
@ -53,16 +54,16 @@ namespace SlnMesnac.TouchSocket
try try
{ {
_service.Connecting = (client, e) => { _service.Connecting = (client, e) => {
_logger.LogInformation($"客户端{client.IP}正在接入服务"); _logger.Info($"客户端{client.IP}正在接入服务");
return EasyTask.CompletedTask; return EasyTask.CompletedTask;
}; };
_service.Connected = (client, e) => { _service.Connected = (client, e) => {
_logger.LogInformation($"客户端{client.IP}接入服务成功"); _logger.Info($"客户端{client.IP}接入服务成功");
RefreshClientInfoEvent?.Invoke(_service); RefreshClientInfoEvent?.Invoke(_service);
return EasyTask.CompletedTask; return EasyTask.CompletedTask;
}; };
_service.Disconnected = (client, e) => { _service.Disconnected = (client, e) => {
_logger.LogInformation($"客户端{client.IP}断开连接"); _logger.Info($"客户端{client.IP}断开连接");
RefreshClientInfoEvent?.Invoke(_service); RefreshClientInfoEvent?.Invoke(_service);
return EasyTask.CompletedTask; return EasyTask.CompletedTask;
}; };
@ -89,12 +90,12 @@ namespace SlnMesnac.TouchSocket
//自定义插件 //自定义插件
})); }));
_service.Start(); _service.Start();
_logger.LogInformation($"TcpServer启动成功监听端口{serverPort}"); _logger.Info($"TcpServer启动成功监听端口{serverPort}");
} }
catch (Exception ex) catch (Exception ex)
{ {
//throw new InvalidOperationException($"TcpServer启动异常{ex.Message}"); //throw new InvalidOperationException($"TcpServer启动异常{ex.Message}");
_logger.LogError($"TcpServer启动异常{ex.Message}"); _logger.Error($"TcpServer启动异常{ex.Message}");
} }
} }

@ -2,6 +2,7 @@
using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Command;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SlnMesnac.Serilog;
using SlnMesnac.WPF.Page.Generate; using SlnMesnac.WPF.Page.Generate;
using System; using System;
using System.Windows; using System.Windows;
@ -10,7 +11,7 @@ namespace SlnMesnac.WPF.ViewModel
{ {
public class MainWindowViewModel: ViewModelBase public class MainWindowViewModel: ViewModelBase
{ {
private readonly ILogger<MainWindowViewModel> _logger; public readonly SerilogHelper _logger;
//代码生成 //代码生成
private readonly GenerateControl generateControl = new GenerateControl(); private readonly GenerateControl generateControl = new GenerateControl();
@ -79,7 +80,7 @@ namespace SlnMesnac.WPF.ViewModel
public MainWindowViewModel() public MainWindowViewModel()
{ {
_logger = App.ServiceProvider.GetService<ILogger<MainWindowViewModel>>(); _logger = App.ServiceProvider.GetService<SerilogHelper>();
ControlOnClickCommand = new RelayCommand<object>(obj => ControlOnClick(obj)); ControlOnClickCommand = new RelayCommand<object>(obj => ControlOnClick(obj));
FormControlCommand = new RelayCommand<object>(x => FormControl(x)); FormControlCommand = new RelayCommand<object>(x => FormControl(x));
@ -129,7 +130,7 @@ namespace SlnMesnac.WPF.ViewModel
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError("窗体控制逻辑异常", ex); _logger.Error("窗体控制逻辑异常", ex);
} }
} }
@ -145,7 +146,7 @@ namespace SlnMesnac.WPF.ViewModel
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError("界面跳转逻辑异常", ex); _logger.Error("界面跳转逻辑异常", ex);
} }
} }

@ -2,6 +2,7 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using SlnMesnac.Model.domain; using SlnMesnac.Model.domain;
using SlnMesnac.Repository.service; using SlnMesnac.Repository.service;
using SlnMesnac.Serilog;
namespace SlnMesnac.Controllers namespace SlnMesnac.Controllers
{ {
@ -12,7 +13,7 @@ namespace SlnMesnac.Controllers
[ApiController] [ApiController]
public class BaseMaterialInfoController public class BaseMaterialInfoController
{ {
private ILogger<BaseMaterialInfoController> _logger; public readonly SerilogHelper _logger;
private IBaseMaterialService _service; private IBaseMaterialService _service;
@ -21,7 +22,7 @@ namespace SlnMesnac.Controllers
/// </summary> /// </summary>
/// <param name="logger"></param> /// <param name="logger"></param>
/// <param name="service"></param> /// <param name="service"></param>
public BaseMaterialInfoController(ILogger<BaseMaterialInfoController> logger, IBaseMaterialService service) public BaseMaterialInfoController(SerilogHelper logger, IBaseMaterialService service)
{ {
_logger = logger; _logger = logger;
_service = service; _service = service;
@ -41,7 +42,7 @@ namespace SlnMesnac.Controllers
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"获取物料信息接口调用异常:{ex.Message}"); _logger.Error($"获取物料信息接口调用异常:{ex.Message}");
} }
return materialInfos; return materialInfos;
} }
@ -61,7 +62,7 @@ namespace SlnMesnac.Controllers
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"根据物料编号获取物料信息接口调用异常:{ex.Message}"); _logger.Error($"根据物料编号获取物料信息接口调用异常:{ex.Message}");
} }
return materialInfo; return materialInfo;
} }
@ -82,7 +83,7 @@ namespace SlnMesnac.Controllers
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"通过物料类别获取物料信息接口调用异常:{ex.Message}"); _logger.Error($"通过物料类别获取物料信息接口调用异常:{ex.Message}");
} }
return materialInfos; return materialInfos;
} }

@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc;
using SlnMesnac.Model.domain; using SlnMesnac.Model.domain;
using SlnMesnac.Plc; using SlnMesnac.Plc;
using SlnMesnac.Repository.service; using SlnMesnac.Repository.service;
using SlnMesnac.Serilog;
namespace SlnMesnac.Controllers namespace SlnMesnac.Controllers
{ {
@ -13,7 +14,7 @@ namespace SlnMesnac.Controllers
[ApiController] [ApiController]
public class BaseUserController : ControllerBase public class BaseUserController : ControllerBase
{ {
private readonly ILogger<BaseUserController> _logger; public readonly SerilogHelper _logger;
private readonly IBaseUserService _service; private readonly IBaseUserService _service;
@ -22,7 +23,7 @@ namespace SlnMesnac.Controllers
/// </summary> /// </summary>
/// <param name="logger"></param> /// <param name="logger"></param>
/// <param name="service"></param> /// <param name="service"></param>
public BaseUserController(ILogger<BaseUserController> logger, IBaseUserService service) public BaseUserController(SerilogHelper logger, IBaseUserService service)
{ {
_logger = logger; _logger = logger;
_service = service; _service = service;
@ -42,7 +43,7 @@ namespace SlnMesnac.Controllers
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"获取用户信息接口调用异常:{ex.Message}"); _logger.Error($"获取用户信息接口调用异常:{ex.Message}");
} }
return users; return users;
} }
@ -62,7 +63,7 @@ namespace SlnMesnac.Controllers
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"获取用户信息接口调用异常:{ex.Message}"); _logger.Error($"获取用户信息接口调用异常:{ex.Message}");
} }
return users; return users;
} }

Loading…
Cancel
Save