Last active
August 29, 2015 13:59
-
-
Save MichaelPaulukonis/10656010 to your computer and use it in GitHub Desktop.
Example of a static class for log4net; adapted from code found at http://stackoverflow.com/a/2853111/41153. Also using optional error-number (GUID) return to hide runtime errors from users.
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
using System.Runtime.CompilerServices; | |
using System.Diagnostics; | |
using log4net; | |
// TODO: you must move the below configuration call. | |
// It must be executed prior to any calls to Logger | |
// Application_Start or summat | |
log4net.Config.XmlConfigurator.Configure(); | |
public class CustomError | |
{ | |
public string ErrorId; | |
public string Message; | |
} | |
public static class Logger | |
{ | |
private static class UnknownObject { } | |
// found @ http://stackoverflow.com/a/2853111/41153 | |
[MethodImpl(MethodImplOptions.NoInlining)] | |
public static ILog GetLogger() | |
{ | |
Type t; | |
try { t = new StackFrame(1, false).GetMethod().DeclaringType; } | |
catch { t = typeof(UnknownObject); } | |
return LogManager.GetLogger(t); | |
} | |
private static string GetErrorNumber() | |
{ | |
return Guid.NewGuid().ToString(); | |
} | |
public static void Info(object msg) | |
{ | |
GetLogger().Info(msg); | |
} | |
public static void Error(object msg) | |
{ | |
GetLogger().Error(msg); | |
} | |
public static CustomError Error(Exception ex) | |
{ | |
var ern = GetErrorNumber(); | |
GetLogger().Error(string.Format("{0}: {1}", ern, ex)); | |
string msg; | |
// bool that reads from [app|web].config | |
if (Settings.VerboseErrors) | |
{ | |
var sb = new StringBuilder(); | |
sb.AppendLine(ex.ToString()); | |
sb.AppendLine(string.Empty); | |
sb.AppendLine( | |
"(This message is displayed because VerboseErrors is set to true. Please set to false to only display ErrorIDs)"); | |
msg = sb.ToString().Replace(Environment.NewLine, "<br />"); | |
} | |
else | |
{ | |
msg = string.Format("An error has occured: Please contact support with case-number {1}", ern); | |
} | |
return new CustomError { ErrorId = ern, Message = msg }; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment