jellyfin/Emby.Common.Implementations/Logging/NlogManager.cs

544 lines
16 KiB
C#
Raw Normal View History

2016-10-29 20:13:23 +00:00
using System;
using System.IO;
using System.Linq;
2016-12-17 20:52:05 +00:00
using System.Xml;
2013-02-26 17:21:18 +00:00
using NLog;
using NLog.Config;
2016-12-17 20:52:05 +00:00
using NLog.Filters;
using NLog.Targets;
2014-11-27 03:10:44 +00:00
using NLog.Targets.Wrappers;
2016-10-29 20:13:23 +00:00
using MediaBrowser.Model.Logging;
2016-10-29 20:13:23 +00:00
namespace Emby.Common.Implementations.Logging
{
/// <summary>
/// Class NlogManager
/// </summary>
2013-02-26 17:21:18 +00:00
public class NlogManager : ILogManager
{
2016-12-17 20:52:05 +00:00
#region Private Fields
private LogSeverity _severity = LogSeverity.Debug;
2013-02-26 17:21:18 +00:00
/// <summary>
/// Gets or sets the log directory.
/// </summary>
/// <value>The log directory.</value>
2016-12-17 20:52:05 +00:00
private readonly string LogDirectory;
2013-02-26 17:21:18 +00:00
/// <summary>
/// Gets or sets the log file prefix.
/// </summary>
/// <value>The log file prefix.</value>
2016-12-17 20:52:05 +00:00
private readonly string LogFilePrefix;
#endregion
#region Event Declarations
/// <summary>
/// Occurs when [logger loaded].
/// </summary>
public event EventHandler LoggerLoaded;
#endregion
#region Public Properties
2013-02-26 17:21:18 +00:00
/// <summary>
/// Gets the log file path.
/// </summary>
/// <value>The log file path.</value>
public string LogFilePath { get; private set; }
2014-12-17 22:39:17 +00:00
/// <summary>
/// Gets or sets the exception message prefix.
/// </summary>
/// <value>The exception message prefix.</value>
public string ExceptionMessagePrefix { get; set; }
2016-12-17 20:52:05 +00:00
public string NLogConfigurationFilePath { get; set; }
2014-11-27 03:10:44 +00:00
2013-09-21 01:04:14 +00:00
public LogSeverity LogSeverity
{
2016-12-17 20:52:05 +00:00
2013-09-21 01:04:14 +00:00
get
{
return _severity;
}
2016-12-17 20:52:05 +00:00
2013-09-21 01:04:14 +00:00
set
{
2016-12-17 20:52:05 +00:00
DebugFileWriter(
LogDirectory, String.Format(
"SET LogSeverity, _severity = [{0}], value = [{1}]",
_severity.ToString(),
value.ToString()
));
2013-09-21 01:04:14 +00:00
var changed = _severity != value;
_severity = value;
if (changed)
{
UpdateLogLevel(value);
}
2016-12-17 20:52:05 +00:00
}
}
#endregion
#region Constructor(s)
/// <summary>
/// Initializes a new instance of the <see cref="NlogManager" /> class.
/// </summary>
/// <param name="logDirectory">The log directory.</param>
/// <param name="logFileNamePrefix">The log file name prefix.</param>
public NlogManager(string logDirectory, string logFileNamePrefix)
{
DebugFileWriter(
logDirectory, String.Format(
"NlogManager constructor called, logDirectory is [{0}], logFileNamePrefix is [{1}], _severity is [{2}].",
logDirectory,
logFileNamePrefix,
_severity.ToString()
));
LogDirectory = logDirectory;
LogFilePrefix = logFileNamePrefix;
LogManager.Configuration = new LoggingConfiguration();
}
/// <summary>
/// Initializes a new instance of the <see cref="NlogManager" /> class.
/// </summary>
/// <param name="logDirectory">The log directory.</param>
/// <param name="logFileNamePrefix">The log file name prefix.</param>
public NlogManager(string logDirectory, string logFileNamePrefix, LogSeverity initialSeverity) : this(logDirectory, logFileNamePrefix)
{
_severity = initialSeverity;
DebugFileWriter(
logDirectory, String.Format(
"NlogManager constructor called, logDirectory is [{0}], logFileNamePrefix is [{1}], _severity is [{2}].",
logDirectory,
logFileNamePrefix,
_severity.ToString()
));
}
#endregion
#region Private Methods
/// <summary>
/// Adds the file target.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="level">The level.</param>
private void AddFileTarget(string path, LogSeverity level)
{
DebugFileWriter(
LogDirectory, String.Format(
"AddFileTarget called, path = [{0}], level = [{1}].",
path,
level.ToString()
));
RemoveTarget("ApplicationLogFileWrapper");
var wrapper = new AsyncTargetWrapper();
wrapper.Name = "ApplicationLogFileWrapper";
var logFile = new FileTarget
{
FileName = path,
Layout = "${longdate} ${level} ${logger}: ${message}"
};
logFile.Name = "ApplicationLogFile";
wrapper.WrappedTarget = logFile;
AddLogTarget(wrapper, level);
}
/// <summary>
/// Gets the log level.
/// </summary>
/// <param name="severity">The severity.</param>
/// <returns>LogLevel.</returns>
/// <exception cref="System.ArgumentException">Unrecognized LogSeverity</exception>
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");
2013-09-21 01:04:14 +00:00
}
}
private void UpdateLogLevel(LogSeverity newLevel)
{
2016-12-17 20:52:05 +00:00
DebugFileWriter(
LogDirectory, String.Format(
"UpdateLogLevel called, newLevel = [{0}].",
newLevel.ToString()
));
2013-09-21 01:04:14 +00:00
var level = GetLogLevel(newLevel);
var rules = LogManager.Configuration.LoggingRules;
foreach (var rule in rules)
{
if (!rule.IsLoggingEnabledForLevel(level))
{
rule.EnableLoggingForLevel(level);
}
2015-07-08 16:10:34 +00:00
foreach (var lev in rule.Levels.ToArray())
{
if (lev < level)
{
rule.DisableLoggingForLevel(lev);
}
}
2013-09-21 01:04:14 +00:00
}
}
2016-12-17 20:52:05 +00:00
private void AddCustomFilters(string defaultLoggerNamePattern, LoggingRule defaultRule)
{
2016-12-17 20:52:05 +00:00
DebugFileWriter(
LogDirectory, String.Format(
"AddCustomFilters called, defaultLoggerNamePattern = [{0}], defaultRule.LoggerNamePattern = [{1}].",
defaultLoggerNamePattern,
defaultRule.LoggerNamePattern
));
try
{
var customConfig = new NLog.Config.XmlLoggingConfiguration(NLogConfigurationFilePath);
2014-11-27 03:10:44 +00:00
2016-12-17 20:52:05 +00:00
DebugFileWriter(
LogDirectory, String.Format(
"Custom Configuration Loaded, Rule Count = [{0}].",
customConfig.LoggingRules.Count.ToString()
));
2014-11-27 03:10:44 +00:00
2016-12-17 20:52:05 +00:00
foreach (var customRule in customConfig.LoggingRules)
{
DebugFileWriter(
LogDirectory, String.Format(
"Read Custom Rule, LoggerNamePattern = [{0}], Targets = [{1}].",
customRule.LoggerNamePattern,
string.Join(",", customRule.Targets.Select(x => x.Name).ToList())
));
if (customRule.LoggerNamePattern.Equals(defaultLoggerNamePattern))
{
if (customRule.Targets.Any((arg) => arg.Name.Equals(defaultRule.Targets.First().Name)))
{
DebugFileWriter(
LogDirectory, String.Format(
"Custom rule filters can be applied to this target, Filter Count = [{0}].",
customRule.Filters.Count.ToString()
));
foreach (ConditionBasedFilter customFilter in customRule.Filters)
{
DebugFileWriter(
LogDirectory, String.Format(
"Read Custom Filter, Filter = [{0}], Action = [{1}], Type = [{2}].",
customFilter.Condition.ToString(),
customFilter.Action.ToString(),
customFilter.GetType().ToString()
));
defaultRule.Filters.Add(customFilter);
}
}
else
{
DebugFileWriter(
LogDirectory, String.Format(
"Ignoring custom rule as [Target] does not match."
));
}
}
else
{
DebugFileWriter(
LogDirectory, String.Format(
"Ignoring custom rule as [LoggerNamePattern] does not match."
));
}
}
}
catch (Exception ex)
{
2016-12-17 20:52:05 +00:00
// Intentionally do nothing, prevent issues affecting normal execution.
DebugFileWriter(
LogDirectory, String.Format(
"Exception in AddCustomFilters, ex.Message = [{0}].",
ex.Message
)
);
2016-12-17 20:52:05 +00:00
}
}
2013-03-04 16:31:33 +00:00
2016-12-17 20:52:05 +00:00
#endregion
#region Public Methods
/// <summary>
/// Gets the logger.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>ILogger.</returns>
public MediaBrowser.Model.Logging.ILogger GetLogger(string name)
{
DebugFileWriter(
LogDirectory, String.Format(
"GetLogger called, name = [{0}].",
name
));
return new NLogger(name, this);
2014-11-27 03:10:44 +00:00
}
/// <summary>
/// Adds the log target.
/// </summary>
/// <param name="target">The target.</param>
2013-02-26 17:21:18 +00:00
/// <param name="level">The level.</param>
2013-03-05 18:11:25 +00:00
public void AddLogTarget(Target target, LogSeverity level)
{
2016-12-17 20:52:05 +00:00
DebugFileWriter(
LogDirectory, String.Format(
"AddLogTarget called, target.Name = [{0}], level = [{1}].",
target.Name,
level.ToString()
));
string loggerNamePattern = "*";
var config = LogManager.Configuration;
2016-12-17 20:52:05 +00:00
var rule = new LoggingRule(loggerNamePattern, GetLogLevel(level), target);
2013-03-04 16:31:33 +00:00
config.AddTarget(target.Name, target);
2016-12-17 20:52:05 +00:00
AddCustomFilters(loggerNamePattern, rule);
config.LoggingRules.Add(rule);
LogManager.Configuration = config;
2016-12-17 20:52:05 +00:00
}
2013-02-26 17:21:18 +00:00
2013-03-04 16:31:33 +00:00
/// <summary>
/// Removes the target.
/// </summary>
/// <param name="name">The name.</param>
public void RemoveTarget(string name)
{
2016-12-17 20:52:05 +00:00
DebugFileWriter(
LogDirectory, String.Format(
"RemoveTarget called, name = [{0}].",
name
));
2013-03-04 16:31:33 +00:00
var config = LogManager.Configuration;
var target = config.FindTargetByName(name);
if (target != null)
{
foreach (var rule in config.LoggingRules.ToList())
{
var contains = rule.Targets.Contains(target);
rule.Targets.Remove(target);
if (contains)
{
config.LoggingRules.Remove(rule);
}
}
config.RemoveTarget(name);
LogManager.Configuration = config;
}
}
2016-12-17 20:52:05 +00:00
public void AddConsoleOutput()
2013-02-26 17:21:18 +00:00
{
2016-12-17 20:52:05 +00:00
DebugFileWriter(
LogDirectory, String.Format(
"AddConsoleOutput called."
));
RemoveTarget("ConsoleTargetWrapper");
var wrapper = new AsyncTargetWrapper();
wrapper.Name = "ConsoleTargetWrapper";
var target = new ConsoleTarget()
{
Layout = "${level}, ${logger}, ${message}",
Error = false
};
target.Name = "ConsoleTarget";
wrapper.WrappedTarget = target;
AddLogTarget(wrapper, LogSeverity);
}
public void RemoveConsoleOutput()
{
DebugFileWriter(
LogDirectory, String.Format(
"RemoveConsoleOutput called."
));
RemoveTarget("ConsoleTargetWrapper");
2013-02-26 17:21:18 +00:00
}
/// <summary>
2016-12-17 20:52:05 +00:00
/// Reloads the logger, maintaining the current log level.
2013-02-26 17:21:18 +00:00
/// </summary>
2016-12-17 20:52:05 +00:00
public void ReloadLogger()
2013-02-26 17:21:18 +00:00
{
2016-12-17 20:52:05 +00:00
ReloadLogger(LogSeverity);
2013-02-26 17:21:18 +00:00
}
/// <summary>
2016-12-17 20:52:05 +00:00
/// Reloads the logger, using the specified logging level.
2013-02-26 17:21:18 +00:00
/// </summary>
/// <param name="level">The level.</param>
public void ReloadLogger(LogSeverity level)
{
2016-12-17 20:52:05 +00:00
DebugFileWriter(
LogDirectory, String.Format(
"ReloadLogger called, level = [{0}], LogFilePath (existing) = [{1}].",
level.ToString(),
LogFilePath
));
2016-10-29 20:13:23 +00:00
LogFilePath = Path.Combine(LogDirectory, LogFilePrefix + "-" + decimal.Floor(DateTime.Now.Ticks / 10000000) + ".txt");
2013-02-26 17:21:18 +00:00
2016-12-17 20:52:05 +00:00
Directory.CreateDirectory(Path.GetDirectoryName(LogFilePath));
2014-01-09 04:44:51 +00:00
2013-02-26 17:21:18 +00:00
AddFileTarget(LogFilePath, level);
2013-09-21 01:04:14 +00:00
LogSeverity = level;
2013-02-26 17:21:18 +00:00
if (LoggerLoaded != null)
{
try
2013-02-26 17:21:18 +00:00
{
2016-12-17 20:52:05 +00:00
DebugFileWriter(
LogDirectory, String.Format(
"ReloadLogger called, raised event LoggerLoaded."
));
LoggerLoaded(this, EventArgs.Empty);
2016-12-17 20:52:05 +00:00
}
catch (Exception ex)
{
GetLogger("Logger").ErrorException("Error in LoggerLoaded event", ex);
}
2013-02-26 17:21:18 +00:00
}
}
/// <summary>
/// Flushes this instance.
/// </summary>
public void Flush()
{
2014-01-09 04:44:51 +00:00
2016-12-17 20:52:05 +00:00
DebugFileWriter(
LogDirectory, String.Format(
"Flush called."
));
2014-01-09 04:44:51 +00:00
2016-12-17 20:52:05 +00:00
LogManager.Flush();
2014-11-27 03:10:44 +00:00
2016-12-17 20:52:05 +00:00
}
2014-11-27 03:10:44 +00:00
2016-12-17 20:52:05 +00:00
#endregion
2014-01-09 04:44:51 +00:00
2016-12-17 20:52:05 +00:00
#region Conditional Debug Methods
2014-01-09 04:44:51 +00:00
2016-12-17 20:52:05 +00:00
/// <summary>
/// DEBUG: Standalone method to write out debug to assist with logger development/troubleshooting.
/// <list type="bullet">
/// <item><description>The output file will be written to the server's log directory.</description></item>
/// <item><description>Calls to the method are safe and will never throw any exceptions.</description></item>
/// <item><description>Method calls will be omitted unless the library is compiled with DEBUG defined.</description></item>
/// </list>
/// </summary>
private static void DebugFileWriter(string logDirectory, string message)
{
#if DEBUG
try
{
2014-11-27 03:10:44 +00:00
2016-12-17 20:52:05 +00:00
System.IO.File.AppendAllText(
Path.Combine(logDirectory, "NlogManager.txt"),
String.Format(
"{0} : {1}{2}",
System.DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"),
message,
System.Environment.NewLine
)
);
2014-01-09 04:44:51 +00:00
2016-12-17 20:52:05 +00:00
}
catch (Exception ex)
{
// Intentionally do nothing, prevent issues affecting normal execution.
}
#endif
2014-01-09 04:44:51 +00:00
}
2016-12-17 20:52:05 +00:00
#endregion
}
2016-12-17 20:52:05 +00:00
}