C#向文本文件中写入日志

  今天看了一篇文章,说的是使用微软自带的日志类写日志,然后晚上我就花了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

下面是文档地址:

   利用C#自带组件强壮程序日志

     

原文地址:https://www.cnblogs.com/wang7/p/3641890.html