You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
3.2 KiB
C#

#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* (c) 2025 WenJY
* CLR4.0.30319.42000
* Mr.Wen's MacBook Pro
* Sln.Iot.Serilog
* 15731D3E-0D48-41B6-B77B-A4CC592B4939
*
* WenJY
*
* 2025-04-11 11:09:14
* V1.0.0
*
*
*--------------------------------------------------------------------
*
*
*
*
* V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
using System;
using Serilog;
namespace Sln.Iot.Serilog
{
public class SerilogHelper
{
private readonly ILogger? Info_logger = Log.ForContext("Module", "Info");
private readonly ILogger? Iot_logger = Log.ForContext("Module", "Iot");
private readonly ILogger? Error_logger = Log.ForContext("Module", "Error");
private readonly ILogger? Alarm_logger = Log.ForContext("Module", "Alarm");
/// <summary>
/// Info日志
/// </summary>
/// <param name="msg"></param>
public void Info(string msg)
{
if (Info_logger != null)
{
this.Info_logger.Information(msg);
}
}
/// <summary>
/// Iot日志
/// </summary>
/// <param name="msg"></param>
public void Iot(string msg)
{
if (Iot_logger != null)
{
this.Iot_logger.Information(msg);
}
}
/// <summary>
/// 设备告警日志
/// </summary>
/// <param name="msg"></param>
public void Alarm(string msg)
{
if (Alarm_logger != null)
{
this.Alarm_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;
}
}
}