using JinYuan.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JinYuan.Helper { /// /// 日志操作类 /// public class LogHelper { private static object singleLock = new object(); /// /// log日志文件路径 /// public static string logFilePath = string.Empty; public static LogHelper _instance = null; public static LogHelper Instance { get { if (_instance == null) { lock (singleLock) { if (_instance == null) { _instance = new LogHelper(); } } } return _instance; } } /// /// 初始化 /// /// public void InitLog(string configPath) { logFilePath = configPath; if (!Directory.Exists(logFilePath)) { Directory.CreateDirectory(logFilePath); } //if (!File.Exists(logFilePath)) //{ // File.Create(logFilePath).Close(); //} } /// /// 写日志文件数据库日志文件 /// /// 消息 public void WriteError(string message) { AddLog(message, "Error"); } public void WriteEX(Exception ex) { AddLog(ex.Message + "\r\n" + ex.InnerException + "\r\n" + ex.StackTrace + "\r\n" + ex.Source, "SysErrorLog"); } public void WriteEX(string ErrorName,Exception ex) { AddLog(ErrorName+ "\r\n"+ex.Message + "\r\n" + ex.InnerException + "\r\n" + ex.StackTrace + "\r\n" + ex.Source, "SysErrorLog"); } /// /// 写日志文件数据库日志文件 /// /// 消息 /// 日志存储目录名称 public void WriteError(Exception ex, string direName) { AddLog(ex.Message + "\r\n" + ex.InnerException + "\r\n" + ex.StackTrace + "\r\n" + ex.Source, direName); } /// /// / /// /// /// public void WriteError(string message, string direName) { AddLog(message, direName); } /// /// 写日志文件数据库日志文件 /// /// 消息 public void WriteLog(string message) { AddLog(message, "Info"); } /// /// 写日志文件数据库日志文件 /// /// 消息 /// 日志存储目录名称 public void WriteLog(string message, string direName) { AddLog(message, direName); } /// /// 写日志文件数据库日志文件 /// /// 消息 /// 日志存储目录名称 private void AddLog(string message, string direName) { string fileLog = logFilePath; if (fileLog == "") { return; } try { var applicationName = direName; //从宿主配置文件中获取日志文件全路径 //所有的接口日志文件放在一个目录下面,跟web站点的目录分开 //日志文件一天放一个,按日期分开 if (string.IsNullOrEmpty(applicationName)) { applicationName = "Log"; } string logFullPath = fileLog + applicationName; if (!Directory.Exists(logFullPath)) { Directory.CreateDirectory(logFullPath); } //只保留30天的日志 var deletePath = $@"{logFullPath}\{DateTime.Now.AddDays(-30):yyyyMMddHH}.txt"; if (File.Exists(deletePath)) { File.Delete(deletePath); } logFullPath = $@"{logFullPath}\{DateTime.Now:yyyyMMddHH}.txt"; if (!File.Exists(logFullPath)) { using (var fs = new FileStream(logFullPath, FileMode.Create, FileAccess.Write)) { StreamWriter sw = new StreamWriter(fs); sw.Close(); fs.Close(); } } using (StreamWriter writer = new StreamWriter(logFullPath, true)) { writer.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); writer.WriteLine(message); writer.WriteLine(Environment.NewLine); } } catch { // ignored } } } }