c#创建日志文件

时间:2021-11-13 07:55:53

/// <summary>
/// 日志文件记录
/// </summary>
/// <param>日志描述</param>
/// <param>写入信息</param>
public static void WriteMsg(string logName, string msg)
{
try
{
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 writer = File.AppendText(logFileName);//文件中添加文件流

writer.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " " + logName + "\r\n" + msg);
writer.WriteLine("--------------------------------分割线--------------------------------");
writer.Flush();
writer.Close();
}
catch (Exception e)
{
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 writer = File.AppendText(logFileName);//文件中添加文件流
writer.WriteLine(DateTime.Now.ToString("日志记录错误HH:mm:ss") + "\r\n " + e.Message + " " + msg);
writer.WriteLine("--------------------------------分割线--------------------------------");
writer.Flush();
writer.Close();
}
}