写入文件日志方式

         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); }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值