一个不需要Log4Net的写日志的简单方法

时间:2023-03-10 01:30:35
一个不需要Log4Net的写日志的简单方法

有些项目写日志时会选择大名鼎鼎的Log4Net。而在我们使用它时,总会出现一些诸如版本不匹配而造成的写日志失败的情况,还要改web.config,还要改AssemblyInfo。而且,它的失败,并不是以日志的形式展现,而是“无反应”,你无法知道是哪里出了问题,最终的效果就是“没有输出日志且不知道为什么,需要根据百度和经验判断”。索性放弃。我只是要输出文本日志而已,杀鸡不要用牛刀了。

以下是一个简单实用的日志类,无需配置。

 public class LogHelper
{ public static void WriteLog(string msg)
{
string logFileName = DateTime.Now.ToString("yyyyMMdd") + ".txt"; //此处根据不同的项目类型用不同的方法取路径
//string logPath = base.Context.Server.MapPath("") + @"\LOG";
//string logPath = HttpContext.Current.Server.MapPath("") + @"\LOG";
string logPath = AppDomain.CurrentDomain.BaseDirectory + @"\log";
string fullPath = logPath + @"\" + logFileName; if (!Directory.Exists(logPath))
{
Directory.CreateDirectory(logPath);
}
using (StreamWriter writer = File.AppendText(fullPath))
{
Log(msg, writer);
writer.Close();
}
}
private static void Log(string logMessage, TextWriter writer)
{
writer.Write("\r\nLog Entry : ");
writer.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
writer.WriteLine(" :{0}", logMessage);
writer.WriteLine("-------------------------------");
writer.Flush();
}
}