Skip to content

Instantly share code, notes, and snippets.

@smarenich

smarenich/Logger.cs

Last active Sep 17, 2015
Embed
What would you like to do?
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
You can’t perform that action at this time.