当前位置: 移动技术网 > IT编程>开发语言>c# > C#自定义日志记录

C#自定义日志记录

2019年07月18日  | 移动技术网IT编程  | 我要评论

废话不多说,直接上代码: 

很简单:将类复制到项目中,最后在配置文件上配置一下:logurl即可。 默认保存在:项目/temp/log

/// <summary>
  /// 日志类
  /// </summary>
  /// <remarks>creator: v-lxh createtime: 2016/7/26 11:18:09</remarks>
  /// <description></description>
  public class log
  {
    /// <summary>
    /// 写入日志.
    /// </summary>
    /// <param name="strlist">the str list.</param>
    /// <remarks>creator: v-lxh createtime: 2016/7/26 11:18:09</remarks>
    /// <description></description>
    public static void writelog(params object[] strlist)
    {
      //判断是否开启日志模式
      //if (!logmodel) return;
      if (strlist.count() == 0) return;
      //日志文件路径
      string strdicpath = "";
      try
      {
        strdicpath = httpcontext.current.server.mappath("~/temp/log/");
        if (strdicpath == null || strdicpath == "")
        {
          strdicpath = system.configuration.configurationmanager.appsettings["logurl"] + "/temp/log/";
        }
      }
      catch (exception e)
      {
        strdicpath = system.configuration.configurationmanager.appsettings["logurl"] + "/temp/log/";
      }
      string strpath = strdicpath + string.format("{0:yyyy年-mm月-dd日}", datetime.now) + "日志记录.txt";
      if (!directory.exists(strdicpath))
      {
        directory.createdirectory(strdicpath);
      }
      if (!file.exists(strpath))
      {
        using (filestream fs = file.create(strpath)) { }
      }
      string str = file.readalltext(strpath);
      stringbuilder sb = new stringbuilder();
      foreach (var item in strlist)
      {
        sb.append("\r\n" + datetime.now.tostring() + "-----" + item + "");
      }
      file.writealltext(strpath, sb.tostring() + "\r\n-----z-----\r\n" + str);
    }

  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网