一定谨记!!!!!
所写的路径如果不存在的话是会抛异常的
判断路径(文件夹)是否存在,如果不存在就创建。
public static void log(string logName , params string [] args)
{
1.获取当前文件的路径:
string logPath=Current.Server.MapPath(" ");
2.创建流
StreamWriter sw=File.AppendText(logPath,+"/log.txt");
3.创建sb
StringBuilder sb=new StringBuilder();
sb.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").ToString());
4.循环遍历args
foreach(string arg in args)
{
sb.Append(arg+"\t");
}
5.写入
sw.WriteLine(sb.ToString());//不用换行,这个是每次一行
6.关闭流
sw.Close();
sw.Dispose();
}
网友的方法:
- /// <summary>
- /// 日志文件记录
- /// </summary>
- /// <param name="program">程序</param>
- /// <param name="msg">内容</param>
- public static void Log(string program, string msg)
- {
- string path = Path.Combine("./log");
- if (!Directory.Exists(path))//判断是否有该文件
- Directory.CreateDirectory(path);//不存在则创建log文件夹
- string info = path + "\\" + program;
- if (!Directory.Exists(info))
- Directory.CreateDirectory(info);
- string logFileName = path + "\\" + program + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";//生成日志文件
- StreamWriter writer;
- try
- {
- writer = File.AppendText(logFileName);//文件中添加文件流
- writer.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " " + msg);
- writer.Flush();
- writer.Close();
- }
- catch (Exception e)
- {
- writer = File.AppendText(logFileName);
- writer.WriteLine(DateTime.Now.ToString("日志记录错误HH:mm:ss") + " " + e.Message + " " + msg);
- writer.Flush();
- writer.Close();
- }
- }