.net自定义的Log类

来源:互联网 发布:兴业期货交易软件 编辑:程序博客网 时间:2024/05/17 10:57

实习已经三个月了,做了两三个木模块,发现要用到log的地方非常的多,一开始的时候用的是第三方的postsharp,用AOP的方式来记录运行时的log,实现方式看起来高大上,但是在代码移植的时候要求移植平台也要安装postsharp,这样子间接性的增加了代码的复杂度,在接下来接手代码的人理解起来会有一定的难度。

之前自己重写了文件生成的类和实现方式,发现对代码的复用性有一定的帮助,但是由于自己的水平有限不能做到大部分的使用,接下来会做一定的改进,争取做到通用。


昨天,在写新的项目的时候不再想用postsharp了,决定自己写一个简单的记录日志的类,以便自己日后使用过程中更加的方便。

由于用到的都是系统的类,所以可以直接复制粘贴,代码量也很少


using System;using System.IO;namespace CustomerLog{    /// <summary>    /// 保存日志    /// </summary>    public class Logging    {        #region 日志分类        /// <summary>        /// 保存普通日志        /// </summary>        /// <param name="message"></param>        public static void Writelog(string message)        {            string logContent = string.Format("[{0}] =>{1}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"), message);            SetFile(@"Log.txt", logContent);        }        /// <summary>        /// 保存关键日志        /// </summary>        /// <param name="message"></param>        public static void WriteKeylog(string message)        {            var logContent = string.Format("[{0}]=>{1}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"), message);            SetFile(@"KeyLog.txt", logContent);        }        /// <summary>        /// 保存错误信息日志        /// </summary>        /// <param name="ex"></param>        public static void WriteBuglog(Exception ex)        {            var logContent = string.Format("[{0}]错误发生在:{1},\r\n 内容:{2}",                DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"), ex.Source, ex.Message);            logContent += string.Format("\r\n [{0}] 跟踪:{1}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"),                ex.StackTrace);            SetFile(@"BugLog.txt", logContent);        }        #endregion        #region 通用操作        /// <summary>        /// 标准化写入过程,继承之后可自定义写入内容        /// 默认保存在debug目录的Log目录下        /// </summary>        /// <param name="filename">文件名</param>        /// <param name="logContent">写入内容</param>        protected static void SetFile(string filename, string logContent)        {            Isexist(); // 判断Log目录是否存在            string errLogFilePath = Environment.CurrentDirectory + @"\Log\" + filename.Trim();            StreamWriter sw;            if (!File.Exists(errLogFilePath))            {                FileStream fs1 = new FileStream(errLogFilePath, FileMode.Create, FileAccess.Write);                sw = new StreamWriter(fs1);            }            else            {                sw = new StreamWriter(errLogFilePath, true);            }            sw.WriteLine(logContent);            sw.Flush();            sw.Close();        }        // 判断是否存在日志文件        private static void Isexist()        {            string path = Environment.CurrentDirectory + @"\Log\";            if (!File.Exists(path))            {                Directory.CreateDirectory(path);            }        }        #endregion    }}


 ↓↓↓↓↓↓↓↓源代码一提供下载 ↓↓↓↓↓↓↓↓【目前只会用百度云盘分享下载,求大神传授其他更高效的下载分享方式】

http://pan.baidu.com/s/1o61Xqps

0 0