Last active
September 17, 2015 12:00
-
-
Save smarenich/1859b006b685a4f969c8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class Logger | |
{ | |
private const uint HRFileLocked = 0x80070020; | |
private const uint HRPortionOfFileLocked = 0x80070021; | |
[ThreadStatic] | |
private static bool IsRecursive; | |
public static void Initialise() | |
{ | |
//Subscribe for domain exception diring initialization. | |
AppDomain.CurrentDomain.FirstChanceException += OnCurrentDomainOnFirstChanceException; | |
} | |
private static void OnCurrentDomainOnFirstChanceException(object o, FirstChanceExceptionEventArgs args) | |
{ | |
if (exception is IOException) | |
{ | |
return; // can`t write something to file, so do nothing to prevent stack overflow | |
} | |
if (IsRecursive) | |
return; | |
try | |
{ | |
IsRecursive = true; | |
Logger.LogException(exception); | |
} | |
catch | |
{ | |
// prevent stack overflow | |
} | |
finally | |
{ | |
IsRecursive = false; | |
} | |
} | |
private static void LogException(Exception exception) | |
{ | |
String path = Path.Combine(AppDomain.CurrentDomain.GetData("DataDirectory").ToString(), "MyLog.log"); | |
var trace = new StackTrace(2); | |
//Check your exception here | |
if (IsExcluded(exception, trace)) | |
return; | |
Stream stream; | |
while (!TryOpen(path, out stream)) | |
{ | |
Thread.Sleep(100); // wait for file to unlock | |
} | |
using (stream) | |
{ | |
//Write your log here | |
StreamWriter tw = new StreamWriter(stream); | |
tw.WriteLine("\n================================================================================"); | |
tw.Write(DateTime.Now.ToString("MMM/dd HH:mm:ss.ffff ")); | |
tw.WriteLine(); | |
tw.WriteLine("Message: " + exception.Message); | |
tw.WriteLine(); | |
tw.Close(); | |
} | |
} | |
private static bool IsExcluded(Exception exception, StackTrace trace) | |
{ | |
return !exception.Message.Contains("Session has expired"); | |
} | |
private static bool FileIsLocked(IOException ioException) | |
{ | |
var errorCode = (uint)Marshal.GetHRForException(ioException); | |
return errorCode == HRFileLocked || errorCode == HRPortionOfFileLocked; | |
} | |
private static 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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment