分天记录日记类
public class LogHelp { private static object Block = new object(); #region 记录日志 /// <summary> /// 记录日志 /// </summary> /// <param name="msg"></param> public static void WriteLog(string msg) { //string path = @"C:\log.txt"; lock (Block) { string filename = DateTime.Now.ToString("yyyyMMdd"); //该日志文件会存在windows服务程序目录下 string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\" + filename + ".txt"; #region 删除前30天的日记 string sYue = DateTime.Now.AddDays(-30).ToString("yyyyMMdd"); DeleteFile(AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\" + sYue + ".txt"); #endregion if (!Directory.Exists(path))//如果不存在,则创建 { Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\"); } FileInfo file = new FileInfo(path); if (!file.Exists) { FileStream fs; fs = File.Create(path); fs.Close(); } else if (file.Length > 30 * 1000 * 1000) { file.Delete(); FileStream fs; fs = File.Create(path); fs.Close(); } using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fs)) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff") + " " + msg); } } } } public static void WriteLog2(string msg) { //string path = @"C:\log.txt"; lock (Block) { //该日志文件会存在windows服务程序目录下 string path = AppDomain.CurrentDomain.BaseDirectory + "\\log.txt"; FileInfo file = new FileInfo(path); if (!file.Exists) { FileStream fs; fs = File.Create(path); fs.Close(); } else if (file.Length > 30 * 1000 * 1000) { file.Delete(); FileStream fs; fs = File.Create(path); fs.Close(); } using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fs)) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff") + " " + msg); } } } } #endregion public static void DeleteFile(string path) { if (File.Exists(path))//判断文件是不是存在 { File.Delete(path);//如果存在则删除 } } }
作者:三小
声明:原创博客请在转载时保留原文链接或者在文章开头加上本人博客地址,如发现错误,欢迎批评指正。凡是转载于本人的文章,不能设置打赏功能,如有特殊需求请与本人联系!
作者:三小
声明:原创博客请在转载时保留原文链接或者在文章开头加上本人博客地址,如发现错误,欢迎批评指正。凡是转载于本人的文章,不能设置打赏功能,如有特殊需求请与本人联系!