//
// Copyright 2014 Perforce Software Inc.
//
using log4net;
using log4net.Appender;
using log4net.Config;
using System;
using System.Collections.Generic;
namespace Perforce {
public enum LogLevel {
Debug = 0,
Error = 1,
Fatal = 2,
Info = 3,
Warning = 4
}
///
/// Write out messages using the logging provider.
///
public static class Log {
#region Members
private static readonly ILog _logger = LogManager.GetLogger(typeof(Log));
private static Dictionary> _actions;
#endregion
///
/// Static instance of the log manager.
///
static Log() {
XmlConfigurator.Configure();
_actions = new Dictionary>();
_actions.Add(LogLevel.Debug, WriteDebug);
_actions.Add(LogLevel.Error, WriteError);
_actions.Add(LogLevel.Fatal, WriteFatal);
_actions.Add(LogLevel.Info, WriteInfo);
_actions.Add(LogLevel.Warning, WriteWarning);
}
///
/// Get the log.
///
/// The instance of the log, if configured.
/// Null otherwise.
public static NotifyAppender Appender {
get {
foreach (ILog log in LogManager.GetCurrentLoggers()) {
foreach (IAppender appender in log.Logger.Repository.GetAppenders()) {
if (appender is NotifyAppender) {
return appender as NotifyAppender;
}
}
}
return null;
}
}
///
/// Write the message to the appropriate log based on the relevant log level.
///
/// The log level to be used.
/// The message to be written.
/// Thrown if the message is empty.
public static void Write(LogLevel level, string message) {
if (!string.IsNullOrEmpty(message)) {
if (level > LogLevel.Warning || level < LogLevel.Debug)
throw new ArgumentOutOfRangeException("level");
// Now call the appropriate log level message.
_actions[level](message);
}
}
public static void Debug(string message) {
WriteDebug(message);
}
public static void Info(string message) {
WriteInfo(message);
}
public static void Warning(string message) {
WriteWarning(message);
}
public static void Error(string message) {
WriteError(message);
}
public static void Fatal(string message) {
WriteFatal(message);
}
#region Action methods
private static void WriteDebug(string message) {
if (_logger.IsDebugEnabled)
_logger.Debug(message);
}
private static void WriteError(string message) {
if (_logger.IsErrorEnabled)
_logger.Error(message);
}
private static void WriteFatal(string message) {
if (_logger.IsFatalEnabled)
_logger.Fatal(message);
}
private static void WriteInfo(string message) {
if (_logger.IsInfoEnabled)
_logger.Info(message);
}
private static void WriteWarning(string message) {
if (_logger.IsWarnEnabled)
_logger.Warn(message);
}
#endregion
}
}