【个人使用.Net类库】(2)Log日志记录类

8/3/2015来源:C#应用人气:1456

【个人使用.Net类库】(2)Log日志记录类

开发接口程序时,要保证程序稳定运行就要时刻监控接口程序发送和接收的数据,这就需要一个日志记录的类将需要的信息记录在日志文件中,便于自己维护接口程序。(Web系统也是如此,只是对应的日志实现比这个要复杂一点)。

刚开始考虑的比较少,没有加入控制日志文件数量的功能。运行了一段时间,文件夹内的Log文件如下所示:

QQ截图20140717172227

如果是这样,那运行一年不就三百多个日志文件了,想一想这太可怕了。通过查找资料,发现.Net中的FileInfo存有文件的信息(包括名称,创建时间,文件大小等),那就自己定义一个文件比较器实现文件按照名称降序排序(采用降序是因为要保留近期的Log文件)。文件比较强实现的类如下所示:

using System;using System.Collections;using System.IO;namespace DotNetCommon.Logger{    /// <summary>    /// 实现IComparer接口,实现文件按名称降序排序    /// </summary>    class FileSorter:IComparer    {        /// <summary>        /// 继承IComparer接口必须实现的方法        /// </summary>        /// <param name="x">FileInfo文件x</param>        /// <param name="y">FileInfo文件y</param>        /// <returns></returns>        public int Compare(object x, object y)        {            if (x == null && y == null)                return 0;            if (x == null) return -1;            if (y == null) return 1;            var xInfo = (FileInfo) x;            var yInfo = (FileInfo) y;            //按名称降序排序            return String.Compare(yInfo.FullName, xInfo.FullName, StringComparison.Ordinal);        }    }}

接下来就是实现日志文件自动删除。具体思路是,当创建一个新的日志文件时,检测是否超出最大日志允许数量。若超出,使用上面定义的比较器删除之。日志自动删除代码方法如下:

/// <summary>        /// 删除Log目录多余的日志文件        /// </summary>        public void DeleteUnnecessaryLogFiles()        {            var path = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"Log\");            var fileInfos = path.GetFiles("*.log");            Array.Sort(fileInfos, new FileSorter());            if (fileInfos.Length <= (_maxLogNum - 1)) return;            for (var i = _maxLogNum - 1; i < fileInfos.Length; i++)            {                var filepath = fileInfos[i].FullName;                if (!File.Exists(filepath)) continue;                try                {                    File.Delete(filepath);                }                catch (Exception)                {                    return;                }            }        }

Log日志类具体代码如下所示:

using System;using System.IO;using System.Text;namespace DotNetCommon.Logger{    /// <summary>    /// 类说明:日志记录(文本记录和byte数组记录)    /// 编码人:鞠小军    /// 联系方式:binghuojxj@QQ.com    /// </summary>    class Log    {        /// <summary>        /// 程序当前目录        /// </summary>        PRivate readonly DirectoryInfo _dir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);        /// <summary>        /// 默认日志文件最大数量为20        /// </summary>        private readonly int _maxLogNum = 20;        /// <summary>        /// 构造函数        /// </summary>        /// <param name="maxLogNum">Log目录下日志文件的最大数量</param>        public Log(int maxLogNum)        {            _maxLogNum = maxLogNum;        }        /// <summary>        /// 字符串写入日志文件        /// </summary>        /// <param name="msg">写入的字符串文本</param>        public void WriteLog_Txt(string msg)        {            FileStream stream = null;            var sb = new StringBuilder();            var path = _dir + "Log";            if (!Directory.Exists(path))            {                Directory.CreateDirectory(path);            }            var str2 = path + @"\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";            sb.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ");            sb.Append(msg);            var bytes = Encoding.UTF8.GetBytes(sb + "\r\n");            try            {                if (!File.Exists(str2))                    DeleteUnnecessaryLogFiles();                stream = File.OpenWrite(str2);                stream.Position = stream.Length;                stream.Write(bytes, 0, bytes.Length);            }            catch (Exception exception)            {                Console.WriteLine("文件打开失败{0}", exception.Message);            }            finally            {                if (stream != null) stream.Close();            }        }        /// <summary>        /// 字节数组写入日志文件        /// </summary>        /// <param name="msg">提示信息</param>        /// <param name="data">字节数组</param>        public void WriteLog_Bytes(string msg, byte[] data)        {            FileStream stream = null;            var sb = new StringBuilder();            var path = _dir + @"\Log";            if (!Directory.Exists(path))            {                Directory.CreateDirectory(path);            }            var str2 = path + @"\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";            sb.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ");            sb.Append(msg);            foreach (var num in data)            {                sb.AppendFormat("{0:x2} ", num);            }            var bytes = Encoding.UTF8.GetBytes(sb + "\r\n");            try            {                if (!File.Exists(str2))                    DeleteUnnecessaryLogFiles();                stream = File.OpenWrite(str2);                stream.Position = stream.Length;                stream.Write(bytes, 0, bytes.Length);            }            catch (Exception exception)            {                Console.WriteLine("文件打开失败{0}", exception.Message);            }            finally            {                if (stream != null) stream.Close();            }        }        /// <summary>        /// 删除Log目录多余的日志文件        /// </summary>        public void DeleteUnnecessaryLogFiles()        {            var path = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + @"Log\");            var fileInfos = path.GetFiles("*.log");            Array.Sort(fileInfos, new FileSorter());            if (fileInfos.Length <= (_maxLogNum - 1)) return;            for (var i = _maxLogNum - 1; i < fileInfos.Length; i++)            {                var filepath = fileInfos[i].FullName;                if (!File.Exists(filepath)) continue;                try                {                    File.Delete(filepath);                }                catch (Exception)                {                    return;                }            }        }    }}

当前日志类不够完善,我还没有加上文件超过固定大小(如超出2M)自动创建新文件等等必要的功能,后续会逐渐完善。大家有什么好建议,欢迎大家拍砖,哈哈。