• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C#向文本文件中写入日志    利用C#自带组件强壮程序日志 ...

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

  今天看了一篇文章,说的是使用微软自带的日志类写日志,然后晚上我就花了2个多小时自己动手试了一下,然后模仿者自己封装了一个类库。

  下面是自己封转的类:

 

/*****
 * 创建人:金河
 * 创建日期:2014-4-2 22:43
 * 内容:日志类
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace Log
{
    /// <summary>
    /// 继承TraceListener
    /// (1)必须要重写的方法void Write(string message);void WriteLine(string message);
    /// (2)子类方法重写必须和父类方法返回值、参数列表完全相同
    /// </summary>
    public class Log : TraceListener
    {

        private string m_fileName; // 文件名
        private string m_filePath; // 文件路径

        public string FileFullPath
        {
            get
            {
                if (Directory.Exists(m_filePath) == false)
                {
                    Directory.CreateDirectory(m_filePath);
                }
                return m_filePath.TrimEnd('/') + "/" + m_fileName;                
            }

        }

        public Log()
        {
            m_fileName = DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; // 默认文件名为 今天的日期
            m_filePath = AppDomain.CurrentDomain.BaseDirectory + "/log";  // 默认路径在当前域log文件夹下面     
        }
        public Log(string sFileName)
        {
            m_fileName = sFileName;
            m_filePath = AppDomain.CurrentDomain.BaseDirectory + "/log";  //默认路径在当前域log文件夹下面 
        }

        public override void Write(string message)
        {
            WriteLine(message);
        }

        public override void WriteLine(string message)
        {
            WriteLine(null, message);
        }


        /// <summary>
        /// 将异常或信息写入日志
        /// </summary>
        /// <param name="exception"></param>
        /// <param name="message"></param>
        public override void WriteLine(object exception, string message)
        {
            string sMsg = Environment.NewLine + DateTime.Now.ToString() + Environment.NewLine;
            if (!string.IsNullOrEmpty(message))  //如果信息不为空,加在最前面
            {
                sMsg += message;
            }
            if (exception is Exception)
            {
                Exception ex = (Exception)exception;
                sMsg += ex.Message + Environment.NewLine; // 错误提示
                sMsg += ex.StackTrace;  // 堆栈信息
            }
            else if (exception != null)
            {
                sMsg += exception.ToString();
            }
           

            File.AppendAllText(FileFullPath, sMsg);
        }

    }
}
View Code

 

 

下面是文档地址:

     


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#中的多线程使用--Thread类发布时间:2022-07-13
下一篇:
Print2flash在.NET(C#)64位中的使用,即文档在线预览(转载)发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap