C#中的日志类

把程序信息,日期,调用者信息都输出到一个日志文件是很有意义的事,有助于定位错误,获知程序运行状况,可观察到复现率低的bug。在java中有log4j,在C#中,自己写了一个简易的日志类,调用时用LogHelper.log("message");即可。日志输出到history.log。日志格式形如:

[ 2012-2-13 14:49:34 ]: ReadExcel2.Form1.buttonTestLog_Click() message!
[ 2012-2-13 14:49:35 ]: ReadExcel2.Form1.buttonTestLog_Click() message!
[ 2012-2-13 14:49:35 ]: ReadExcel2.Form1.buttonTestLog_Click() message!


using System;

using System.Collections.Generic;

using System.Text;

using System.IO;


using System.Reflection;

using System.Diagnostics;


namespace ReadExcel2

{

    //日志类

    class LogHelper

    {

        private static String logFileName = "history.log";


        public static void log(String message)

        {

            if (!File.Exists(logFileName))

            {

                File.CreateText(logFileName);

            }


            using (StreamWriter sw = File.AppendText(logFileName))

            {

                //获取调用者的信息

                StackTrace trace = new StackTrace(); 

                MethodBase method = trace.GetFrame(1).GetMethod();

                String methodInfo = method.DeclaringType.FullName + "." + method.Name + "()";


                //输出日期、调用者信息、message

                message = methodInfo + message;

                String strDate = DateTime.Now.ToString();

                sw.WriteLine("[ "+strDate+" ]: "+message);

            }

        }

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值