你的位置:首页 > ASP.net教程

[ASP.net教程]测试程序的时候用到写参数或者错误日志的几个方法,用来方便发现错误


/// <summary>  /// 写接口日志类(by mo)  /// </summary>  public class LogWrite  {    /// <summary>    /// 写异常日志    /// </summary>    /// <param name="path">相对路径("~/log")</param>    /// <param name="content">异常内容</param>    /// <param name="filename">文件名(不能带后缀格式,默认保存txt文本)</param>    public static void WriteBug(string path, string content, string filename)    {      StringBuilder sb = new StringBuilder();      sb.Append("----------bug日志--------\r\n");      sb.AppendFormat("时间:{0}\r\n异常内容:{1}\r\n\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm"), content);      if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(path)))      {        System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));      }      System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath(path + filename + ".txt"), sb.ToString(), System.Text.Encoding.Default);    }    /// <summary>    /// 写请求参数日志(用于接口调用)    /// </summary>    /// <param name="path">路径</param>    /// <param name="title">标题</param>    /// <param name="content">内容</param>    /// <param name="filename">文件名(不能带后缀格式,默认保存txt文本)</param>    public static void WriteRequstParameters(string path, string title, string content, string filename)    {      StringBuilder sb = new StringBuilder();      sb.AppendFormat("----------{0}--------\r\n", title);      sb.AppendFormat("请求时间={0},{1}\r\n\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm"), content);      if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(path)))      {        System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));      }      System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath(path + filename + ".txt"), sb.ToString(), System.Text.Encoding.Default);    }    /// <summary>    /// 写所有请求参数日志    /// </summary>    /// <param name="path">相对路径</param>    /// <param name="title">标题</param>    /// <param name="filename">文件名(不能带后缀格式,默认保存txt文本)</param>    public static void WriteRequstStream(string path, string title, string filename)    {      string a = string.Empty;      using (System.IO.Stream stream = System.Web.HttpContext.Current.Request.InputStream)      {        using (System.IO.StreamReader sr = new System.IO.StreamReader(stream))        {          a = sr.ReadToEnd();        }      }      StringBuilder sb = new StringBuilder();      sb.AppendFormat("----------{0}--------\r\n", title);      sb.AppendFormat("请求时间:{0},\r\n请求参数:{1}\r\n\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm"), a);      if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(path)))      {        System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));      }      System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath(path + filename + ".txt"), sb.ToString(), System.Text.Encoding.Default);    }  }