using NLog; using System; namespace Sony.Filtr.Tasks.Helpers { public class LoggerAdapter { private readonly Logger Logger; private readonly Action> TraceLoggingFunc; private readonly Action> InformationLoggingFunc; private readonly Action> WarnLoggingFunc; private readonly Action> DebugLoggingFunc; private readonly Action> ErrorLoggingFunc; private readonly Action> FatalLoggingFunc; private readonly Action> ErrorWithExceptionLoggingFunc; public static LoggerAdapter GetLogger(string name) { return new LoggerAdapter(LogManager.GetLogger(name)); } public LoggerAdapter(Logger logger) { this.Logger = logger; this.InformationLoggingFunc = this.CreateFuncForLevel(LogLevel.Info); this.WarnLoggingFunc = this.CreateFuncForLevel(LogLevel.Warn); this.DebugLoggingFunc = this.CreateFuncForLevel(LogLevel.Debug); this.ErrorLoggingFunc = this.CreateFuncForLevel(LogLevel.Error); this.FatalLoggingFunc = this.CreateFuncForLevel(LogLevel.Fatal); this.TraceLoggingFunc = this.CreateFuncForLevel(LogLevel.Trace); this.ErrorWithExceptionLoggingFunc = this.GetErrorLoggingWithExceptionFunc(); } public void Trace(Func getString) { this.TraceLoggingFunc(getString); } public void Information(Func getString) { this.InformationLoggingFunc(getString); } public void Warn(Func getString) { this.WarnLoggingFunc(getString); } public void Debug(Func getString) { this.DebugLoggingFunc(getString); } public void Fatal(Func getString) { this.FatalLoggingFunc(getString); } public void Error(Func getString) { this.ErrorLoggingFunc(getString); } public void Error(Exception ex, Func getString) { this.ErrorWithExceptionLoggingFunc(ex, getString); } private Action> CreateFuncForLevel(LogLevel level) { return this.Logger.IsEnabled(level) ? this.GetLoggerFunctionForLevel(level) : getString => { }; } private Action> GetLoggerFunctionForLevel(LogLevel level) { if(level == LogLevel.Info) { return getString => this.Logger.Info(getString()); } if (level == LogLevel.Debug) { return getString => this.Logger.Debug(getString()); } if (level == LogLevel.Warn) { return getString => this.Logger.Warn(getString()); } if (level == LogLevel.Error) { return getString => this.Logger.Error(getString()); } if (level == LogLevel.Fatal) { return getString => this.Logger.Fatal(getString()); } if (level == LogLevel.Trace) { return getString => this.Logger.Trace(getString()); } return getString => { }; } private Action> GetErrorLoggingWithExceptionFunc() { if (this.Logger.IsErrorEnabled) { return (ex, getString) => this.Logger.Error(ex, getString()); } return (ex, getString) => { }; } } }