using MediaBrowser.Model.Logging; using NLog; using NLog.Config; using NLog.Targets; using System; using System.IO; using System.Threading.Tasks; namespace MediaBrowser.Logging.Nlog { /// /// Class NlogManager /// public class NlogManager : ILogManager { /// /// Occurs when [logger loaded]. /// public event EventHandler LoggerLoaded; /// /// Gets or sets the log directory. /// /// The log directory. private string LogDirectory { get; set; } /// /// Gets or sets the log file prefix. /// /// The log file prefix. private string LogFilePrefix { get; set; } /// /// Gets the log file path. /// /// The log file path. public string LogFilePath { get; private set; } /// /// Initializes a new instance of the class. /// /// The log directory. /// The log file name prefix. public NlogManager(string logDirectory, string logFileNamePrefix) { LogDirectory = logDirectory; LogFilePrefix = logFileNamePrefix; } /// /// Adds the file target. /// /// The path. /// The level. private void AddFileTarget(string path, LogSeverity level) { var logFile = new FileTarget(); logFile.FileName = path; logFile.Layout = "${longdate}, ${level}, ${logger}, ${message}"; AddLogTarget(logFile, "ApplicationLogFile", level); } /// /// Adds the log target. /// /// The target. /// The name. /// The level. private void AddLogTarget(Target target, string name, LogSeverity level) { var config = LogManager.Configuration; config.RemoveTarget(name); target.Name = name; config.AddTarget(name, target); var rule = new LoggingRule("*", GetLogLevel(level), target); config.LoggingRules.Add(rule); LogManager.Configuration = config; } /// /// Gets the logger. /// /// The name. /// ILogger. public ILogger GetLogger(string name) { return new NLogger(name); } /// /// Gets the log level. /// /// The severity. /// LogLevel. /// Unrecognized LogSeverity private LogLevel GetLogLevel(LogSeverity severity) { switch (severity) { case LogSeverity.Debug: return LogLevel.Debug; case LogSeverity.Error: return LogLevel.Error; case LogSeverity.Fatal: return LogLevel.Fatal; case LogSeverity.Info: return LogLevel.Info; case LogSeverity.Warn: return LogLevel.Warn; default: throw new ArgumentException("Unrecognized LogSeverity"); } } /// /// Reloads the logger. /// /// The level. public void ReloadLogger(LogSeverity level) { LogFilePath = Path.Combine(LogDirectory, LogFilePrefix + "-" + DateTime.Now.Ticks + ".log"); AddFileTarget(LogFilePath, level); if (LoggerLoaded != null) { Task.Run(() => { try { LoggerLoaded(this, EventArgs.Empty); } catch (Exception ex) { GetLogger("Logger").ErrorException("Error in LoggerLoaded event", ex); } }); } } } }