.net中 最常用的日志记录一般都知道log4net,相对需要引用dll和一些配置,其实可以最简单的自己生成日志,为了方便以后自己的使用,在此记录下
public static class Logger
{
public static void WriteLog(string msg)
{
string filePath = "";
string logPath = "";
try
{
string LogDir = ConfigurationManager.AppSettings["LogDir"].ToString();//文件名
filePath = @"C:\Log\" + LogDir + @"\"; //路径
logPath = filePath + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
using (StreamWriter sw = File.AppendText(logPath))
{
sw.WriteLine("消息:" + msg);
sw.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
sw.WriteLine("**************************************************");
sw.WriteLine();
sw.Flush();
sw.Close();
sw.Dispose();
}
}
catch (IOException e)
{
using (StreamWriter sw = File.AppendText(logPath))
{
sw.WriteLine("异常:" + e.Message);
sw.WriteLine("时间:" + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"));
sw.WriteLine("**************************************************");
sw.WriteLine();
sw.Flush();
sw.Close();
sw.Dispose();
}
}
}
}
在其他类中直接调用即可
Logger.WriteLog("这里是要记录的日志!");