第一步:增加日志方法
说明:新增类Log.cs。
public class Log
{
//日期文件夹路径
public static string strDicPath = "";
//在处理话类型之前自动调用,去检查日志文件夹是否存在
static Log()
{
//检测启动目录:
strDicPath = System.Threading.Thread.GetDomain().BaseDirectory.Replace("\\bin\\Debug", "") + "\\ALLLogs\\";
//创建文件夹
if (!Directory.Exists(strDicPath))
{
Directory.CreateDirectory(strDicPath);
}
}
//读写锁,当资源处于写入模式时,其他线程写入需要等待本次写入结束之后才能继续写入
private static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
/// <summary>
/// 写入日志.
/// </summary>
/// <param name="strList">The STR list.</param>
/// <remarks> </remarks>
/// <Description></Description>
public void WriteLog(params object[] strList)
{
if (strList.Count() == 0) return;
string strPath = ""; //文件路径
try
{
strPath = strDicPath + string.Format("{0:yyyy年MM月dd日}", DateTime.Now) + "日志记录.txt";
}
catch (Exception e)
{
strDicPath = "C:\\temp\\log\\";
strPath = strDicPath + string.Format("{0:yyyy年MM月dd日}", DateTime.Now) + "日志记录.txt";
}
try
{
//自动创建文件(但不能创建文件夹),并设置文件内容追加模式,使用using会自动释放FileSteam资源
LogWriteLock.EnterWriteLock();
using (FileStream stream = new FileStream(strPath, FileMode.Append))
{
StreamWriter write = new StreamWriter(stream);
string content = "\r\n-----start-----\r\n";
foreach (var str in strList)
{
content += "Timestamp:" + DateTime.Now.ToString() + "\r\n" + "Message:" + str;
}
content += "\r\n-----end-----\r\n";
write.WriteLine(content);
//关闭并销毁流写入文件
write.Close();
write.Dispose();
}
}
catch (Exception)
{
}
finally
{
LogWriteLock.ExitWriteLock();
}
}
}
第二步:调用日志方法
说明:在需要写入日志的地方调用此方法。
public Log log = null;
log= new Log();
try
{
//处理代码
//处理代码
log.WriteLog("此处添加需要添加的日志!");
}
catch (Exception ex)
{
ltwoLog.WriteLog(ex.ToString());
}