给程序加入记日志的功能

来源:互联网 发布:软件 委托 编辑:程序博客网 时间:2024/06/11 07:42

以前在写程序的过程中总是忽视了记日志的功能,后来在给客户部署的过程中,出现了莫名其妙的问题,但是客户都是政府机构的内外网物理隔离的系统,不能互连互通而且是涉密环境,被迫开启了日志功能,感到了日志功能在调试程序过程中的便捷,作为一个良好的习惯,以后每一个程序中我都要首先建立日志功能,为了顺应在不想要的环境中最好在web.config中加入一个开关,ok!

1、  <add key="writeLog" value="1"></add>

2、其次建一个日志类

using System;
using System.IO;
using System.Text;
using System.Configuration;
namespace Log
{
 /// <summary>
 /// Summary description for docman.
 /// </summary>
 public class logEvents
 {  
  public logEvents()
  {
  }

  public void logWriteText( string traceMsg )
  {
   if( ConfigurationSettings.AppSettings["writeLog"] =="1" )
   {
    string filePath =  Path.Combine( AppDomain.CurrentDomain.BaseDirectory, "logs//logs.txt" );
    byte [] buffer = Encoding.ASCII.GetBytes( traceMsg );
    StreamWriter rw= new StreamWriter( filePath,true);
    rw.WriteLine( traceMsg + "   " + System.DateTime.Now.ToString() );
    rw.Flush();
    rw.Close();
   }
  }
 }
}
 

3 、在想要日志的地方调用。

 

 二、获取页面的执行时间代码

   System.DateTime startTime = (System.DateTime)Application["StartTime"];
   System.DateTime endTime = System.DateTime.Now;
   System.TimeSpan ts = endTime - startTime;
   Response.Write("页面执行时间:"+ ts.Milliseconds +" 毫秒");