.net后台记录输出日志到文本,向文本文件追加字符数据

有些时候不方便F5调试。这样输出到文本。可以当调试,又可以当错误日志,或操作日志

上代码 

using System;
using System.Web;
using System.IO;

/// <summary>
/// 输出文本日志到文件~/log目录
/// </summary>
/// <param name="title">方便查询的关键字</param>
/// <param name="logStr">日志内容</param>
public static void CreateWebLog(string title,string logStr)
{
	try
	{
		string dir = System.Web.HttpContext.Current.Server.MapPath("~/log");
		if (Directory.Exists(dir) == false)
		{
			Directory.CreateDirectory(dir);
		}
		string strFilePath = System.Web.HttpContext.Current.Server.MapPath("~/log/log_" + DateTime.Now.ToString("yyyyMMdd") + ".txt");
		FileInfo logFile = new FileInfo(strFilePath);
		System.IO.FileStream fs;
		if (logFile.Exists)
		{
			fs = new System.IO.FileStream(strFilePath, System.IO.FileMode.Append);
		}
		else
		{
			fs = new System.IO.FileStream(strFilePath, System.IO.FileMode.Create);
		}
		System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);
		sw.WriteLine("---------------------------------------------------------------------------------------");
		sw.WriteLine("-----------------------------" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + "---------------------------------------");
		sw.WriteLine("-----------------------------" + title + "----------------------------------------------------------");
		sw.WriteLine("---------------------------------------------------------------------------------------");
		sw.WriteLine(logStr);
		sw.Close();
		fs.Close();
	}
	catch (Exception)
	{

	}

}

 

posted @ 2020-06-25 10:33  离。  阅读(71)  评论(0编辑  收藏