using System;
using System.IO;
using System.Web;
public class SimpleLog
{
#region 写日志,指定文件夹、文件名称、内容
public static void Write(string logPath, string fileName, string content)
{
try
{
// 常用的获取服务器目录的方法,但在多线程环境下,会调用失败;
// string strPath = HttpContext.Current.Server.MapPath(logPah);
string folderPath = HttpRuntime.AppDomainAppPath + "/log";
if (logPath.Trim() != "")
{
folderPath += "/" + logPath;
}
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
folderPath = folderPath + "\\" + fileName + ".txt";
StreamWriter fs = new StreamWriter(folderPath, true, System.Text.Encoding.UTF8);
fs.WriteLine(content);
fs.Close();
}
catch(Exception ex)
{ }
}
#endregion
#region 在LOG文件夹根目录下写日志
public static void Write(string content)
{
content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + content;
string fileName = DateTime.Today.ToString("yyyyMMdd");
Write("", fileName, content);
}
#endregion
#region 在特定文件夹写日志
public static void Write(string folderName, string content)
{
string fileName = DateTime.Today.ToString("yyyyMMdd");
content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + content;
Write(folderName, fileName, content);
}
#endregion
}
只包含写的方法,用来记录一些简单的内容,更高级的建议还是使用Log4Net这类专业的工具。
调用方法很简单:
SimpleLog.Write("xxx", “要记录的内容”);
或者用异步的方式:
var task = new TaskFactory().StartNew(() =>
{
SimpleLog.Write("xxx", "要记录的内容");
});
会在站点根目录的/log/xxx目录下生成以当前日期命名的文件,如20161005.txt