Skip to content

Instantly share code, notes, and snippets.

@feanz
Forked from ferventcoder/0HowAwesomeIsThis.cs
Last active December 20, 2015 19:39
Show Gist options
  • Save feanz/6184814 to your computer and use it in GitHub Desktop.
Save feanz/6184814 to your computer and use it in GitHub Desktop.
public class SomeClass {
public void SomeMethod() {
this.Log().Info("Here is a log message with params which can be in Razor Views as well: '{0}'".FormatWith(typeof(SomeClass).Name));
}
}
Log.InitializeWith<Log4NetLog>();
public interface ILogger
{
void Debug(string message);
void Error(string message);
void Error(string message, Exception exception);
void Fatal(string message);
void Fatal(string message, Exception exception);
void Info(string message);
void InitializeFor(string loggerName);
void Warning(string message);
}
/// <summary>
/// Ensures a default constructor for the logger type
/// </summary>
/// <typeparam name="T"></typeparam>
public interface ILogger<T> where T : new()
{
}
/// <summary>
/// Logger type initialization
/// </summary>
public static class Log
{
private static Type _logType = typeof(NullDebugLogger);
private static ILogger _logger;
/// <summary>
/// Sets up logging to be with a certain type
/// </summary>
/// <typeparam name="T">The type of ILog for the application to use</typeparam>
public static void InitializeWith<T>() where T : ILogger, new()
{
_logType = typeof(T);
}
/// <summary>
/// Sets up logging to be with a certain instance. The other method is preferred.
/// </summary>
/// <param name="loggerType">Type of the logger.</param>
/// <remarks>This is mostly geared towards testing</remarks>
public static void InitializeWith(ILogger loggerType)
{
_logType = loggerType.GetType();
_logger = loggerType;
}
/// <summary>
/// Initializes a new instance of a logger for an object.
/// This should be done only once per object name.
/// </summary>
/// <param name="objectName">Name of the object.</param>
/// <returns>ILog instance for an object if log type has been initialized; otherwise null</returns>
public static ILogger GetLoggerFor(string objectName)
{
var logger = _logger;
if (_logger == null)
{
logger = Activator.CreateInstance(_logType) as ILogger;
if (logger != null)
{
logger.InitializeFor(objectName);
}
}
return logger;
}
}
using System;
using log4net;
using log4net.Config;
[assembly: XmlConfigurator(Watch = true)]
namespace Some.Namespace {
/// <summary>
/// Log4net logger implementing special ILog class
/// </summary>
public class Log4NetLog : ILog, ILog<Log4NetLog>
{
private global::log4net.ILog _logger;
public void InitializeFor(string loggerName)
{
_logger = LogManager.GetLogger(loggerName);
}
public void Debug(string message, params object[] formatting)
{
if (_logger.IsDebugEnabled) _logger.DebugFormat(DecorateMessageWithAuditInformation(message), formatting);
}
public void Debug(Func<string> message)
{
if (_logger.IsDebugEnabled) _logger.Debug(DecorateMessageWithAuditInformation(message.Invoke()));
}
public void Info(string message, params object[] formatting)
{
if (_logger.IsInfoEnabled) _logger.InfoFormat(DecorateMessageWithAuditInformation(message), formatting);
}
public void Info(Func<string> message)
{
if (_logger.IsInfoEnabled) _logger.Info(DecorateMessageWithAuditInformation(message.Invoke()));
}
public void Warn(string message, params object[] formatting)
{
if (_logger.IsWarnEnabled) _logger.WarnFormat(DecorateMessageWithAuditInformation(message), formatting);
}
public void Warn(Func<string> message)
{
if (_logger.IsWarnEnabled) _logger.Warn(DecorateMessageWithAuditInformation(message.Invoke()));
}
public void Error(string message, params object[] formatting)
{
// don't need to check for enabled at this level
_logger.ErrorFormat(DecorateMessageWithAuditInformation(message), formatting);
}
public void Error(Func<string> message)
{
// don't need to check for enabled at this level
_logger.Error(DecorateMessageWithAuditInformation(message.Invoke()));
}
public void Fatal(string message, params object[] formatting)
{
// don't need to check for enabled at this level
_logger.FatalFormat(DecorateMessageWithAuditInformation(message), formatting);
}
public void Fatal(Func<string> message)
{
// don't need to check for enabled at this level
_logger.Fatal(DecorateMessageWithAuditInformation(message.Invoke()));
}
public string DecorateMessageWithAuditInformation(string message)
{
string currentUserName = ApplicationParameters.GetCurrentUserName();
if (!string.IsNullOrWhiteSpace(currentUserName))
{
return "{0} - {1}".FormatWith(message, currentUserName);
}
return message;
}
}
}
/// <summary>
/// Extensions to help make logging awesome
/// </summary>
public static class LoggingExtensions
{
/// <summary>
/// Concurrent dictionary that ensures only one instance of a logger for a type.
/// </summary>
private static readonly Lazy<ConcurrentDictionary<string, ILogger>> _dictionary = new Lazy<ConcurrentDictionary<string, ILogger>>(() => new ConcurrentDictionary<string, ILogger>());
public static ILogger Log<T>(this T type)
{
var objectName = typeof(T).FullName;
return Log(objectName);
}
public static ILogger Log(this string objectName)
{
return _dictionary.Value.GetOrAdd(objectName, Logging.Log.GetLoggerFor);
}
public static void Debug(this ILogger logger, string message, params object[] args)
{
logger.Debug(string.Format(message,args));
}
public static void Info(this ILogger logger, string message, params object[] args)
{
logger.Debug(string.Format(message, args));
}
public static void Warning(this ILogger logger, string message, params object[] args)
{
logger.Debug(string.Format(message, args));
}
public static void Error(this ILogger logger, string message, params object[] args)
{
logger.Debug(string.Format(message, args));
}
public static void Fatal(this ILogger logger, string message, params object[] args)
{
logger.Debug(string.Format(message, args));
}
}
/// <summary>
/// Default logger
/// </summary>
public class NullLogger : ILogger
{
public void Debug(string message)
{
}
public void Error(string message)
{
}
public void Error(string message, Exception exception)
{
}
public void Fatal(string message)
{
}
public void Fatal(string message, Exception exception)
{
}
public void Info(string message)
{
}
public void InitializeFor(string loggerName)
{
}
public void Warning(string message)
{
}
}
public static class StringExtensions
{
/// <summary>
/// Formats string with the formatting passed in. This is a shortcut to string.Format().
/// </summary>
/// <param name="input">The input.</param>
/// <param name="formatting">The formatting.</param>
/// <returns>A formatted string.</returns>
public static string FormatWith(this string input, params object[] formatting)
{
return string.Format(input, formatting);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment