safer log configuration

pull/3113/head
Keivan Beigi 10 years ago
parent b7b4c568be
commit 0a341199a8

@ -1,8 +1,8 @@
using System;
using LogentriesCore;
using LogentriesNLog.fastJSON;
using NLog;
using NLog.Targets;
using NzbDrone.Common.Exceptron.fastJSON;
namespace LogentriesNLog
{

@ -4,7 +4,7 @@
using System;
using System.Collections.Generic;
namespace NzbDrone.Common.Exceptron.fastJSON
namespace LogentriesNLog.fastJSON
{
internal class Getters
{

@ -11,7 +11,7 @@ using System.Reflection;
using System.Reflection.Emit;
using System.Xml.Serialization;
namespace NzbDrone.Common.Exceptron.fastJSON
namespace LogentriesNLog.fastJSON
{
internal class JSON

@ -6,7 +6,7 @@ using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace NzbDrone.Common.Exceptron.fastJSON
namespace LogentriesNLog.fastJSON
{
/// <summary>
/// This class encodes and decodes JSON strings.

@ -9,7 +9,7 @@ using System.Globalization;
using System.IO;
using System.Text;
namespace NzbDrone.Common.Exceptron.fastJSON
namespace LogentriesNLog.fastJSON
{
internal class JSONSerializer
{

@ -3,7 +3,7 @@
using System.Collections.Generic;
namespace NzbDrone.Common.Exceptron.fastJSON
namespace LogentriesNLog.fastJSON
{
internal class SafeDictionary<TKey, TValue>
{

@ -15,17 +15,16 @@ namespace NzbDrone.Api
public class NancyBootstrapper : TinyIoCNancyBootstrapper
{
private readonly TinyIoCContainer _tinyIoCContainer;
private readonly Logger _logger;
private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(NancyBootstrapper));
public NancyBootstrapper(TinyIoCContainer tinyIoCContainer)
{
_tinyIoCContainer = tinyIoCContainer;
_logger = NzbDroneLogger.GetLogger();
}
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
{
_logger.Info("Starting NzbDrone API");
Logger.Info("Starting NzbDrone API");
if (RuntimeInfoBase.IsProduction)
{

@ -36,7 +36,7 @@ namespace NzbDrone.Automation.Test
{
driver = new FirefoxDriver();
_runner = new NzbDroneRunner();
_runner = new NzbDroneRunner(LogManager.GetCurrentClassLogger());
_runner.KillAll();
_runner.Start();

@ -14,7 +14,7 @@ namespace NzbDrone.Common.Disk
{
public abstract class DiskProviderBase : IDiskProvider
{
private static readonly Logger Logger = NzbDroneLogger.GetLogger();
private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(DiskProviderBase));
public abstract long? GetAvailableSpace(string path);
public abstract void InheritFolderPermissions(string filename);

@ -6,7 +6,7 @@ namespace NzbDrone.Common.Instrumentation
{
public static class GlobalExceptionHandlers
{
private static readonly Logger Logger = NzbDroneLogger.GetLogger();
private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(GlobalExceptionHandlers));
public static void Register()
{
AppDomain.CurrentDomain.UnhandledException += ((s, e) => AppDomainException(e.ExceptionObject as Exception));

@ -1,146 +0,0 @@
using System;
using System.Diagnostics;
using System.IO;
using LogentriesNLog;
using NLog;
using NLog.Config;
using NLog.Targets;
using NzbDrone.Common.EnvironmentInfo;
using NzbDrone.Common.Extensions;
namespace NzbDrone.Common.Instrumentation
{
public static class LogTargets
{
public static void Register(IStartupContext startupContext, bool updateApp, bool inConsole)
{
var appFolderInfo = new AppFolderInfo(startupContext);
LogManager.Configuration = new LoggingConfiguration();
if (Debugger.IsAttached)
{
RegisterDebugger();
}
//Disabling for now - until its fixed or we yank it out
//RegisterExceptron();
if (updateApp)
{
RegisterUpdateFile(appFolderInfo);
RegisterLogEntries();
}
else
{
if (inConsole && (OsInfo.IsNotWindows || RuntimeInfoBase.IsUserInteractive))
{
RegisterConsole();
}
RegisterAppFile(appFolderInfo);
}
LogManager.ReconfigExistingLoggers();
}
private static void RegisterLogEntries()
{
var target = new LogentriesTarget();
target.Name = "logentriesTarget";
target.Token = "d3a83ee9-74fb-4045-ad25-a84c1d4d7c81";
target.LogHostname = true;
target.Debug = false;
var loggingRule = new LoggingRule("*", LogLevel.Info, target);
LogManager.Configuration.AddTarget("logentries", target);
LogManager.Configuration.LoggingRules.Add(loggingRule);
}
private static void RegisterDebugger()
{
DebuggerTarget target = new DebuggerTarget();
target.Name = "debuggerLogger";
target.Layout = "[${level}] [${threadid}] ${logger}: ${message} ${onexception:inner=${newline}${newline}${exception:format=ToString}${newline}}";
var loggingRule = new LoggingRule("*", LogLevel.Trace, target);
LogManager.Configuration.AddTarget("debugger", target);
LogManager.Configuration.LoggingRules.Add(loggingRule);
}
private static void RegisterConsole()
{
var level = LogLevel.Trace;
if (RuntimeInfoBase.IsProduction)
{
level = LogLevel.Info;
}
var coloredConsoleTarget = new ColoredConsoleTarget();
coloredConsoleTarget.Name = "consoleLogger";
coloredConsoleTarget.Layout = "[${level}] ${logger}: ${message} ${onexception:inner=${newline}${newline}${exception:format=ToString}${newline}}";
var loggingRule = new LoggingRule("*", level, coloredConsoleTarget);
LogManager.Configuration.AddTarget("console", coloredConsoleTarget);
LogManager.Configuration.LoggingRules.Add(loggingRule);
}
const string FILE_LOG_LAYOUT = @"${date:format=yy-M-d HH\:mm\:ss.f}|${level}|${logger}|${message}${onexception:inner=${newline}${newline}${exception:format=ToString}${newline}}";
private static void RegisterAppFile(IAppFolderInfo appFolderInfo)
{
var fileTarget = new NzbDroneFileTarget();
fileTarget.Name = "rollingFileLogger";
fileTarget.FileName = Path.Combine(appFolderInfo.GetLogFolder(), "nzbdrone.txt");
fileTarget.AutoFlush = true;
fileTarget.KeepFileOpen = false;
fileTarget.ConcurrentWrites = false;
fileTarget.ConcurrentWriteAttemptDelay = 50;
fileTarget.ConcurrentWriteAttempts = 10;
fileTarget.ArchiveAboveSize = 1024000;
fileTarget.MaxArchiveFiles = 5;
fileTarget.EnableFileDelete = true;
fileTarget.ArchiveNumbering = ArchiveNumberingMode.Rolling;
fileTarget.Layout = FILE_LOG_LAYOUT;
var loggingRule = new LoggingRule("*", LogLevel.Trace, fileTarget);
LogManager.Configuration.AddTarget("appfile", fileTarget);
LogManager.Configuration.LoggingRules.Add(loggingRule);
}
private static void RegisterUpdateFile(IAppFolderInfo appFolderInfo)
{
var fileTarget = new FileTarget();
fileTarget.Name = "updateFileLogger";
fileTarget.FileName = Path.Combine(appFolderInfo.GetUpdateLogFolder(), DateTime.Now.ToString("yyyy.MM.dd-HH.mm") + ".txt");
fileTarget.AutoFlush = true;
fileTarget.KeepFileOpen = false;
fileTarget.ConcurrentWrites = false;
fileTarget.ConcurrentWriteAttemptDelay = 50;
fileTarget.ConcurrentWriteAttempts = 100;
fileTarget.Layout = FILE_LOG_LAYOUT;
var loggingRule = new LoggingRule("*", LogLevel.Trace, fileTarget);
LogManager.Configuration.AddTarget("updateFile", fileTarget);
LogManager.Configuration.LoggingRules.Add(loggingRule);
}
private static void RegisterExceptron()
{
var exceptronTarget = new ExceptronTarget();
var rule = new LoggingRule("*", LogLevel.Warn, exceptronTarget);
LogManager.Configuration.AddTarget("ExceptronTarget", exceptronTarget);
LogManager.Configuration.LoggingRules.Add(rule);
}
}
}

@ -1,42 +1,170 @@
using System;
using System.Diagnostics;
using System.IO;
using LogentriesNLog;
using NLog;
using NLog.Config;
using NLog.Targets;
using NzbDrone.Common.EnvironmentInfo;
using NzbDrone.Common.Extensions;
namespace NzbDrone.Common.Instrumentation
{
public static class NzbDroneLogger
{
public static Logger GetLogger()
private static bool _isConfigured;
static NzbDroneLogger()
{
string loggerName;
Type declaringType;
int framesToSkip = 1;
do
LogManager.Configuration = new LoggingConfiguration();
}
public static void Register(IStartupContext startupContext, bool updateApp, bool inConsole)
{
if (_isConfigured)
{
throw new InvalidOperationException("Loggers have already been registered.");
}
_isConfigured = true;
var appFolderInfo = new AppFolderInfo(startupContext);
if (Debugger.IsAttached)
{
RegisterDebugger();
}
//Disabling for now - until its fixed or we yank it out
//RegisterExceptron();
if (updateApp)
{
RegisterUpdateFile(appFolderInfo);
RegisterLogEntries();
}
else
{
var frame = new StackFrame(framesToSkip, false);
var method = frame.GetMethod();
declaringType = method.DeclaringType;
if (declaringType == null)
if (inConsole && (OsInfo.IsNotWindows || RuntimeInfoBase.IsUserInteractive))
{
loggerName = method.Name;
break;
RegisterConsole();
}
framesToSkip++;
loggerName = declaringType.Name;
} while (declaringType.Module.Name.Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase));
RegisterAppFile(appFolderInfo);
}
return LogManager.GetLogger(loggerName);
LogManager.ReconfigExistingLoggers();
}
public static Logger GetLogger(object obj)
private static void RegisterLogEntries()
{
var target = new LogentriesTarget();
target.Name = "logentriesTarget";
target.Token = "d3a83ee9-74fb-4045-ad25-a84c1d4d7c81";
target.LogHostname = true;
target.Debug = false;
var loggingRule = new LoggingRule("*", LogLevel.Info, target);
LogManager.Configuration.AddTarget("logentries", target);
LogManager.Configuration.LoggingRules.Add(loggingRule);
}
private static void RegisterDebugger()
{
DebuggerTarget target = new DebuggerTarget();
target.Name = "debuggerLogger";
target.Layout = "[${level}] [${threadid}] ${logger}: ${message} ${onexception:inner=${newline}${newline}${exception:format=ToString}${newline}}";
var loggingRule = new LoggingRule("*", LogLevel.Trace, target);
LogManager.Configuration.AddTarget("debugger", target);
LogManager.Configuration.LoggingRules.Add(loggingRule);
}
private static void RegisterConsole()
{
var level = LogLevel.Trace;
if (RuntimeInfoBase.IsProduction)
{
level = LogLevel.Info;
}
var coloredConsoleTarget = new ColoredConsoleTarget();
coloredConsoleTarget.Name = "consoleLogger";
coloredConsoleTarget.Layout = "[${level}] ${logger}: ${message} ${onexception:inner=${newline}${newline}${exception:format=ToString}${newline}}";
var loggingRule = new LoggingRule("*", level, coloredConsoleTarget);
LogManager.Configuration.AddTarget("console", coloredConsoleTarget);
LogManager.Configuration.LoggingRules.Add(loggingRule);
}
const string FILE_LOG_LAYOUT = @"${date:format=yy-M-d HH\:mm\:ss.f}|${level}|${logger}|${message}${onexception:inner=${newline}${newline}${exception:format=ToString}${newline}}";
private static void RegisterAppFile(IAppFolderInfo appFolderInfo)
{
var fileTarget = new NzbDroneFileTarget();
fileTarget.Name = "rollingFileLogger";
fileTarget.FileName = Path.Combine(appFolderInfo.GetLogFolder(), "nzbdrone.txt");
fileTarget.AutoFlush = true;
fileTarget.KeepFileOpen = false;
fileTarget.ConcurrentWrites = false;
fileTarget.ConcurrentWriteAttemptDelay = 50;
fileTarget.ConcurrentWriteAttempts = 10;
fileTarget.ArchiveAboveSize = 1024000;
fileTarget.MaxArchiveFiles = 5;
fileTarget.EnableFileDelete = true;
fileTarget.ArchiveNumbering = ArchiveNumberingMode.Rolling;
fileTarget.Layout = FILE_LOG_LAYOUT;
var loggingRule = new LoggingRule("*", LogLevel.Trace, fileTarget);
LogManager.Configuration.AddTarget("appfile", fileTarget);
LogManager.Configuration.LoggingRules.Add(loggingRule);
}
private static void RegisterUpdateFile(IAppFolderInfo appFolderInfo)
{
return LogManager.GetLogger(obj.GetType().Name);
var fileTarget = new FileTarget();
fileTarget.Name = "updateFileLogger";
fileTarget.FileName = Path.Combine(appFolderInfo.GetUpdateLogFolder(), DateTime.Now.ToString("yyyy.MM.dd-HH.mm") + ".txt");
fileTarget.AutoFlush = true;
fileTarget.KeepFileOpen = false;
fileTarget.ConcurrentWrites = false;
fileTarget.ConcurrentWriteAttemptDelay = 50;
fileTarget.ConcurrentWriteAttempts = 100;
fileTarget.Layout = FILE_LOG_LAYOUT;
var loggingRule = new LoggingRule("*", LogLevel.Trace, fileTarget);
LogManager.Configuration.AddTarget("updateFile", fileTarget);
LogManager.Configuration.LoggingRules.Add(loggingRule);
}
public static Logger GetLogger<T>()
private static void RegisterExceptron()
{
return LogManager.GetLogger(typeof(T).Name);
var exceptronTarget = new ExceptronTarget();
var rule = new LoggingRule("*", LogLevel.Warn, exceptronTarget);
LogManager.Configuration.AddTarget("ExceptronTarget", exceptronTarget);
LogManager.Configuration.LoggingRules.Add(rule);
}
public static Logger GetLogger(Type obj)
{
return LogManager.GetLogger(obj.Name.Replace("NzbDrone.", ""));
}
public static Logger GetLogger(object obj)
{
return GetLogger(obj.GetType());
}
}
}

@ -158,7 +158,6 @@
<Compile Include="Instrumentation\Extensions\LoggerProgressExtensions.cs" />
<Compile Include="Instrumentation\GlobalExceptionHandlers.cs" />
<Compile Include="Instrumentation\LogEventExtensions.cs" />
<Compile Include="Instrumentation\LogTargets.cs" />
<Compile Include="Instrumentation\NzbDroneFileTarget.cs" />
<Compile Include="Instrumentation\NzbDroneLogger.cs" />
<Compile Include="Instrumentation\VersionLayoutRenderer.cs" />

@ -31,11 +31,16 @@ namespace NzbDrone.Common.Processes
public class ProcessProvider : IProcessProvider
{
private static readonly Logger Logger = NzbDroneLogger.GetLogger();
private readonly Logger _logger;
public const string NZB_DRONE_PROCESS_NAME = "NzbDrone";
public const string NZB_DRONE_CONSOLE_PROCESS_NAME = "NzbDrone.Console";
public ProcessProvider(Logger logger)
{
_logger = logger;
}
public ProcessInfo GetCurrentProcess()
{
return ConvertToProcessInfo(Process.GetCurrentProcess());
@ -58,17 +63,17 @@ namespace NzbDrone.Common.Processes
public ProcessInfo GetProcessById(int id)
{
Logger.Debug("Finding process with Id:{0}", id);
_logger.Debug("Finding process with Id:{0}", id);
var processInfo = ConvertToProcessInfo(Process.GetProcesses().FirstOrDefault(p => p.Id == id));
if (processInfo == null)
{
Logger.Warn("Unable to find process with ID {0}", id);
_logger.Warn("Unable to find process with ID {0}", id);
}
else
{
Logger.Debug("Found process {0}", processInfo.ToString());
_logger.Debug("Found process {0}", processInfo.ToString());
}
return processInfo;
@ -81,7 +86,7 @@ namespace NzbDrone.Common.Processes
public void OpenDefaultBrowser(string url)
{
Logger.Info("Opening URL [{0}]", url);
_logger.Info("Opening URL [{0}]", url);
var process = new Process
{
@ -161,7 +166,7 @@ namespace NzbDrone.Common.Processes
path = "mono";
}
Logger.Debug("Starting {0} {1}", path, args);
_logger.Debug("Starting {0} {1}", path, args);
var startInfo = new ProcessStartInfo(path, args);
var process = new Process
@ -184,7 +189,7 @@ namespace NzbDrone.Common.Processes
public void WaitForExit(Process process)
{
Logger.Debug("Waiting for process {0} to exit.", process.ProcessName);
_logger.Debug("Waiting for process {0} to exit.", process.ProcessName);
process.WaitForExit();
}
@ -193,7 +198,7 @@ namespace NzbDrone.Common.Processes
{
var process = Process.GetProcessById(processId);
Logger.Info("Updating [{0}] process priority from {1} to {2}",
_logger.Info("Updating [{0}] process priority from {1} to {2}",
process.ProcessName,
process.PriorityClass,
priority);
@ -207,7 +212,7 @@ namespace NzbDrone.Common.Processes
if (process == null)
{
Logger.Warn("Cannot find process with id: {0}", processId);
_logger.Warn("Cannot find process with id: {0}", processId);
return;
}
@ -215,31 +220,31 @@ namespace NzbDrone.Common.Processes
if (process.HasExited)
{
Logger.Debug("Process has already exited");
_logger.Debug("Process has already exited");
return;
}
Logger.Info("[{0}]: Killing process", process.Id);
_logger.Info("[{0}]: Killing process", process.Id);
process.Kill();
Logger.Info("[{0}]: Waiting for exit", process.Id);
_logger.Info("[{0}]: Waiting for exit", process.Id);
process.WaitForExit();
Logger.Info("[{0}]: Process terminated successfully", process.Id);
_logger.Info("[{0}]: Process terminated successfully", process.Id);
}
public void KillAll(string processName)
{
var processes = GetProcessesByName(processName);
Logger.Debug("Found {0} processes to kill", processes.Count);
_logger.Debug("Found {0} processes to kill", processes.Count);
foreach (var processInfo in processes)
{
Logger.Debug("Killing process: {0} [{1}]", processInfo.Id, processInfo.ProcessName);
_logger.Debug("Killing process: {0} [{1}]", processInfo.Id, processInfo.ProcessName);
Kill(processInfo.Id);
}
}
private static ProcessInfo ConvertToProcessInfo(Process process)
private ProcessInfo ConvertToProcessInfo(Process process)
{
if (process == null) return null;
@ -263,7 +268,7 @@ namespace NzbDrone.Common.Processes
}
catch (Win32Exception e)
{
Logger.WarnException("Couldn't get process info for " + process.ProcessName, e);
_logger.WarnException("Couldn't get process info for " + process.ProcessName, e);
}
return processInfo;
@ -280,7 +285,7 @@ namespace NzbDrone.Common.Processes
return process.Modules.Cast<ProcessModule>().FirstOrDefault(module => module.ModuleName.ToLower().EndsWith(".exe")).FileName;
}
private static List<Process> GetProcessesByName(string name)
private List<Process> GetProcessesByName(string name)
{
//TODO: move this to an OS specific class
@ -294,7 +299,7 @@ namespace NzbDrone.Common.Processes
var processes = Process.GetProcessesByName(name)
.Union(monoProcesses).ToList();
Logger.Debug("Found {0} processes with the name: {1}", processes.Count, name);
_logger.Debug("Found {0} processes with the name: {1}", processes.Count, name);
return processes;
}

@ -8,7 +8,7 @@ namespace NzbDrone.Common.Security
{
public static class X509CertificateValidationPolicy
{
private static readonly Logger Logger = NzbDroneLogger.GetLogger();
private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(X509CertificateValidationPolicy));
public static void Register()
{

@ -5,7 +5,6 @@ using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using NLog;
using NzbDrone.Common.Instrumentation;
using NzbDrone.Common.Processes;
namespace NzbDrone.Common
@ -29,17 +28,18 @@ namespace NzbDrone.Common
public const string NZBDRONE_SERVICE_NAME = "NzbDrone";
private readonly IProcessProvider _processProvider;
private readonly Logger _logger;
private static readonly Logger Logger = NzbDroneLogger.GetLogger();
public ServiceProvider(IProcessProvider processProvider)
public ServiceProvider(IProcessProvider processProvider, Logger logger)
{
_processProvider = processProvider;
_logger = logger;
}
public virtual bool ServiceExist(string name)
{
Logger.Debug("Checking if service {0} exists.", name);
_logger.Debug("Checking if service {0} exists.", name);
return
ServiceController.GetServices().Any(
s => String.Equals(s.ServiceName, name, StringComparison.InvariantCultureIgnoreCase));
@ -47,7 +47,7 @@ namespace NzbDrone.Common
public virtual bool IsServiceRunning(string name)
{
Logger.Debug("Checking if '{0}' service is running", name);
_logger.Debug("Checking if '{0}' service is running", name);
var service = ServiceController.GetServices()
.SingleOrDefault(s => String.Equals(s.ServiceName, name, StringComparison.InvariantCultureIgnoreCase));
@ -61,7 +61,7 @@ namespace NzbDrone.Common
public virtual void Install(string serviceName)
{
Logger.Info("Installing service '{0}'", serviceName);
_logger.Info("Installing service '{0}'", serviceName);
var installer = new ServiceProcessInstaller
@ -86,12 +86,12 @@ namespace NzbDrone.Common
serviceInstaller.Install(new ListDictionary());
Logger.Info("Service Has installed successfully.");
_logger.Info("Service Has installed successfully.");
}
public virtual void UnInstall(string serviceName)
{
Logger.Info("Uninstalling {0} service", serviceName);
_logger.Info("Uninstalling {0} service", serviceName);
Stop(serviceName);
@ -102,7 +102,7 @@ namespace NzbDrone.Common
serviceInstaller.ServiceName = serviceName;
serviceInstaller.Uninstall(null);
Logger.Info("{0} successfully uninstalled", serviceName);
_logger.Info("{0} successfully uninstalled", serviceName);
}
public virtual void Run(ServiceBase service)
@ -117,15 +117,15 @@ namespace NzbDrone.Common
public virtual void Stop(string serviceName)
{
Logger.Info("Stopping {0} Service...", serviceName);
_logger.Info("Stopping {0} Service...", serviceName);
var service = GetService(serviceName);
if (service == null)
{
Logger.Warn("Unable to stop {0}. no service with that name exists.", serviceName);
_logger.Warn("Unable to stop {0}. no service with that name exists.", serviceName);
return;
}
Logger.Info("Service is currently {0}", service.Status);
_logger.Info("Service is currently {0}", service.Status);
if (service.Status != ServiceControllerStatus.Stopped)
{
@ -135,16 +135,16 @@ namespace NzbDrone.Common
service.Refresh();
if (service.Status == ServiceControllerStatus.Stopped)
{
Logger.Info("{0} has stopped successfully.", serviceName);
_logger.Info("{0} has stopped successfully.", serviceName);
}
else
{
Logger.Error("Service stop request has timed out. {0}", service.Status);
_logger.Error("Service stop request has timed out. {0}", service.Status);
}
}
else
{
Logger.Warn("Service {0} is already in stopped state.", service.ServiceName);
_logger.Warn("Service {0} is already in stopped state.", service.ServiceName);
}
}
@ -155,17 +155,17 @@ namespace NzbDrone.Common
public void Start(string serviceName)
{
Logger.Info("Starting {0} Service...", serviceName);
_logger.Info("Starting {0} Service...", serviceName);
var service = GetService(serviceName);
if (service == null)
{
Logger.Warn("Unable to start '{0}' no service with that name exists.", serviceName);
_logger.Warn("Unable to start '{0}' no service with that name exists.", serviceName);
return;
}
if (service.Status != ServiceControllerStatus.Paused && service.Status != ServiceControllerStatus.Stopped)
{
Logger.Warn("Service is in a state that can't be started. Current status: {0}", service.Status);
_logger.Warn("Service is in a state that can't be started. Current status: {0}", service.Status);
}
service.Start();
@ -175,11 +175,11 @@ namespace NzbDrone.Common
if (service.Status == ServiceControllerStatus.Running)
{
Logger.Info("{0} has started successfully.", serviceName);
_logger.Info("{0} has started successfully.", serviceName);
}
else
{
Logger.Error("Service start request has timed out. {0}", service.Status);
_logger.Error("Service start request has timed out. {0}", service.Status);
}
}

@ -6,18 +6,20 @@ namespace NzbDrone.Common.TPL
{
public static class TaskExtensions
{
private static readonly Logger Logger = NzbDroneLogger.GetLogger();
private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(TaskExtensions));
public static Task LogExceptions(this Task task)
{
task.ContinueWith(t =>
{
var aggregateException = t.Exception.Flatten();
foreach (var exception in aggregateException.InnerExceptions)
if (t.Exception != null)
{
Logger.ErrorException("Task Error", exception);
var aggregateException = t.Exception.Flatten();
foreach (var exception in aggregateException.InnerExceptions)
{
Logger.ErrorException("Task Error", exception);
}
}
}, TaskContinuationOptions.OnlyOnFaulted);
return task;

@ -9,14 +9,14 @@ namespace NzbDrone.Console
{
public static class ConsoleApp
{
private static readonly Logger Logger = NzbDroneLogger.GetLogger();
private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(ConsoleApp));
public static void Main(string[] args)
{
try
{
var startupArgs = new StartupContext(args);
LogTargets.Register(startupArgs, false, true);
NzbDroneLogger.Register(startupArgs, false, true);
Bootstrap.Start(startupArgs, new ConsoleAlerts());
}
catch (SocketException exception)

@ -35,9 +35,9 @@ namespace NzbDrone.Core.Test.InstrumentationTests
LogManager.ReconfigExistingLoggers();
_logger = NzbDroneLogger.GetLogger();
_logger = NzbDroneLogger.GetLogger(this);
_uniqueMessage = "Unique message: " + Guid.NewGuid().ToString();
_uniqueMessage = "Unique message: " + Guid.NewGuid();
}
[Test]

@ -16,7 +16,7 @@ namespace NzbDrone.Core.Datastore
{
private readonly Func<IDataMapper> _datamapperFactory;
private Logger logger = NzbDroneLogger.GetLogger();
private readonly Logger _logger = NzbDroneLogger.GetLogger(typeof(Database));
public Database(Func<IDataMapper> datamapperFactory)
{
@ -42,13 +42,13 @@ namespace NzbDrone.Core.Datastore
{
try
{
logger.Info("Vacuuming database");
_logger.Info("Vacuuming database");
_datamapperFactory().ExecuteNonQuery("Vacuum;");
logger.Info("Database Compressed");
_logger.Info("Database Compressed");
}
catch (Exception e)
{
logger.Error("An Error occurred while vacuuming database.", e);
_logger.Error("An Error occurred while vacuuming database.", e);
}
}
}

@ -12,7 +12,7 @@ namespace NzbDrone.Core.Indexers
{
public static class XElementExtensions
{
private static readonly Logger Logger = NzbDroneLogger.GetLogger();
private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(XmlExtentions));
public static readonly Regex RemoveTimeZoneRegex = new Regex(@"\s[A-Z]{2,4}$", RegexOptions.Compiled);

@ -4,7 +4,6 @@ using NLog;
using NzbDrone.Common.Disk;
using NzbDrone.Common.EnvironmentInfo;
using NzbDrone.Common.Extensions;
using NzbDrone.Common.Instrumentation;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.MediaFiles.Commands;
using NzbDrone.Core.Messaging.Commands;
@ -25,35 +24,36 @@ namespace NzbDrone.Core.MediaFiles
{
private readonly IDiskProvider _diskProvider;
private readonly IConfigService _configService;
private readonly Logger _logger;
private static readonly Logger logger = NzbDroneLogger.GetLogger();
public RecycleBinProvider(IDiskProvider diskProvider, IConfigService configService)
public RecycleBinProvider(IDiskProvider diskProvider, IConfigService configService, Logger logger)
{
_diskProvider = diskProvider;
_configService = configService;
_logger = logger;
}
public void DeleteFolder(string path)
{
logger.Info("Attempting to send '{0}' to recycling bin", path);
_logger.Info("Attempting to send '{0}' to recycling bin", path);
var recyclingBin = _configService.RecycleBin;
if (String.IsNullOrWhiteSpace(recyclingBin))
{
logger.Info("Recycling Bin has not been configured, deleting permanently. {0}", path);
_logger.Info("Recycling Bin has not been configured, deleting permanently. {0}", path);
_diskProvider.DeleteFolder(path, true);
logger.Debug("Folder has been permanently deleted: {0}", path);
_logger.Debug("Folder has been permanently deleted: {0}", path);
}
else
{
var destination = Path.Combine(recyclingBin, new DirectoryInfo(path).Name);
logger.Debug("Moving '{0}' to '{1}'", path, destination);
_logger.Debug("Moving '{0}' to '{1}'", path, destination);
_diskProvider.MoveFolder(path, destination);
logger.Debug("Setting last accessed: {0}", path);
_logger.Debug("Setting last accessed: {0}", path);
_diskProvider.FolderSetLastWriteTime(destination, DateTime.UtcNow);
foreach (var file in _diskProvider.GetFiles(destination, SearchOption.AllDirectories))
{
@ -64,26 +64,26 @@ namespace NzbDrone.Core.MediaFiles
}
}
logger.Debug("Folder has been moved to the recycling bin: {0}", destination);
_logger.Debug("Folder has been moved to the recycling bin: {0}", destination);
}
}
public void DeleteFile(string path)
{
logger.Debug("Attempting to send '{0}' to recycling bin", path);
_logger.Debug("Attempting to send '{0}' to recycling bin", path);
var recyclingBin = _configService.RecycleBin;
if (String.IsNullOrWhiteSpace(recyclingBin))
{
logger.Info("Recycling Bin has not been configured, deleting permanently. {0}", path);
_logger.Info("Recycling Bin has not been configured, deleting permanently. {0}", path);
if (OsInfo.IsWindows)
{
logger.Debug(_diskProvider.GetFileAttributes(path));
_logger.Debug(_diskProvider.GetFileAttributes(path));
}
_diskProvider.DeleteFile(path);
logger.Debug("File has been permanently deleted: {0}", path);
_logger.Debug("File has been permanently deleted: {0}", path);
}
else
@ -105,7 +105,7 @@ namespace NzbDrone.Core.MediaFiles
}
}
logger.Debug("Moving '{0}' to '{1}'", path, destination);
_logger.Debug("Moving '{0}' to '{1}'", path, destination);
_diskProvider.MoveFile(path, destination, true);
//TODO: Better fix than this for non-Windows?
@ -114,7 +114,7 @@ namespace NzbDrone.Core.MediaFiles
_diskProvider.FileSetLastWriteTime(destination, DateTime.UtcNow);
}
logger.Debug("File has been moved to the recycling bin: {0}", destination);
_logger.Debug("File has been moved to the recycling bin: {0}", destination);
}
}
@ -122,11 +122,11 @@ namespace NzbDrone.Core.MediaFiles
{
if (String.IsNullOrWhiteSpace(_configService.RecycleBin))
{
logger.Info("Recycle Bin has not been configured, cannot empty.");
_logger.Info("Recycle Bin has not been configured, cannot empty.");
return;
}
logger.Info("Removing all items from the recycling bin");
_logger.Info("Removing all items from the recycling bin");
foreach (var folder in _diskProvider.GetDirectories(_configService.RecycleBin))
{
@ -138,24 +138,24 @@ namespace NzbDrone.Core.MediaFiles
_diskProvider.DeleteFile(file);
}
logger.Debug("Recycling Bin has been emptied.");
_logger.Debug("Recycling Bin has been emptied.");
}
public void Cleanup()
{
if (String.IsNullOrWhiteSpace(_configService.RecycleBin))
{
logger.Info("Recycle Bin has not been configured, cannot cleanup.");
_logger.Info("Recycle Bin has not been configured, cannot cleanup.");
return;
}
logger.Info("Removing items older than 7 days from the recycling bin");
_logger.Info("Removing items older than 7 days from the recycling bin");
foreach (var folder in _diskProvider.GetDirectories(_configService.RecycleBin))
{
if (_diskProvider.FolderGetLastWrite(folder).AddDays(7) > DateTime.UtcNow)
{
logger.Debug("Folder hasn't expired yet, skipping: {0}", folder);
_logger.Debug("Folder hasn't expired yet, skipping: {0}", folder);
continue;
}
@ -166,14 +166,14 @@ namespace NzbDrone.Core.MediaFiles
{
if (_diskProvider.FileGetLastWrite(file).AddDays(7) > DateTime.UtcNow)
{
logger.Debug("File hasn't expired yet, skipping: {0}", file);
_logger.Debug("File hasn't expired yet, skipping: {0}", file);
continue;
}
_diskProvider.DeleteFile(file);
}
logger.Debug("Recycling Bin has been cleaned up.");
_logger.Debug("Recycling Bin has been cleaned up.");
}
public void HandleAsync(SeriesDeletedEvent message)

@ -13,7 +13,7 @@ namespace NzbDrone.Core.Parser
{
public static class Parser
{
private static readonly Logger Logger = NzbDroneLogger.GetLogger();
private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(Parser));
private static readonly Regex[] ReportTitleRegex = new[]
{
@ -665,7 +665,7 @@ namespace NzbDrone.Core.Parser
if (hash.Success)
{
var hashValue = hash.Value.Trim('[',']');
var hashValue = hash.Value.Trim('[', ']');
if (hashValue.Equals("1280x720"))
{
@ -674,7 +674,7 @@ namespace NzbDrone.Core.Parser
return hashValue;
}
return String.Empty;
}
}

@ -11,7 +11,7 @@ namespace NzbDrone.Core.Rest
{
public static class RestSharpExtensions
{
private static readonly Logger Logger = NzbDroneLogger.GetLogger();
private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(RestSharpExtensions));
public static IRestResponse ValidateResponse(this IRestResponse response, IRestClient restClient)
{

@ -23,7 +23,6 @@ namespace NzbDrone.Core.RootFolders
public class RootFolderService : IRootFolderService
{
private static readonly Logger Logger = NzbDroneLogger.GetLogger();
private readonly IRootFolderRepository _rootFolderRepository;
private readonly IDiskProvider _diskProvider;
private readonly ISeriesRepository _seriesRepository;
@ -110,7 +109,7 @@ namespace NzbDrone.Core.RootFolders
private List<UnmappedFolder> GetUnmappedFolders(string path)
{
Logger.Debug("Generating list of unmapped folders");
_logger.Debug("Generating list of unmapped folders");
if (String.IsNullOrEmpty(path))
throw new ArgumentException("Invalid path provided", "path");
@ -119,7 +118,7 @@ namespace NzbDrone.Core.RootFolders
if (!_diskProvider.FolderExists(path))
{
Logger.Debug("Path supplied does not exist: {0}", path);
_logger.Debug("Path supplied does not exist: {0}", path);
return results;
}
@ -135,7 +134,7 @@ namespace NzbDrone.Core.RootFolders
var setToRemove = SpecialFolders;
results.RemoveAll(x => setToRemove.Contains(new DirectoryInfo(x.Path.ToLowerInvariant()).Name));
Logger.Debug("{0} unmapped folders detected.", results.Count);
_logger.Debug("{0} unmapped folders detected.", results.Count);
return results;
}

@ -14,12 +14,10 @@ namespace NzbDrone.Host
public static class Bootstrap
{
private static IContainer _container;
private static readonly Logger Logger = NzbDroneLogger.GetLogger();
private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(Bootstrap));
public static void Start(StartupContext startupContext, IUserAlert userAlert, Action<IContainer> startCallback = null)
{
LogTargets.Register(startupContext, false, true);
try
{
GlobalExceptionHandlers.Register();

@ -9,7 +9,7 @@ namespace NzbDrone.Host
{
public static class PlatformValidation
{
private static readonly Logger Logger = NzbDroneLogger.GetLogger();
private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(PlatformValidation));
private const string DOWNLOAD_LINK = "http://www.microsoft.com/en-us/download/details.aspx?id=42643";

@ -65,7 +65,7 @@ namespace NzbDrone.Integration.Test
[TestFixtureSetUp]
public void SmokeTestSetup()
{
_runner = new NzbDroneRunner();
_runner = new NzbDroneRunner(LogManager.GetCurrentClassLogger());
_runner.KillAll();
_runner.Start();

@ -13,7 +13,7 @@ namespace NzbDrone.Mono
{
public class DiskProvider : DiskProviderBase
{
private static readonly Logger Logger = NzbDroneLogger.GetLogger();
private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(DiskProvider));
public override long? GetAvailableSpace(string path)
{

@ -5,6 +5,7 @@ using System.Threading;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using NLog;
using NUnit.Framework;
using NzbDrone.Common.EnvironmentInfo;
using NzbDrone.Common.Processes;
@ -21,9 +22,9 @@ namespace NzbDrone.Test.Common
public string AppData { get; private set; }
public string ApiKey { get; private set; }
public NzbDroneRunner(int port = 8989)
public NzbDroneRunner(Logger logger, int port = 8989)
{
_processProvider = new ProcessProvider();
_processProvider = new ProcessProvider(logger);
_restClient = new RestClient("http://localhost:8989/api");
}

@ -18,7 +18,7 @@ namespace NzbDrone.Update
private readonly IProcessProvider _processProvider;
private static IContainer _container;
private static readonly Logger logger = NzbDroneLogger.GetLogger();
private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(UpdateApp));
public UpdateApp(IInstallUpdateService installUpdateService, IProcessProvider processProvider)
{
@ -31,7 +31,7 @@ namespace NzbDrone.Update
try
{
var startupArgument = new StartupContext(args);
LogTargets.Register(startupArgument, true, true);
NzbDroneLogger.Register(startupArgument, true, true);
Console.WriteLine("Starting NzbDrone Update Client");
@ -41,12 +41,12 @@ namespace NzbDrone.Update
_container = UpdateContainerBuilder.Build(startupArgument);
logger.Info("Updating NzbDrone to version {0}", BuildInfo.Version);
Logger.Info("Updating NzbDrone to version {0}", BuildInfo.Version);
_container.Resolve<UpdateApp>().Start(args);
}
catch (Exception e)
{
logger.FatalException("An error has occurred while applying update package.", e);
Logger.FatalException("An error has occurred while applying update package.", e);
}
}
@ -54,8 +54,8 @@ namespace NzbDrone.Update
{
var startupContext = ParseArgs(args);
var targetFolder = GetInstallationDirectory(startupContext);
logger.Info("Starting update process. Target Path:{0}", targetFolder);
Logger.Info("Starting update process. Target Path:{0}", targetFolder);
_installUpdateService.Start(targetFolder, startupContext.ProcessId);
}
@ -82,18 +82,18 @@ namespace NzbDrone.Update
startupContext.ExecutingApplication = args[2];
break;
default:
{
logger.Debug("Arguments:");
foreach (var arg in args)
{
logger.Debug(" {0}", arg);
}
Logger.Debug("Arguments:");
var message = String.Format("Number of arguments are unexpected, expected: 3, found: {0}", args.Count());
foreach (var arg in args)
{
Logger.Debug(" {0}", arg);
}
throw new ArgumentOutOfRangeException("args", message);
}
var message = String.Format("Number of arguments are unexpected, expected: 3, found: {0}", args.Count());
throw new ArgumentOutOfRangeException("args", message);
}
}
}
@ -108,7 +108,7 @@ namespace NzbDrone.Update
throw new ArgumentOutOfRangeException("arg", "Invalid process ID");
}
logger.Debug("NzbDrone process ID: {0}", id);
Logger.Debug("NzbDrone process ID: {0}", id);
return id;
}
@ -116,18 +116,18 @@ namespace NzbDrone.Update
{
if (startupContext.ExecutingApplication.IsNullOrWhiteSpace())
{
logger.Debug("Using process ID to find installation directory: {0}", startupContext.ProcessId);
Logger.Debug("Using process ID to find installation directory: {0}", startupContext.ProcessId);
var exeFileInfo = new FileInfo(_processProvider.GetProcessById(startupContext.ProcessId).StartPath);
logger.Debug("Executable location: {0}", exeFileInfo.FullName);
Logger.Debug("Executable location: {0}", exeFileInfo.FullName);
return exeFileInfo.DirectoryName;
}
else
{
logger.Debug("Using executing application: {0}", startupContext.ExecutingApplication);
Logger.Debug("Using executing application: {0}", startupContext.ExecutingApplication);
var exeFileInfo = new FileInfo(startupContext.ExecutingApplication);
logger.Debug("Executable location: {0}", exeFileInfo.FullName);
Logger.Debug("Executable location: {0}", exeFileInfo.FullName);
return exeFileInfo.DirectoryName;
}

@ -10,7 +10,7 @@ namespace NzbDrone.Windows
{
public class DiskProvider : DiskProviderBase
{
private static readonly Logger Logger = NzbDroneLogger.GetLogger();
private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(DiskProvider));
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]

@ -10,7 +10,7 @@ namespace NzbDrone
{
public static class WindowsApp
{
private static readonly Logger Logger = NzbDroneLogger.GetLogger();
private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(WindowsApp));
public static void Main(string[] args)
{
@ -18,7 +18,7 @@ namespace NzbDrone
{
var startupArgs = new StartupContext(args);
LogTargets.Register(startupArgs, false, true);
NzbDroneLogger.Register(startupArgs, false, true);
Bootstrap.Start(startupArgs, new MessageBoxUserAlert(), container =>
{

Loading…
Cancel
Save