今天我们来写一个记录日志的方法
日志是我们在开发环境中必不可少的记录Bug点的东西。那么用C#中的原生File应该怎么去写呢?
下面我们一起来看一下
private static readonly object writeFile = new object();
public static void WriteLog(string debugstr)
{
WriteLog(HttpContext.Current.Server.MapPath("~/Log"), debugstr);
}
private static void WriteLog(string path, string debugstr)
{
lock (writeFile)
{
try
{
string filename = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
//日志目录
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
using (FileStream fs = new FileStream(path + "/" + filename, FileMode.Append,FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
{
sw.WriteLine(DateTime.Now.ToString() + " " + debugstr + "\r\n");
}
}
}
catch (Exception eror)
{
string str = eror.ToString();
WriteLog(path, debugstr);
}
}
}
内容比较简单,提供了一个默认的重载。直接调用写内容就可以了。
就这样
原文:https://www.cnblogs.com/SevenWang/p/14308030.html