C# winform程式將異常寫入日誌的方法

來源:互聯網
上載者:User

標籤:winform   http   c   com   string   檔案   

轉載地址:夏日裡的春天的部落格 http://hi.baidu.com/honfei/item/3a6f212998910099b73263b5

//出錯之後計入記錄檔
        private void SqlConnError(SqlException e2)
        {
            //如果是同一天的話,則開啟檔案在末尾寫入。如果不是同一天,則建立檔案寫入檔案

            //判斷是否存在檔案
            if (File.Exists(DateTime.Today.ToString("yyyyMMdd") + ".log"))
            {
                //如果存在檔案,則向檔案添加日誌
                StreamWriter sw =new StreamWriter(DateTime.Today.ToString("yyyyMMdd") + ".log",true);
                
                sw.WriteLine("============================================================================");
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+":");
                sw.WriteLine(e2.Message);
                sw.Close();
                return;
               
            }

                //如果檔案不存在,則建立檔案後向檔案添加日誌
            StreamWriter sw2 = new StreamWriter(DateTime.Today.ToString("yyyyMMdd") + ".log",true);

            sw2.WriteLine("============================================================================");
            sw2.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":");
            sw2.WriteLine(e2.Message);
            sw2.Close();
           
        }

//記錄檔結束

 

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

上面的方法的參數是sqlException類型的異常,你也可以重載此方法,用來處理所有異常,如果你改動參數類型的話(比如改成string或其他物件類型,下面的代碼也要做相應的轉換<最終要轉換成string類型>)

注意要對檔案進行操作要引入System.IO;

using System.IO;

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.