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

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

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

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Web;
 7 
 8 namespace  Common
 9 {
10    public class LogHelper
11     {
12 
13        /// <summary>
14        /// 写入日志
15        /// </summary>
16         ///  <param name="action">日志说明</param>
17        /// <param name="msg">内容</param>
18         public static void WriteLog(string action,string msg)
19         {
20             string sj=DateTime.Now.ToString("yyyyMMdd");
21             string logFileName = action+sj+ ".txt";
22 
23 
24            string logPath = HttpContext.Current.Server.MapPath("~/Log/"+sj+"");
25             string fullPath = logPath + @"\" + logFileName;
26             
27             if (!Directory.Exists(logPath))
28             {
29                 Directory.CreateDirectory(logPath);
30             }
31             using (StreamWriter writer = File.AppendText(fullPath))
32             {
33                 Log(msg, writer);
34                 writer.Close();
35             }
36         }
37         private static void Log(string logMessage, TextWriter writer)
38         {
39             writer.Write("\r\nLog Entry : ");
40             writer.WriteLine("{0} {1} :", DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString());
41             writer.WriteLine(" {0}", logMessage);
42             writer.WriteLine("-------------------------------");
43             writer.Flush();
44         }
45     }
46 }

猜你喜欢

转载自www.cnblogs.com/apeng/p/12941121.html