• 写入文件日志方式


             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, " ")); _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); }
  • 相关阅读:
    U-Boot新手入门
    安装交叉编译工具
    Makefile 工程管理
    gcc基本用法
    poj 3264 Balanced Lineup
    hdoj 1166 敌兵布阵
    poj 1363 Rails
    poj 1028 Web Navigation
    zoj 3621 Factorial Problem in Base K
    poj1861最小生成树
  • 原文地址:https://www.cnblogs.com/Warmsunshine/p/9699363.html
Copyright © 2020-2023  润新知