using System.Text;
namespace LogTool;
public class WcsLog
{
private static WcsLog? instance;
public static WcsLog Instance()
{
instance ??= new WcsLog();
return instance;
}
private static readonly object writeLog = new();
///
/// 通用写日志类
///
/// 文件夹名称
/// 日志内容
/// 是否在日志中自动添加时间
public void WriteLog(string LogName, string strLog, bool addTime = true)
{
Task.Factory.StartNew(() =>
{
lock (writeLog)
{
string LogAddress = AppDomain.CurrentDomain.BaseDirectory + "Log\\" + LogName;
DirectoryInfo di = new(LogAddress);
if (di.Exists == false) { di.Create(); }
StringBuilder logBuilder = new();
if (addTime)
{
logBuilder.AppendLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss:fff}]");
}
logBuilder.AppendLine($"{strLog}");
string logFileName = LogAddress + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
using FileStream fs = new(logFileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
using StreamWriter sw = new(fs);
try
{
sw.Write(logBuilder);
}
catch (Exception ex)
{
_ = ex;
}
}
});
}
///
/// 写系统日志
///
///
public void WriteSystemLog(string strLog) => WriteLog("系统日志", strLog);
///
/// 写系统日志
///
///
public void WriteSystemLog(StringBuilder strLog) => WriteLog("系统日志", strLog.ToString(), false);
///
/// 写事件日志
///
///
public void WriteEventLog(string strLog) => WriteLog("事件日志", strLog);
///
/// 写事件日志
///
///
public void WriteEventLog(StringBuilder strLog) => WriteLog("事件日志", strLog.ToString(), false);
///
/// 写入Tcp日志
///
///
public void WriteTcpLog(StringBuilder strLog) => WriteLog("Tcp日志", strLog.ToString(), false);
///
/// 写接口日志
///
///
public void WriteApiRequestLog(string strLog) => WriteLog("接口请求日志", strLog);
///
/// 写异常日志
///
///
public void WriteExceptionLog(string strLog) => WriteLog("异常日志", strLog);
///
/// 写异常日志
///
///
public void WriteExceptionLog(StringBuilder strLog) => WriteLog("异常日志", strLog.ToString(), false);
///
/// 写数据库日志
///
///
public void WriteSQLLog(string strLog) => WriteLog("数据库日志", strLog);
///
/// 写接口接收日志
///
///
public void WriteApiAcceptLog(string strLog) => WriteLog("接口接收日志", strLog);
}