Logs 发表于 2023-06-18 11:35:51 字数统计 523 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156using System; using System.Diagnostics; using System.IO; using System.Reflection; namespace ConsoleAppLogs { /// <summary> /// 日志策略接口 /// </summary> public interface ILogStrategy { /// <summary> /// 写入日志 /// </summary> /// <param name="message">消息</param> void Write(string message); } /// <summary> /// 日志操作管理类 /// </summary> public class Logs { private static ILogStrategy _ilogstrategy = new LogStrategy();//日志策略 /// <summary> /// 写入日志 /// </summary> /// <param name="message">消息</param> public static void Write(string message) { _ilogstrategy.Write(message); } /// <summary> /// 写入日志 /// </summary> /// <param name="ex">异常对象</param> public static void Write(Exception ex) { _ilogstrategy.Write(string.Format("{0}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace)); } } /// <summary> /// 基于txt文件的日志策略 /// </summary> public class LogStrategy : ILogStrategy { private static object _locker = new object();//锁对象 private static int _fileCountLimit = 31;//A long month of logs /// <summary> /// 写入日志 /// </summary> /// <param name="message">消息</param> public void Write(string message) { lock (_locker) { FileStream fs = null; StreamWriter sw = null; try { string basePath = AppDomain.CurrentDomain.BaseDirectory; string logName = string.Format("log{0}.txt", DateTime.Now.ToString("yyyyMMdd")); string fileName = Path.Combine(basePath, "logs", logName); FileInfo fileInfo = new FileInfo(fileName); if (!fileInfo.Directory.Exists) { fileInfo.Directory.Create(); } if (!fileInfo.Exists) { fileInfo.Create().Close(); //清理文件,只保留一定数量的文件 FileInfo[] fis = fileInfo.Directory.GetFiles("log*.txt", SearchOption.TopDirectoryOnly); if(fis.Length > _fileCountLimit) { Array.Sort(fis, delegate (FileInfo f1, FileInfo f2) { return f2.Name.CompareTo(f1.Name); }); for(int i = _fileCountLimit; i < fis.Length; i++) { FileInfo f = fis[i]; f.Delete(); } } } else if (fileInfo.Length > 2048 * 1000) { fileInfo.Delete(); } fs = fileInfo.OpenWrite(); sw = new StreamWriter(fs); sw.BaseStream.Seek(0, SeekOrigin.End); sw.Write("{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); sw.Write(Environment.NewLine); StackFrame stackFrame = FindStackFrame(); MethodBase methodBase = GetCallingMethodBase(stackFrame); string callingClass = methodBase.ReflectedType.FullName; string callingMethod = methodBase.Name; sw.Write("{0}.{1}", callingClass, callingMethod); sw.Write(Environment.NewLine); sw.Write(message); sw.Write(Environment.NewLine); sw.Write(Environment.NewLine); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { if (sw != null) { sw.Flush(); sw.Close(); } if (fs != null) { fs.Close(); } } } } private static StackFrame FindStackFrame() { StackTrace stackTrace = new StackTrace(); int i = 0; foreach (StackFrame item in stackTrace.GetFrames()) { MethodBase methodBase = item.GetMethod(); string name = MethodBase.GetCurrentMethod().Name; if (!methodBase.Name.Equals("Write") && !methodBase.Name.Equals(name)) return new StackFrame(i, false); i++; } return null; } private static MethodBase GetCallingMethodBase(StackFrame stackFrame) { return stackFrame == null ? MethodBase.GetCurrentMethod() : stackFrame.GetMethod(); } } }