110 lines
No EOL
2.9 KiB
C#
110 lines
No EOL
2.9 KiB
C#
using System;
|
|
using JD.Kernel.StaticHelpers;
|
|
|
|
namespace JD.LogService
|
|
{
|
|
/// <summary>
|
|
/// Basic logging facilities.
|
|
/// </summary>
|
|
public static class Logger
|
|
{
|
|
private static ILogger m_emptyLogger;
|
|
|
|
/// <summary>
|
|
/// Gets a logger that does nothing except not being null :)
|
|
/// </summary>
|
|
public static ILogger Empty
|
|
{
|
|
get { return m_emptyLogger = m_emptyLogger ?? new EmptyLogger(); }
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates and return a delegated logger.
|
|
/// </summary>
|
|
/// <param name="logAction">Will be used as the logging action of the logger.</param>
|
|
public static ILogger FromAction(Action<LogEvent> logAction)
|
|
{
|
|
return new DelegatedLogger(logAction);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns a wrapper logger that locks each log call individually.
|
|
/// </summary>
|
|
public static ILogger Locked(ILogger logger)
|
|
{
|
|
return new LockedLogger(logger);
|
|
}
|
|
|
|
public static ILogger CreateConsoleLogger()
|
|
{
|
|
return new ConsoleLogger();
|
|
}
|
|
|
|
#region Nested
|
|
|
|
private class EmptyLogger : ILogger
|
|
{
|
|
public void Log(LogEvent @event)
|
|
{
|
|
// Do nothing!
|
|
}
|
|
}
|
|
|
|
private class DelegatedLogger : ILogger
|
|
{
|
|
private readonly Action<LogEvent> m_logAction;
|
|
|
|
public DelegatedLogger(Action<LogEvent> logAction)
|
|
{
|
|
Throw.IfNull(logAction, "logAction");
|
|
m_logAction = logAction;
|
|
}
|
|
|
|
public void Log(LogEvent @event)
|
|
{
|
|
m_logAction(@event);
|
|
}
|
|
}
|
|
|
|
private class LockedLogger : ILogger
|
|
{
|
|
private readonly object m_lock = new object();
|
|
private readonly ILogger m_logger;
|
|
|
|
public LockedLogger(ILogger logger)
|
|
{
|
|
Throw.IfNull(logger, "logger");
|
|
m_logger = logger;
|
|
}
|
|
|
|
public void Log(LogEvent @event)
|
|
{
|
|
lock (m_lock)
|
|
{
|
|
m_logger.Log(@event);
|
|
}
|
|
}
|
|
}
|
|
|
|
private class ConsoleLogger : ILogger
|
|
{
|
|
public void Log(LogEvent @event)
|
|
{
|
|
if (@event.Category == LogCategory.Error)
|
|
{
|
|
Console.Error.WriteLine(@event.ToCanonicalString());
|
|
}
|
|
else if (@event.Category == LogCategory.Warning)
|
|
{
|
|
Console.Out.WriteLine(@event.ToCanonicalString());
|
|
}
|
|
else
|
|
{
|
|
Console.Out.WriteLine(@event.Message);
|
|
}
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
} |