-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathexceptionlogger.cs
110 lines (97 loc) · 3.41 KB
/
exceptionlogger.cs
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
using System;
using System.Data.Common;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Threading;
namespace ESPEDfGK
{
// // https://asiablog.acumatica.com/2015/09/log-specific-exceptions-with-first.html
internal class ExceptionLogger
{
private string filename;
private const uint HRFileLocked = 0x80070020;
private const uint HRPortionOfFileLocked = 0x80070021;
//******************************************************************************************************************
public ExceptionLogger(string filename)
{
this.filename = filename;
AppDomain.CurrentDomain.FirstChanceException += OnCurrentDomainOnFirstChanceException;
}
[ThreadStatic]
private bool IsRecursive;
//******************************************************************************************************************
private void OnCurrentDomainOnFirstChanceException(object o, FirstChanceExceptionEventArgs args)
{
if (IsRecursive)
{
return;
}
if (args.Exception is IOException)
{
return;
}
try
{
IsRecursive = true;
LogException(args.Exception);
}
catch
{
// prevent stack overflow
}
finally
{
IsRecursive = false;
}
}
//******************************************************************************************************************
private void LogException(Exception exception)
{
StackTrace trace = new StackTrace(2);
Stream stream;
while (!TryOpen(filename, out stream))
{
Thread.Sleep(100); // wait for file to unlock
}
using (stream)
{
//Write your log here
StreamWriter sw = new StreamWriter(stream);
sw.Write("\n======== ");
sw.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff "));
sw.Write(" ========");
sw.WriteLine();
sw.WriteLine("Message: " + exception.Message);
sw.WriteLine();
sw.WriteLine(trace.ToString());
sw.WriteLine();
sw.Close();
}
}
//******************************************************************************************************************
private bool FileIsLocked(IOException ioException)
{
var errorCode = (uint)Marshal.GetHRForException(ioException);
return errorCode == HRFileLocked || errorCode == HRPortionOfFileLocked;
}
//******************************************************************************************************************
private bool TryOpen(string path, out Stream stream)
{
try
{
stream = File.Open(path, FileMode.Append);
return true;
}
catch (IOException e)
{
if (!FileIsLocked(e))
throw;
stream = null;
return false;
}
}
}
}