zoukankan      html  css  js  c++  java
  • 初识IO流——IO流实战之记录错误日志

      在web项目中经常会遇到各种各样的异常,除了调试之外,我们还可以通过文本来记录异常。这样也可以迅速找出异常所在。

      

      下面写一个小测试。页面加载的时候在Page_Load()方法中给出一个异常,捕获到异常后就调用我们写好的方法来将异常写入文本文件中。

      具体实现:

     1 protected void Page_Load(object sender, EventArgs e)
     2         {
     3 
     4             string test_str = "I see you !";
     5 
     6             try
     7             {
     8 
     9                 Int32 test_num = Convert.ToInt32(test_str);
    10 
    11             }
    12             catch (Exception ex)
    13             {
    14 
    15                 getErrorMessage(ex.ToString());
    16 
    17             }
    18         }
    19 
    20 
    21 
    22 
    23 
    24         public static void getErrorMessage(string errorMessage)
    25         {
    26             try
    27             {
    28                 /*相对路径(文件相对于项目)*/
    29                 string outfile = "/Error/" + "Error-" + DateTime.Today.ToString("yyyy-MM-dd") + ".txt";
    30 
    31                 /*获取项目的根目录并和outfile组合成文件的完整路径*/
    32                 string path = AppDomain.CurrentDomain.BaseDirectory + outfile;
    33 
    34                 /*判断文件是否存在,如果不存在则创建*/
    35                 if (!File.Exists(path))
    36                 {
    37                     File.Create(path).Close();
    38                 }
    39                 using (StreamWriter writer = File.AppendText(path))
    40                 {
    41                     /*写入自定义的数据和获取到的异常信息*/
    42                     writer.WriteLine("ErrorMessage: ");
    43                     writer.WriteLine("Time: {0}", DateTime.Now.ToString("yyyy/MM/dd  hh:mm:ss"));
    44                     writer.WriteLine("Url: {0}", System.Web.HttpContext.Current.Request.Url.ToString());
    45                     writer.WriteLine("Detial: {0}", errorMessage);
    46                     writer.WriteLine("————————————————————————————————————————————————————————————————————");
    47                 }
    48             }
    49             catch (Exception ex)
    50             {
    51                 getErrorMessage(ex.ToString());
    52             }
    53         }

      这样我们就可以在项目的Error目录找到我们的日志文件,并可以通过日志文件迅速的找到异常所在。下面是实现的日志截图:

      

      在具体的项目中,可以写一个工具类来实现该方法,代码变得简洁的同时也可以让整个系统的架构更清晰。

  • 相关阅读:
    MVC模式-----struts2框架(2)
    MVC模式-----struts2框架
    html的<h>标签
    jsp脚本元素
    LeetCode "Paint House"
    LeetCode "Longest Substring with At Most Two Distinct Characters"
    LeetCode "Graph Valid Tree"
    LeetCode "Shortest Word Distance"
    LeetCode "Verify Preorder Sequence in Binary Search Tree"
    LeetCode "Binary Tree Upside Down"
  • 原文地址:https://www.cnblogs.com/SunshineAgain/p/5699283.html
Copyright © 2011-2022 走看看