博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C# 实现一个Log日志文件 以每2Mb创建一个新的日志

Posted on 2011-12-02 21:52  moss_tan_jun  阅读(370)  评论(0编辑  收藏  举报

这个日志文件存放在程序的bin文件夹下得Debug中

static private string logpathlog = AppDomain.CurrentDomain.BaseDirectory + "log.txt";

static public void writelog(string classname)
{
string path = logpathlog;
if (!File.Exists(path))
{
// Create a file to write to.
using (File.Create(path)) { }
}

FileInfo fileinfo = new FileInfo(path);
if (fileinfo.Length > 1024 * 1024 * 2)
{
File.Move(path, AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToString("yyyyMMddHHmmss") + "log.txt");

if (!File.Exists(path))
{
using (File.Create(path)) { }
}

}

using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "" + "\t\n");
sw.WriteLine(classname + "\t\n");
sw.WriteLine("------------------------------------------------------------------------" + "\t\n");
sw.Close();
}

}