public static void WriteMsg(string logName, string msg) { try { //string path = Path.Combine("./log"); string path = Application.StartupPath + "./log"; Directory.CreateDirectory(path); string logFileName = path + "\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";//生成日志文件 if (!File.Exists(logFileName))//判断日志是否为当天 { FileStream fs; fs = File.Create(logFileName);//创建文件 fs.Close(); } StreamWriter write = File.AppendText(logFileName);//文件中添加文件流 write.WriteLine(DateTime.Now.ToString()+": "+ logName + msg); //write.WriteLine("----------------分割线--------------------"); write.Flush(); write.Close(); } catch (Exception ) { string path = Path.Combine("./log"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); string logFileName = path + "\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log"; if (!File.Exists(logFileName))//判断日志是否为当天 { FileStream fs; fs = File.Create(logFileName);//创建文件 fs.Close(); } StreamWriter write = File.AppendText(logFileName);//文件中添加文件流 //write.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "" + logName + " " + msg); write.WriteLine(DateTime.Now.ToString() + ": " + logName + msg); // write.WriteLine("----------------分割线--------------------"); write.Flush(); write.Close(); } } }
创建一Log类,直接类调用就可以。