写入文件日志方式

         private static readonly object _LockObject = new object();
private
static Random _Random = new Random(); private static DateTime _LastDeleteTime = DateTime.Now; //文件夹名称 _FilePath=@"Logs" 文件名 _FileName, public static void WriteLog(string _FilePath, string _FileName, string _Msg) { lock (_LockObject) { try { var _Path = AppDomain.CurrentDomain.BaseDirectory + _FilePath + @"\"; if (!Directory.Exists(_Path)) { Directory.CreateDirectory(_Path); } _FileName = _FileName + "_" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; if (_Random.Next(10) >= 9 && File.Exists(_Path + _FileName)) { FileInfo fileInfo = new FileInfo(_Path + _FileName); if (fileInfo.Length > 10485760)//10M { fileInfo.MoveTo(_Path + _FileName.Replace(".", string.Format("_{0}.", DateTime.Now.ToString("HHmmss")))); } } System.IO.StreamWriter _Writer = new System.IO.StreamWriter ( _Path + _FileName, true, System.Text.Encoding.Default ); _Writer.WriteLine(string.Concat("[", DateTime.Now.ToString("HH:mm:ss"), "] ", _Msg, "\n\n")); _Writer.Close(); // 删除超过15天的日志 if ((DateTime.Now.Day != _LastDeleteTime.Day)) { _LastDeleteTime = DateTime.Now; var files = Directory.GetFiles(_Path); foreach (var file in files.Where(t => t.EndsWith(".txt"))) { var fileInfo = new FileInfo(file); if (!IsRealMatch(fileInfo.Name.ToLower(), "_[0-9]{4}[-][0-9]{2}[-][0-9]{2}[^.]{0,20}[.]txt")) { continue; } if ((DateTime.Now - fileInfo.LastWriteTime).TotalDays > 15) { File.Delete(file); } } } } catch { } } } public static bool IsRealMatch(string inputInfo, string strInfo) { return IsMatch(inputInfo, strInfo, RegexOptions.IgnoreCase | RegexOptions.Singleline); } public static bool IsMatch(string inputInfo, string strInfo, RegexOptions options) { return Regex.IsMatch(inputInfo, strInfo, options); }

猜你喜欢

转载自www.cnblogs.com/Warmsunshine/p/9699363.html