首页 > Web开发 > 详细

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

时间:2017-08-15 13:48:29      阅读:301      评论:0      收藏:0      [点我收藏+]

有些项目写日志时会选择大名鼎鼎的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();
        }
    }

 

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

原文:http://www.cnblogs.com/Sabre/p/7364619.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!