C# 打印异常

时间:2022-09-04 17:07:38

1. [代码]函数:将异常打印到LOG文件     跳至 [1] [2] [4] [全屏预览]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/// <summary>
/// 将异常打印到LOG文件
/// </summary>
/// <param name="ex">异常</param>
/// <param name="LogAddress">日志文件地址</param>
public static void WriteLog(Exception ex, string LogAddress = "")
{
    //如果日志文件为空,则默认在Debug目录下新建 YYYY-mm-dd_Log.log文件
    if (LogAddress == "")
    {
        LogAddress = Environment.CurrentDirectory + '\\' +
            DateTime.Now.Year + '-' +
            DateTime.Now.Month + '-' +
            DateTime.Now.Day + "_Log.log";
    }
 
    //把异常信息输出到文件
    StreamWriter sw = new StreamWriter(LogAddress, true);
    sw.WriteLine("当前时间:" + DateTime.Now.ToString());
    sw.WriteLine("异常信息:" + ex.Message);
    sw.WriteLine("异常对象:" + ex.Source);
    sw.WriteLine("调用堆栈:\n" + ex.StackTrace.Trim());
    sw.WriteLine("触发方法:" + ex.TargetSite);
    sw.WriteLine();
    sw.Close();
}

2. [代码]调用方法

1
2
3
4
5
6
7
8
try
{
    throw new Exception("测试异常");
}
catch (Exception ex)
{
    WriteLog(ex);
}

3. [图片] 测试异常.png

C# 打印异常

4. [代码]多线程调用函数,需要在函数体内部用到lock关键字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
static void Main(string[] args)
{
    Thread th1 = new Thread(new ParameterizedThreadStart(MakeException));
    Thread th2 = new Thread(new ParameterizedThreadStart(MakeException));
 
    th1.Start("Thread1");
    th2.Start("Thread2");
}
 
/// <summary>
/// 制造异常
/// </summary>
/// <param name="Tag">传入标签</param>
public static void MakeException(object Tag)
{
    while (true)
    {
        try
        {
            throw new Exception("测试异常");
        }
        catch (Exception ex)
        {
            WriteLog(ex, Tag.ToString());
        }
    }
}
 
public static object locker = new object();
 
/// <summary>
/// 将异常打印到LOG文件
/// </summary>
/// <param name="ex">异常</param>
/// <param name="LogAddress">日志文件地址</param>
/// <param name="Tag">传入标签(这里用于标识函数由哪个线程调用)</param>
public static void WriteLog(Exception ex, string Tag = "", string LogAddress = "")
{
    lock (locker)
    {
        //如果日志文件为空,则默认在Debug目录下新建 YYYY-mm-dd_Log.log文件
        if (LogAddress == "")
        {
            LogAddress = Environment.CurrentDirectory + '\\' +
                DateTime.Now.Year + '-' +
                DateTime.Now.Month + '-' +
                DateTime.Now.Day + "_Log.log";
        }
 
        //把异常信息输出到文件
        StreamWriter sw = new StreamWriter(LogAddress, true);
        sw.WriteLine(String.Concat('[', DateTime.Now.ToString(), "] Tag:" + Tag));
        sw.WriteLine("异常信息:" + ex.Message);
        sw.WriteLine("异常对象:" + ex.Source);
        sw.WriteLine("调用堆栈:\n" + ex.StackTrace.Trim());
        sw.WriteLine("触发方法:" + ex.TargetSite);
        sw.WriteLine();
        sw.Close();
    }
}
1
2
3
4
if (!Directory.Exists(sPath))
{
     Directory.CreateDirectory(sPath);
}