1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6 //using System.Diagnostics;
7 using System.IO;
8
9
10 namespace ConsoleApplication1
11 {
12 class Program
13 {
14 static void Main(string[] args)
15 {
16 int i;
17 int j;
18
19 try
20 {
21 i = 0;
22 j = 2 / i;
23 }
24 catch (Exception ex)
25 {
26 WriteLog(ex);
27 }
28 finally
29 {
30 j = 2 / 1;
31 Console.Write(j);
32 Console.ReadLine();
33 }
34 }
35
36 ///<summary>
37 ///打印异常
38 ///</summary>
39 ///<param name="ex">异常</param>
40 ///<param name="LogAddress">日志文件地址</param>
41 public static void WriteLog(Exception ex, string LogAddress = "")
42 {
43 //if日志文件为空,默认在Debug目录下建立
44 if (LogAddress == "")
45 {
46 LogAddress = Environment.CurrentDirectory + '\\' +
47 DateTime.Now.Year + '-' +
48 DateTime.Now.Month + '-' +
49 DateTime.Now.Day + "_Log.log";
50 }
51
52 //将异常信息输出到文件
53 StreamWriter fs = new StreamWriter(LogAddress, true);
54 fs.WriteLine("当前信息:" + DateTime.Now.ToString());
55 fs.WriteLine("异常信息:" + ex.Message);
56 fs.WriteLine("异常信息:" + ex.Source);
57 fs.WriteLine("调用堆栈:\n" + ex.StackTrace.Trim());
58 fs.WriteLine("触发方法:" + ex.TargetSite);
59 fs.WriteLine();
60 fs.Close();
61 }
62 }
63 }