打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C#代码写错误日志(转)
C#代码写错误日志(转)
2009-08-10 11:13

1.新建一个文件夹存放LOG文件,我建的文件夹为logs,保证这个文件具有写入的权限.

2.新建一个类:Clogs.cs

    private StreamWriter swWrite = null;//写文件
    private string logpath = null;//日志路径

    /// <summary>
    /// 判断是否有当天日志,如果没有则创建
    /// </summary>
    /// <param name="sCurDate">日期</param>
    /// <param name="pathweb">路径</param>
    private void InitLog(string sCurDate,string pathweb)
    {
        if (sCurDate!=""||sCurDate!=null)
        {
             logpath = pathweb+"\"+ sCurDate + ".log";
        }
        if (!File.Exists(logpath))
        {
            swWrite = File.CreateText(logpath);
        }
        else
        {
            swWrite = File.AppendText(logpath);
        }
    }

    /// <summary>
    /// 日志主方法
    /// </summary>
    /// <param name="sMess">错误</param>
    /// <param name="ex">异常</param>
    /// <param name="path1">日志路径</param>
    public void LogError(string sMess, Exception ex,string path1)
    {
        DateTime dt = DateTime.Now;
        string sCurDate = dt.ToShortDateString();
        if (swWrite == null)
        {
            InitLog(sCurDate,path1);
        }
        swWrite.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss"));
        swWrite.WriteLine("输出信息:"+sMess);
        if (ex != null)
        {
            swWrite.WriteLine("异常信息:\r\n"+ex.ToString());
            swWrite.WriteLine("异常堆栈:\r\n" + ex.StackTrace);
        }
        swWrite.WriteLine("\r\n");
        swWrite.Flush();
        swWrite.Dispose();
    }

3.调用类.

    private string showData(string userid)
    {
        string name = null;
        SqlConnection con = null;
        SqlCommand com = null;
        SqlDataReader sdr = null;
        try
        {
            string sql = "select user_name from hr_basic where user_account='" + userid + "'";
            con = new SqlConnection(constr);
            com = new SqlCommand(sql,con);
            con.Open();
            sdr = com.ExecuteReader();
            while (sdr.Read())
            {
                name = sdr["user_name"].ToString();
            }
            sdr.Dispose();
        }
        catch (Exception ex)
        {
            string path1 = Server.MapPath("logs");
            Clogs cl = new Clogs();
            cl.LogError("错误信息",ex,path1);
        }
        finally
        {
            com.Dispose();
            con.Close();
        }
        return name;

    }

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
100行代码实现了多线程,批量写入,文件分块的日志方法(上)
.NET Jquery MsSql实现仿百度输入自动补全
asp.net三层架构详解
.NET ORM框架(一)
C# 简易异步日志类 [ C# | Log | TextWriterTraceListen...
CYQ.Data 轻量数据层之路 SQLHelper 回头太难(八)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服