在配置文件中添加日志文件的存放路径:
1 <appSettings> 2 <add key="LogPath" value="H:\Logs" /> 3 </appSettings>
封装一个记录日志的类:
1 public class SystemLog 2 { 3 public static void WriteLogLine(string exceptionMessage) 4 { 5 string path = string.Empty; 6 try 7 { 8 path = ConfigurationManager.AppSettings["LogPath"]; 9 } 10 catch (Exception) 11 { 12 path = @"c:\temp"; 13 } 14 if (string.IsNullOrEmpty(path)) 15 path = @"c:\temp"; 16 try 17 { 18 //如果日志目录不存在,则创建该目录 19 if (!Directory.Exists(path)) 20 { 21 Directory.CreateDirectory(path); 22 } 23 string logFileName = path + "\\程序日志_" + DateTime.Now.ToString("yyyy_MM_dd_HH") + ".log"; 24 StringBuilder logContents = new StringBuilder(); 25 logContents.AppendLine(exceptionMessage); 26 //当天的日志文件不存在则新建,否则追加内容 27 StreamWriter sw = new StreamWriter(logFileName, true, System.Text.Encoding.Unicode); 28 sw.Write(DateTime.Now.ToString("yyyy-MM-dd hh:mm:sss") + " " + logContents.ToString()); 29 sw.Flush(); 30 sw.Close(); 31 } 32 catch (Exception) 33 { 34 } 35 } 36 }
在程序中使用日志类:
SystemLog.WriteLogLine("======>程序开始执行");//记录程序开始执行的时间
时间: 2024-10-14 14:16:04