diff --git a/src/Umbraco.Core/Components/BootLoader.cs b/src/Umbraco.Core/Components/BootLoader.cs index 0840449789..b28119cac1 100644 --- a/src/Umbraco.Core/Components/BootLoader.cs +++ b/src/Umbraco.Core/Components/BootLoader.cs @@ -179,7 +179,7 @@ namespace Umbraco.Core.Components foreach (var component in _components) { var componentType = component.GetType(); - using (_proflog.DebugDuration($"Composing {componentType.FullName}.", $"Composed {componentType.FullName}.", LogThresholdMilliseconds)) + using (_proflog.DebugDuration($"Composing {componentType.FullName}.", $"Composed {componentType.FullName}.", thresholdMilliseconds: LogThresholdMilliseconds)) { component.Compose(_container, level); } @@ -199,7 +199,7 @@ namespace Umbraco.Core.Components var componentType = component.GetType(); var initializers = componentType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) .Where(x => x.Name == "Initialize" && x.IsGenericMethod == false); - using (_proflog.DebugDuration($"Initializing {componentType.FullName}.", $"Initialised {componentType.FullName}.", LogThresholdMilliseconds)) + using (_proflog.DebugDuration($"Initializing {componentType.FullName}.", $"Initialised {componentType.FullName}.", thresholdMilliseconds: LogThresholdMilliseconds)) { foreach (var initializer in initializers) { @@ -222,14 +222,18 @@ namespace Umbraco.Core.Components public void Terminate() { - if (_booted == false) throw new InvalidOperationException("Cannot terminate, has not booted."); + if (_booted == false) + { + _proflog.Logger.Warn("Cannot terminate, has not booted."); + return; + } using (_proflog.DebugDuration($"Terminating. (log components when >{LogThresholdMilliseconds}ms)", "Terminated.")) { foreach (var component in _components) { var componentType = component.GetType(); - using (_proflog.DebugDuration($"Terminating {componentType.FullName}.", $"Terminated {componentType.FullName}.", LogThresholdMilliseconds)) + using (_proflog.DebugDuration($"Terminating {componentType.FullName}.", $"Terminated {componentType.FullName}.", thresholdMilliseconds: LogThresholdMilliseconds)) { component.Terminate(); } diff --git a/src/Umbraco.Core/Configuration/UmbracoConfig.cs b/src/Umbraco.Core/Configuration/UmbracoConfig.cs index e36004cdf8..6ed27fe664 100644 --- a/src/Umbraco.Core/Configuration/UmbracoConfig.cs +++ b/src/Umbraco.Core/Configuration/UmbracoConfig.cs @@ -5,6 +5,7 @@ using Umbraco.Core.Cache; using Umbraco.Core.Configuration.Dashboard; using Umbraco.Core.Configuration.Grid; using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.Logging; namespace Umbraco.Core.Configuration @@ -66,7 +67,7 @@ namespace Umbraco.Core.Configuration if (_dashboardSection == null) { var ex = new ConfigurationErrorsException("Could not load the " + typeof(IDashboardSection) + " from config file, ensure the web.config and Dashboard.config files are formatted correctly"); - LogHelper.Error("Config error", ex); + Current.Logger.Error("Config error", ex); throw ex; } @@ -99,7 +100,7 @@ namespace Umbraco.Core.Configuration if (_umbracoSettings == null) { var ex = new ConfigurationErrorsException("Could not load the " + typeof (IUmbracoSettingsSection) + " from config file, ensure the web.config and umbracoSettings.config files are formatted correctly"); - LogHelper.Error("Config error", ex); + Current.Logger.Error("Config error", ex); throw ex; } diff --git a/src/Umbraco.Core/Configuration/UmbracoVersion.cs b/src/Umbraco.Core/Configuration/UmbracoVersion.cs index ee87379d90..d96e8ceddc 100644 --- a/src/Umbraco.Core/Configuration/UmbracoVersion.cs +++ b/src/Umbraco.Core/Configuration/UmbracoVersion.cs @@ -21,7 +21,7 @@ namespace Umbraco.Core.Configuration /// /// Gets the version comment of the executing code (eg "beta"). /// - public static string CurrentComment => "alpha0016"; + public static string CurrentComment => "alpha0017"; /// /// Gets the assembly version of Umbraco.Code.dll. diff --git a/src/Umbraco.Core/CoreRuntime.cs b/src/Umbraco.Core/CoreRuntime.cs index 45f72e50df..cc1a15c9f9 100644 --- a/src/Umbraco.Core/CoreRuntime.cs +++ b/src/Umbraco.Core/CoreRuntime.cs @@ -71,44 +71,93 @@ namespace Umbraco.Core // are NOT disposed - which is not a big deal as long as they remain lightweight // objects. - using (ProfilingLogger.TraceDuration($"Booting Umbraco {UmbracoVersion.SemanticVersion.ToSemanticString()} on {NetworkHelper.MachineName}.", "Booted.")) + using (var bootTimer = ProfilingLogger.TraceDuration( + $"Booting Umbraco {UmbracoVersion.SemanticVersion.ToSemanticString()} on {NetworkHelper.MachineName}.", + "Booted.", + "Boot failed.")) { - Logger.Debug($"Runtime: {GetType().FullName}"); - - using (ProfilingLogger.DebugDuration("Acquiring MainDom.", "Aquired.")) + try + { + Logger.Debug($"Runtime: {GetType().FullName}"); + + AquireMainDom(container); + DetermineRuntimeLevel(container); + var componentTypes = ResolveComponentTypes(); + _bootLoader = new BootLoader(container); + _bootLoader.Boot(componentTypes, _state.Level); + + // this was done in Complete() right before running the Started event handlers + // "special case for the user service, we need to tell it if it's an upgrade, if so we need to ensure that + // exceptions are bubbled up if a user is attempted to be persisted during an upgrade (i.e. when they auth to login)" + // + // was *always* setting the value to true which is?! so using the runtime level + // and then, it is *never* resetted to false, meaning Umbraco has been running with IsUpgrading being true? + // fixme - this is... bad + ((UserService) Current.Services.UserService).IsUpgrading = _state.Level == RuntimeLevel.Upgrade; + } + catch (Exception e) + { + _state.Level = RuntimeLevel.BootFailed; + var bfe = e as BootFailedException ?? new BootFailedException("Boot failed.", e); + bootTimer.Fail(exception: bfe); // be sure to log the exception - even if we repeat ourselves + + // throwing here can cause w3wp to hard-crash and we want to avoid it. + // instead, we're logging the exception and setting level to BootFailed. + // various parts of Umbraco such as UmbracoModule and UmbracoDefaultOwinStartup + // understand this and will nullify themselves, while UmbracoModule will + // throw a BootFailedException for every requests. + } + } + } + + private void AquireMainDom(IServiceFactory container) + { + using (var timer = ProfilingLogger.DebugDuration("Acquiring MainDom.", "Aquired.")) + { + try { - // become the main domain - before anything else var mainDom = container.GetInstance(); mainDom.Acquire(); } + catch + { + timer.Fail(); + throw; + } + } + } - using (ProfilingLogger.DebugDuration("Determining runtime level.", "Determined.")) + private void DetermineRuntimeLevel(IServiceFactory container) + { + using (var timer = ProfilingLogger.DebugDuration("Determining runtime level.", "Determined.")) + { + try { var dbfactory = container.GetInstance(); SetRuntimeStateLevel(_state, dbfactory, Logger); + Logger.Debug($"Runtime level: {_state.Level}"); } - - Logger.Debug($"Runtime level: {_state.Level}"); - - IEnumerable componentTypes; - using (ProfilingLogger.TraceDuration("Resolving component types.", "Resolved.")) + catch { - componentTypes = GetComponentTypes(); + timer.Fail(); + throw; } + } + } - // boot - _bootLoader = new BootLoader(container); - _bootLoader.Boot(componentTypes, _state.Level); - - // this was done in Complete() right before running the Started event handlers - // "special case for the user service, we need to tell it if it's an upgrade, if so we need to ensure that - // exceptions are bubbled up if a user is attempted to be persisted during an upgrade (i.e. when they auth to login)" - // - // was *always* setting the value to true which is?! so using the runtime level - // and then, it is *never* resetted to false, meaning Umbraco has been running with IsUpgrading being true? - // fixme - this is... bad - ((UserService) Current.Services.UserService).IsUpgrading = _state.Level == RuntimeLevel.Upgrade; - + private IEnumerable ResolveComponentTypes() + { + using (var timer = ProfilingLogger.TraceDuration("Resolving component types.", "Resolved.")) + { + try + { + return GetComponentTypes(); + } + catch + { + timer.Fail(); + throw; + } } } @@ -217,7 +266,7 @@ namespace Umbraco.Core { // cannot connect to configured database, this is bad, fail logger.Debug("Could not connect to database."); - runtimeState.Level = RuntimeLevel.Failed; + runtimeState.Level = RuntimeLevel.BootFailed; // in fact, this is bad enough that we want to throw throw new BootFailedException("A connection string is configured but Umbraco could not connect to the database."); diff --git a/src/Umbraco.Core/DatabaseContext.cs b/src/Umbraco.Core/DatabaseContext.cs index e28b44e723..617c8a563e 100644 --- a/src/Umbraco.Core/DatabaseContext.cs +++ b/src/Umbraco.Core/DatabaseContext.cs @@ -9,6 +9,7 @@ using System.Xml.Linq; using NPoco; using Semver; using Umbraco.Core.Configuration; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Persistence; @@ -90,7 +91,7 @@ namespace Umbraco.Core { if (IsDatabaseConfigured == false) return false; var canConnect = _factory.CanConnect; - LogHelper.Info("CanConnect = " + canConnect); + Current.Logger.Info("CanConnect = " + canConnect); return canConnect; } } diff --git a/src/Umbraco.Core/DisposableObject.cs b/src/Umbraco.Core/DisposableObject.cs index 82c045e8f5..fc561fe3d7 100644 --- a/src/Umbraco.Core/DisposableObject.cs +++ b/src/Umbraco.Core/DisposableObject.cs @@ -36,7 +36,11 @@ namespace Umbraco.Core } private void Dispose(bool disposing) - { + { + // can happen if the object construction failed + if (_locko == null) + return; + lock (_locko) { if (Disposed) return; diff --git a/src/Umbraco.Core/DisposableTimer.cs b/src/Umbraco.Core/DisposableTimer.cs index 5b365c5ec3..f5a506a0e8 100644 --- a/src/Umbraco.Core/DisposableTimer.cs +++ b/src/Umbraco.Core/DisposableTimer.cs @@ -1,9 +1,5 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; using System.Diagnostics; -using System.Web; -using Umbraco.Core.DependencyInjection; using Umbraco.Core.Logging; namespace Umbraco.Core @@ -15,264 +11,101 @@ namespace Umbraco.Core { private readonly ILogger _logger; private readonly LogType? _logType; - private readonly IProfiler _profiler; private readonly Type _loggerType; - private readonly string _endMessage; - private readonly int _minimumMsThreshold = 0; + private readonly int _thresholdMilliseconds; private readonly IDisposable _profilerStep; - private readonly Stopwatch _stopwatch = Stopwatch.StartNew(); - private readonly Action _callback; + private readonly string _endMessage; + private string _failMessage; + private Exception _failException; + private bool _failed; - internal enum LogType + internal enum LogType { Debug, Info } - internal DisposableTimer(ILogger logger, LogType logType, IProfiler profiler, Type loggerType, string startMessage, string endMessage, int minimumMsThreshold) + // internal - created by profiling logger + internal DisposableTimer(ILogger logger, LogType logType, IProfiler profiler, Type loggerType, + string startMessage, string endMessage, string failMessage = null, + int thresholdMilliseconds = 0) { - if (logger == null) throw new ArgumentNullException("logger"); - if (loggerType == null) throw new ArgumentNullException("loggerType"); + if (logger == null) throw new ArgumentNullException(nameof(logger)); + if (loggerType == null) throw new ArgumentNullException(nameof(loggerType)); _logger = logger; _logType = logType; - _profiler = profiler; _loggerType = loggerType; _endMessage = endMessage; - _minimumMsThreshold = minimumMsThreshold; + _failMessage = failMessage; + _thresholdMilliseconds = thresholdMilliseconds < 0 ? 0 : thresholdMilliseconds; - //NOTE: We aren't logging the start message with this ctor, this is output to the profiler but not the log, - // we just want the log to contain the result if it's more than the minimum ms threshold - - if (profiler != null) + if (thresholdMilliseconds == 0) { - _profilerStep = profiler.Step(loggerType, startMessage); - } - } - - internal DisposableTimer(ILogger logger, LogType logType, IProfiler profiler, Type loggerType, string startMessage, string endMessage) - { - if (logger == null) throw new ArgumentNullException("logger"); - if (loggerType == null) throw new ArgumentNullException("loggerType"); - - _logger = logger; - _logType = logType; - _profiler = profiler; - _loggerType = loggerType; - _endMessage = endMessage; - - switch (logType) - { - case LogType.Debug: - logger.Debug(loggerType, startMessage); - break; - case LogType.Info: - logger.Info(loggerType, startMessage); - break; - default: - throw new ArgumentOutOfRangeException("logType"); - } - - if (profiler != null) - { - _profilerStep = profiler.Step(loggerType, startMessage); - } - } - - protected internal DisposableTimer(Action callback) - { - if (callback == null) throw new ArgumentNullException("callback"); - _callback = callback; - } - - public Stopwatch Stopwatch - { - get { return _stopwatch; } - } - - /// - /// Starts the timer and invokes the specified callback upon disposal. - /// - /// The callback. - /// - [Obsolete("Use either TraceDuration or DebugDuration instead of using Start")] - public static DisposableTimer Start(Action callback) - { - return new DisposableTimer(callback); - } - - #region TraceDuration - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Use the other methods that specify strings instead of Func")] - public static DisposableTimer TraceDuration(Func startMessage, Func completeMessage) - { - return TraceDuration(typeof(T), startMessage, completeMessage); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Use the other methods that specify strings instead of Func")] - public static DisposableTimer TraceDuration(Type loggerType, Func startMessage, Func completeMessage) - { - return new DisposableTimer( - Current.Logger, - LogType.Info, - Current.Profiler, - loggerType, - startMessage(), - completeMessage()); - } - - /// - /// Adds a start and end log entry as Info and tracks how long it takes until disposed. - /// - /// - /// - /// - /// - [Obsolete("Use the Umbraco.Core.Logging.ProfilingLogger to create instances of DisposableTimer")] - public static DisposableTimer TraceDuration(string startMessage, string completeMessage) - { - return TraceDuration(typeof(T), startMessage, completeMessage); - } - - /// - /// Adds a start and end log entry as Info and tracks how long it takes until disposed. - /// - /// - /// - /// - [Obsolete("Use the Umbraco.Core.Logging.ProfilingLogger to create instances of DisposableTimer")] - public static DisposableTimer TraceDuration(string startMessage) - { - return TraceDuration(typeof(T), startMessage, "Complete"); - } - - /// - /// Adds a start and end log entry as Info and tracks how long it takes until disposed. - /// - /// - /// - /// - /// - [Obsolete("Use the Umbraco.Core.Logging.ProfilingLogger to create instances of DisposableTimer")] - public static DisposableTimer TraceDuration(Type loggerType, string startMessage, string completeMessage) - { - return new DisposableTimer( - Current.Logger, - LogType.Info, - Current.Profiler, - loggerType, - startMessage, - completeMessage); - } - - #endregion - - #region DebugDuration - - /// - /// Adds a start and end log entry as Debug and tracks how long it takes until disposed. - /// - /// - /// - /// - /// - [Obsolete("Use the Umbraco.Core.Logging.ProfilingLogger to create instances of DisposableTimer")] - public static DisposableTimer DebugDuration(string startMessage, string completeMessage) - { - return DebugDuration(typeof(T), startMessage, completeMessage); - } - - /// - /// Adds a start and end log entry as Debug and tracks how long it takes until disposed. - /// - /// - /// - /// - [Obsolete("Use the Umbraco.Core.Logging.ProfilingLogger to create instances of DisposableTimer")] - public static DisposableTimer DebugDuration(string startMessage) - { - return DebugDuration(typeof(T), startMessage, "Complete"); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Use the other methods that specify strings instead of Func")] - public static DisposableTimer DebugDuration(Func startMessage, Func completeMessage) - { - return DebugDuration(typeof(T), startMessage, completeMessage); - } - - /// - /// Adds a start and end log entry as Debug and tracks how long it takes until disposed. - /// - /// - /// - /// - /// - [Obsolete("Use the Umbraco.Core.Logging.ProfilingLogger to create instances of DisposableTimer")] - public static DisposableTimer DebugDuration(Type loggerType, string startMessage, string completeMessage) - { - return new DisposableTimer( - Current.Logger, - LogType.Debug, - Current.Profiler, - loggerType, - startMessage, - completeMessage); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Use the other methods that specify strings instead of Func")] - public static DisposableTimer DebugDuration(Type loggerType, Func startMessage, Func completeMessage) - { - return new DisposableTimer( - Current.Logger, - LogType.Debug, - Current.Profiler, - loggerType, - startMessage(), - completeMessage()); - } - #endregion - - /// - /// Handles the disposal of resources. Derived from abstract class which handles common required locking logic. - /// - protected override void DisposeResources() - { - Stopwatch.Stop(); - - if (_profiler != null) - { - _profiler.DisposeIfDisposable(); - } - - if (_profilerStep != null) - { - _profilerStep.Dispose(); - } - - if (Stopwatch.ElapsedMilliseconds >= _minimumMsThreshold && _logType.HasValue && _endMessage.IsNullOrWhiteSpace() == false && _loggerType != null && _logger != null) - { - switch (_logType) + switch (logType) { case LogType.Debug: - _logger.Debug(_loggerType, () => _endMessage + " (took " + Stopwatch.ElapsedMilliseconds + "ms)"); + logger.Debug(loggerType, startMessage); break; case LogType.Info: - _logger.Info(_loggerType, () => _endMessage + " (took " + Stopwatch.ElapsedMilliseconds + "ms)"); + logger.Info(loggerType, startMessage); break; default: - throw new ArgumentOutOfRangeException("logType"); + throw new ArgumentOutOfRangeException(nameof(logType)); } } - if (_callback != null) - { - _callback.Invoke(Stopwatch.ElapsedMilliseconds); - } - - } + // else aren't logging the start message, this is output to the profiler but not the log, + // we just want the log to contain the result if it's more than the minimum ms threshold. + _profilerStep = profiler?.Step(loggerType, startMessage); + } + + /// + /// Reports a failure. + /// + /// The fail message. + /// The exception. + /// Completion of the timer will be reported as an error, with the specified message and exception. + public void Fail(string failMessage = null, Exception exception = null) + { + _failed = true; + _failMessage = failMessage ?? _failMessage ?? "Failed."; + _failException = exception; + } + + public Stopwatch Stopwatch { get; } = Stopwatch.StartNew(); + + /// + ///Disposes resources. + /// + /// Overrides abstract class which handles required locking. + protected override void DisposeResources() + { + Stopwatch.Stop(); + + _profilerStep?.Dispose(); + + if ((Stopwatch.ElapsedMilliseconds >= _thresholdMilliseconds || _failed) + && _logType.HasValue && _loggerType != null && _logger != null + && (_endMessage.IsNullOrWhiteSpace() == false || _failed)) + { + if (_failed) + { + _logger.Error(_loggerType, $"{_failMessage} ({Stopwatch.ElapsedMilliseconds}ms)", _failException); + } + else switch (_logType) + { + case LogType.Debug: + _logger.Debug(_loggerType, () => $"{_endMessage} ({Stopwatch.ElapsedMilliseconds}ms)"); + break; + case LogType.Info: + _logger.Info(_loggerType, () => $"{_endMessage} ({Stopwatch.ElapsedMilliseconds}ms)"); + break; + // filtered in the ctor + //default: + // throw new Exception(); + } + } + } } } \ No newline at end of file diff --git a/src/Umbraco.Core/Exceptions/BootFailedException.cs b/src/Umbraco.Core/Exceptions/BootFailedException.cs index b2836f22ed..3e13c83af4 100644 --- a/src/Umbraco.Core/Exceptions/BootFailedException.cs +++ b/src/Umbraco.Core/Exceptions/BootFailedException.cs @@ -14,5 +14,15 @@ namespace Umbraco.Core.Exceptions public BootFailedException(string message) : base(message) { } + + /// + /// Initializes a new instance of the class with a specified error message + /// and a reference to the inner exception which is the cause of this exception. + /// + /// The message that describes the error. + /// The inner exception, or null. + public BootFailedException(string message, Exception inner) + : base(message, inner) + { } } } \ No newline at end of file diff --git a/src/Umbraco.Core/IO/PhysicalFileSystem.cs b/src/Umbraco.Core/IO/PhysicalFileSystem.cs index 47daff932d..1e02c93b24 100644 --- a/src/Umbraco.Core/IO/PhysicalFileSystem.cs +++ b/src/Umbraco.Core/IO/PhysicalFileSystem.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.Logging; namespace Umbraco.Core.IO @@ -70,11 +71,11 @@ namespace Umbraco.Core.IO } catch (UnauthorizedAccessException ex) { - LogHelper.Error("Not authorized to get directories", ex); + Current.Logger.Error("Not authorized to get directories", ex); } catch (DirectoryNotFoundException ex) { - LogHelper.Error("Directory not found", ex); + Current.Logger.Error("Directory not found", ex); } return Enumerable.Empty(); @@ -97,7 +98,7 @@ namespace Umbraco.Core.IO } catch (DirectoryNotFoundException ex) { - LogHelper.Error("Directory not found", ex); + Current.Logger.Error("Directory not found", ex); } } @@ -144,11 +145,11 @@ namespace Umbraco.Core.IO } catch (UnauthorizedAccessException ex) { - LogHelper.Error("Not authorized to get directories", ex); + Current.Logger.Error("Not authorized to get directories", ex); } catch (DirectoryNotFoundException ex) { - LogHelper.Error("Directory not found", ex); + Current.Logger.Error("Directory not found", ex); } return Enumerable.Empty(); @@ -172,7 +173,7 @@ namespace Umbraco.Core.IO } catch (FileNotFoundException ex) { - LogHelper.Info(string.Format("DeleteFile failed with FileNotFoundException: {0}", ex.InnerException)); + Current.Logger.Info(string.Format("DeleteFile failed with FileNotFoundException: {0}", ex.InnerException)); } } diff --git a/src/Umbraco.Core/IO/UmbracoMediaFile.cs b/src/Umbraco.Core/IO/UmbracoMediaFile.cs index d708fcb804..d427b76010 100644 --- a/src/Umbraco.Core/IO/UmbracoMediaFile.cs +++ b/src/Umbraco.Core/IO/UmbracoMediaFile.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Threading.Tasks; using System.Web; using Umbraco.Core.Configuration; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.Logging; using Umbraco.Core.Media; @@ -93,7 +94,7 @@ namespace Umbraco.Core.IO Exists = _fs.FileExists(Path); if (Exists == false) { - LogHelper.Warn("The media file doesn't exist: " + Path); + Current.Logger.Warn("The media file doesn't exist: " + Path); } } diff --git a/src/Umbraco.Core/Logging/DebugDiagnosticsLogger.cs b/src/Umbraco.Core/Logging/DebugDiagnosticsLogger.cs index c1b3306129..8f6a07e75e 100644 --- a/src/Umbraco.Core/Logging/DebugDiagnosticsLogger.cs +++ b/src/Umbraco.Core/Logging/DebugDiagnosticsLogger.cs @@ -3,41 +3,111 @@ using System.Linq; namespace Umbraco.Core.Logging { + /// + /// Implements on top of . + /// internal class DebugDiagnosticsLogger : ILogger { - public void Error(Type callingType, string message, Exception exception) + /// + public void Error(Type reporting, string message, Exception exception = null) { - System.Diagnostics.Debug.WriteLine(message + Environment.NewLine + exception, callingType.ToString()); + System.Diagnostics.Debug.WriteLine(message + Environment.NewLine + exception, reporting.FullName); } - public void Warn(Type callingType, string message, params Func[] formatItems) + /// + public void Warn(Type reporting, string message) { - System.Diagnostics.Debug.WriteLine(string.Format(message, formatItems.Select(x => x()).ToArray()), callingType.ToString()); + System.Diagnostics.Debug.WriteLine(message, reporting.FullName); } - public void WarnWithException(Type callingType, string message, Exception e, params Func[] formatItems) + /// + public void Warn(Type reporting, Func messageBuilder) { - System.Diagnostics.Debug.WriteLine(string.Format(message + Environment.NewLine + e, formatItems.Select(x => x()).ToArray()), callingType.ToString()); + System.Diagnostics.Debug.WriteLine(messageBuilder(), reporting.FullName); } - public void Info(Type callingType, Func generateMessage) + /// + public void Warn(Type reporting, string format, params object[] args) { - System.Diagnostics.Debug.WriteLine(generateMessage(), callingType.ToString()); + System.Diagnostics.Debug.WriteLine(string.Format(format, args), reporting.FullName); } - public void Info(Type type, string generateMessageFormat, params Func[] formatItems) + /// + public void Warn(Type reporting, string format, params Func[] args) { - System.Diagnostics.Debug.WriteLine(string.Format(generateMessageFormat, formatItems.Select(x => x()).ToArray()), type.ToString()); + System.Diagnostics.Debug.WriteLine(string.Format(format, args.Select(x => x()).ToArray()), reporting.FullName); } - public void Debug(Type callingType, Func generateMessage) + /// + public void Warn(Type reporting, Exception exception, string message) { - System.Diagnostics.Debug.WriteLine(generateMessage(), callingType.ToString()); + System.Diagnostics.Debug.WriteLine(message + Environment.NewLine + exception, reporting.FullName); } - public void Debug(Type type, string generateMessageFormat, params Func[] formatItems) + /// + public void Warn(Type reporting, Exception exception, Func messageBuilder) { - System.Diagnostics.Debug.WriteLine(string.Format(generateMessageFormat, formatItems.Select(x => x()).ToArray()), type.ToString()); + System.Diagnostics.Debug.WriteLine(messageBuilder() + Environment.NewLine + exception, reporting.FullName); + } + + /// + public void Warn(Type reporting, Exception exception, string format, params object[] args) + { + System.Diagnostics.Debug.WriteLine(string.Format(format + Environment.NewLine + exception, args), reporting.FullName); + } + + /// + public void Warn(Type reporting, Exception exception, string format, params Func[] args) + { + System.Diagnostics.Debug.WriteLine(string.Format(format + Environment.NewLine + exception, args.Select(x => x()).ToArray()), reporting.FullName); + } + + /// + public void Info(Type reporting, string message) + { + System.Diagnostics.Debug.WriteLine(message, reporting.FullName); + } + + /// + public void Info(Type reporting, Func messageBuilder) + { + System.Diagnostics.Debug.WriteLine(messageBuilder(), reporting.FullName); + } + + /// + public void Info(Type reporting, string format, params object[] args) + { + System.Diagnostics.Debug.WriteLine(string.Format(format, args), reporting.FullName); + } + + /// + public void Info(Type reporting, string format, params Func[] args) + { + System.Diagnostics.Debug.WriteLine(string.Format(format, args.Select(x => x()).ToArray()), reporting.FullName); + } + + /// + public void Debug(Type reporting, string message) + { + System.Diagnostics.Debug.WriteLine(message, reporting.FullName); + } + + /// + public void Debug(Type reporting, Func messageBuilder) + { + System.Diagnostics.Debug.WriteLine(messageBuilder(), reporting.FullName); + } + + /// + public void Debug(Type reporting, string format, params object[] args) + { + System.Diagnostics.Debug.WriteLine(string.Format(format, args), reporting.FullName); + } + + /// + public void Debug(Type reporting, string format, params Func[] args) + { + System.Diagnostics.Debug.WriteLine(string.Format(format, args.Select(x => x()).ToArray()), reporting.FullName); } } } \ No newline at end of file diff --git a/src/Umbraco.Core/Logging/ILogger.cs b/src/Umbraco.Core/Logging/ILogger.cs index 3fb6bfc476..2eec5dbd14 100644 --- a/src/Umbraco.Core/Logging/ILogger.cs +++ b/src/Umbraco.Core/Logging/ILogger.cs @@ -3,22 +3,142 @@ using System; namespace Umbraco.Core.Logging { /// - /// Interface for logging service. + /// Defines the logging service. /// public interface ILogger { - void Error(Type callingType, string message, Exception exception); + /// + /// Logs an error message. + /// + /// The reporting type. + /// A message. + /// An exception. + void Error(Type reporting, string message, Exception exception = null); - void Warn(Type callingType, string message, params Func[] formatItems); - - void WarnWithException(Type callingType, string message, Exception e, params Func[] formatItems); + // note: should we have more overloads for Error too? - void Info(Type callingType, Func generateMessage); + /// + /// Logs a warning message. + /// + /// The reporting type. + /// A message. + void Warn(Type reporting, string message); - void Info(Type type, string generateMessageFormat, params Func[] formatItems); + /// + /// Logs a warning message. + /// + /// The reporting type. + /// A message builder. + void Warn(Type reporting, Func messageBuilder); - void Debug(Type callingType, Func generateMessage); + /// + /// Logs a formatted warning message. + /// + /// The reporting type. + /// A composite format string. + /// An array of objects to format. + void Warn(Type reporting, string format, params object[] args); - void Debug(Type type, string generateMessageFormat, params Func[] formatItems); + /// + /// Logs a formatted warning message. + /// + /// The reporting type. + /// A composite format string. + /// An array of functions returning objects to format. + void Warn(Type reporting, string format, params Func[] args); + + /// + /// Logs a warning message with an exception. + /// + /// The reporting type. + /// An exception. + /// A message. + void Warn(Type reporting, Exception exception, string message); + + /// + /// Logs a warning message with an exception. + /// + /// The reporting type. + /// An exception. + /// A message builder. + void Warn(Type reporting, Exception exception, Func messageBuilder); + + /// + /// Logs a formatted warning message with an exception. + /// + /// The reporting type. + /// An exception. + /// A composite format string. + /// An array of objects to format. + void Warn(Type reporting, Exception exception, string format, params object[] args); + + /// + /// Logs a formatted warning message with an exception. + /// + /// The reporting type. + /// An exception. + /// A composite format string. + /// An array of functions returning objects to format. + void Warn(Type reporting, Exception exception, string format, params Func[] args); + + /// + /// Logs an information message. + /// + /// The reporting type. + /// A message. + void Info(Type reporting, string message); + + /// + /// Logs an information message. + /// + /// The reporting type. + /// A message builder. + void Info(Type reporting, Func messageBuilder); + + /// + /// Logs a formatted information message. + /// + /// The reporting type. + /// A composite format string. + /// An array of objects to format. + void Info(Type reporting, string format, params object[] args); + + /// + /// Logs a formatted information message. + /// + /// The reporting type. + /// A composite format string. + /// An array of functions returning objects to format. + void Info(Type reporting, string format, params Func[] args); + + /// + /// Logs a debugging message. + /// + /// The reporting type. + /// A message. + void Debug(Type reporting, string message); + + /// + /// Logs a debugging message. + /// + /// The reporting type. + /// A message builder. + void Debug(Type reporting, Func messageBuilder); + + /// + /// Logs a formatted debugging message. + /// + /// The reporting type. + /// A composite format string. + /// An array of objects to format. + void Debug(Type reporting, string format, params object[] args); + + /// + /// Logs a formatted debugging message. + /// + /// The reporting type. + /// A composite format string. + /// An array of functions returning objects to format. + void Debug(Type reporting, string format, params Func[] args); } } \ No newline at end of file diff --git a/src/Umbraco.Core/Logging/IProfiler.cs b/src/Umbraco.Core/Logging/IProfiler.cs index 94ba9a6af6..8768889799 100644 --- a/src/Umbraco.Core/Logging/IProfiler.cs +++ b/src/Umbraco.Core/Logging/IProfiler.cs @@ -3,41 +3,36 @@ namespace Umbraco.Core.Logging { /// - /// Defines an object for use in the application to profile operations + /// Defines the profiling service. /// public interface IProfiler { /// - /// Render the UI to display the profiler + /// Renders the profiling results. /// - /// - /// - /// Generally used for HTML displays - /// + /// The profiling results. + /// Generally used for Html rendering. string Render(); /// - /// Profile an operation + /// Gets an that will time the code between its creation and disposal. /// - /// - /// - /// - /// Use the 'using(' syntax - /// + /// The name of the step. + /// A step. + /// The returned is meant to be used within a using (...) {{ ... }} block. IDisposable Step(string name); /// - /// Start the profiler + /// Starts the profiler. /// void Start(); /// - /// Start the profiler + /// Stops the profiler. /// - /// - /// set discardResults to false when you want to abandon all profiling, this is useful for - /// when someone is not authenticated or you want to clear the results based on some other mechanism. - /// + /// A value indicating whether to discard results. + /// Set discardResult to true to abandon all profiling - useful when eg someone is not + /// authenticated or you want to clear the results, based upon some other mechanism. void Stop(bool discardResults = false); } } \ No newline at end of file diff --git a/src/Umbraco.Core/Logging/ImageProcessorLogger.cs b/src/Umbraco.Core/Logging/ImageProcessorLogger.cs index 5bcf119b0d..52d9b21f60 100644 --- a/src/Umbraco.Core/Logging/ImageProcessorLogger.cs +++ b/src/Umbraco.Core/Logging/ImageProcessorLogger.cs @@ -1,4 +1,6 @@ -namespace Umbraco.Core.Logging +using Umbraco.Core.DependencyInjection; + +namespace Umbraco.Core.Logging { using System; using System.Runtime.CompilerServices; @@ -26,7 +28,7 @@ { // Using LogHelper since the ImageProcessor logger expects a parameterless constructor. var message = $"{callerName} {lineNumber} : {text}"; - LogHelper.Error(string.Empty, new ImageProcessingException(message)); + Current.Logger.Error(string.Empty, new ImageProcessingException(message)); } /// @@ -40,7 +42,7 @@ { // Using LogHelper since the ImageProcessor logger expects a parameterless constructor. var message = $"{callerName} {lineNumber} : {text}"; - LogHelper.Error(type, string.Empty, new ImageProcessingException(message)); + Current.Logger.Error(type, string.Empty, new ImageProcessingException(message)); } } } diff --git a/src/Umbraco.Core/Logging/LogHelper.cs b/src/Umbraco.Core/Logging/LogHelper.cs deleted file mode 100644 index e45beca6b4..0000000000 --- a/src/Umbraco.Core/Logging/LogHelper.cs +++ /dev/null @@ -1,227 +0,0 @@ -using System; -using System.Linq; -using System.Threading; -using System.Web; -using log4net; -using Umbraco.Core.DependencyInjection; - -namespace Umbraco.Core.Logging -{ - /// - /// Used for logging, ILogger should be used instead but this is available for static access to logging - /// - /// - /// this wraps ILogger - /// - public static class LogHelper - { - #region Error - /// - /// Adds an error log - /// - /// - /// - /// - public static void Error(string message, Exception exception) - { - Current.Logger.Error(message, exception); - } - - public static void Error(Type callingType, string message, Exception exception) - { - Current.Logger.Error(callingType, message, exception); - } - - #endregion - - #region Warn - - public static void Warn(Type callingType, string message, params Func[] formatItems) - { - Current.Logger.Warn(callingType, message, formatItems); - } - - [Obsolete("Warnings with http trace should not be used. This method will be removed in future versions")] - public static void Warn(Type callingType, string message, bool showHttpTrace, params Func[] formatItems) - { - Mandate.ParameterNotNull(callingType, "callingType"); - Mandate.ParameterNotNullOrEmpty(message, "message"); - - if (showHttpTrace && HttpContext.Current != null) - { - HttpContext.Current.Trace.Warn(callingType.Name, string.Format(message, formatItems.Select(x => x.Invoke()).ToArray())); - } - - Current.Logger.Warn(callingType, message, formatItems); - - } - - public static void WarnWithException(Type callingType, string message, Exception e, params Func[] formatItems) - { - WarnWithException(callingType, message, false, e, formatItems); - } - - [Obsolete("Warnings with http trace should not be used. This method will be removed in future versions")] - public static void WarnWithException(Type callingType, string message, bool showHttpTrace, Exception e, params Func[] formatItems) - { - Mandate.ParameterNotNull(e, "e"); - Mandate.ParameterNotNull(callingType, "callingType"); - Mandate.ParameterNotNullOrEmpty(message, "message"); - - if (showHttpTrace && HttpContext.Current != null) - { - HttpContext.Current.Trace.Warn( - callingType.Name, - string.Format(message, formatItems.Select(x => x.Invoke()).ToArray()), - e); - } - - Current.Logger.WarnWithException(callingType, message, e, formatItems); - } - - /// - /// Adds a warn log - /// - /// - /// - /// - public static void Warn(string message, params Func[] formatItems) - { - Warn(typeof(T), message, formatItems); - } - - [Obsolete("Warnings with http trace should not be used. This method will be removed in future versions")] - public static void Warn(string message, bool showHttpTrace, params Func[] formatItems) - { - Warn(typeof(T), message, showHttpTrace, formatItems); - } - - public static void WarnWithException(string message, Exception e, params Func[] formatItems) - { - WarnWithException(typeof(T), message, e, formatItems); - } - - [Obsolete("Warnings with http trace should not be used. This method will be removed in future versions")] - public static void WarnWithException(string message, bool showHttpTrace, Exception e, params Func[] formatItems) - { - WarnWithException(typeof(T), message, showHttpTrace, e, formatItems); - } - - #endregion - - #region Info - /// - /// Traces a message, only generating the message if tracing is actually enabled. Use this method to avoid calling any long-running methods such as "ToDebugString" if logging is disabled. - /// - /// - /// The delegate to generate a message. - /// - public static void Info(Func generateMessage) - { - Info(typeof(T), generateMessage); - } - - /// - /// Traces if tracing is enabled. - /// - /// - /// - public static void Info(Type callingType, Func generateMessage) - { - Current.Logger.Info(callingType, generateMessage); - } - - /// - /// Traces if tracing is enabled. - /// - /// The type for the logging namespace. - /// The message format. - /// The format items. - public static void Info(Type type, string generateMessageFormat, params Func[] formatItems) - { - Current.Logger.Info(type, generateMessageFormat, formatItems); - } - - /// - /// Traces a message, only generating the message if tracing is actually enabled. Use this method to avoid calling any long-running methods such as "ToDebugString" if logging is disabled. - /// - /// - /// The generate message format. - /// The format items. - /// - public static void Info(string generateMessageFormat, params Func[] formatItems) - { - Info(typeof(T), generateMessageFormat, formatItems); - } - - #endregion - - #region Debug - - /// - /// Debugs a message, only generating the message if tracing is actually enabled. Use this method to avoid calling any long-running methods such as "ToDebugString" if logging is disabled. - /// - /// - /// The delegate to generate a message. - /// - public static void Debug(Func generateMessage) - { - Debug(typeof(T), generateMessage); - } - - /// - /// Debugs if tracing is enabled. - /// - /// - /// - public static void Debug(Type callingType, Func generateMessage) - { - Current.Logger.Debug(callingType, generateMessage); - } - - /// - /// Debugs if tracing is enabled. - /// - /// The type for the logging namespace. - /// The message format. - /// The format items. - public static void Debug(Type type, string generateMessageFormat, params Func[] formatItems) - { - Current.Logger.Debug(type, generateMessageFormat, formatItems); - } - - /// - /// Debugs a message, only generating the message if debug is actually enabled. Use this method to avoid calling any long-running methods such as "ToDebugString" if logging is disabled. - /// - /// - /// The generate message format. - /// The format items. - /// - public static void Debug(string generateMessageFormat, params Func[] formatItems) - { - Debug(typeof(T), generateMessageFormat, formatItems); - } - - /// - /// Debugs a message and also writes to the TraceContext specified, useful for when you would like the debug - /// output also displayed in the Http trace output. - /// - /// - /// - /// - /// - [Obsolete("Warnings with http trace should not be used. This method will be removed in future versions")] - public static void Debug(string generateMessageFormat, bool showHttpTrace, params Func[] formatItems) - { - if (showHttpTrace && HttpContext.Current != null) - { - HttpContext.Current.Trace.Write( - typeof(T).Name, - string.Format(generateMessageFormat, formatItems.Select(x => x()).ToArray())); - } - Debug(typeof(T), generateMessageFormat, formatItems); - } - - #endregion - } -} diff --git a/src/Umbraco.Core/Logging/LogProfiler.cs b/src/Umbraco.Core/Logging/LogProfiler.cs index 1f3b0f44f5..72e1e891a0 100644 --- a/src/Umbraco.Core/Logging/LogProfiler.cs +++ b/src/Umbraco.Core/Logging/LogProfiler.cs @@ -1,9 +1,10 @@ using System; +using System.Diagnostics; namespace Umbraco.Core.Logging { /// - /// A profiler that outputs its results to an ILogger + /// Implements by writing profiling results to an . /// internal class LogProfiler : IProfiler { @@ -14,25 +15,48 @@ namespace Umbraco.Core.Logging _logger = logger; } + /// public string Render() { return string.Empty; } + /// public IDisposable Step(string name) { - _logger.Debug(typeof(LogProfiler), "Starting - " + name); - return new DisposableTimer(l => _logger.Info(typeof(LogProfiler), () => name + " (took " + l + "ms)")); + _logger.Debug($"Begin: {name}."); + return new LightDisposableTimer(duration => _logger.Info($"End {name}. ({duration}ms)")); } + /// public void Start() { - //the log will alwasy be started + // the log will always be started } + /// public void Stop(bool discardResults = false) { - //we don't need to do anything here + // the log never stops + } + + // a lightweight disposable timer + private class LightDisposableTimer : DisposableObject + { + private readonly Action _callback; + private readonly Stopwatch _stopwatch = Stopwatch.StartNew(); + + protected internal LightDisposableTimer(Action callback) + { + if (callback == null) throw new ArgumentNullException(nameof(callback)); + _callback = callback; + } + + protected override void DisposeResources() + { + _stopwatch.Stop(); + _callback(_stopwatch.ElapsedMilliseconds); + } } } } diff --git a/src/Umbraco.Core/Logging/Logger.cs b/src/Umbraco.Core/Logging/Logger.cs index a6ed064c01..c545de5986 100644 --- a/src/Umbraco.Core/Logging/Logger.cs +++ b/src/Umbraco.Core/Logging/Logger.cs @@ -1,138 +1,185 @@ using System; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; -using System.Threading; -using System.Web; using log4net; using log4net.Config; +using log4net.Util; namespace Umbraco.Core.Logging { /// - /// Used for logging + /// Implements on top of log4net. /// public class Logger : ILogger { - + /// + /// Initialize a new instance of the class with a log4net configuration file. + /// + /// public Logger(FileInfo log4NetConfigFile) - :this() + : this() { XmlConfigurator.Configure(log4NetConfigFile); } + // private for CreateWithDefaultLog4NetConfiguration private Logger() { - //Add custom global properties to the log4net context that we can use in our logging output - - log4net.GlobalContext.Properties["processId"] = Process.GetCurrentProcess().Id; - log4net.GlobalContext.Properties["appDomainId"] = AppDomain.CurrentDomain.Id; + // add custom global properties to the log4net context that we can use in our logging output + GlobalContext.Properties["processId"] = Process.GetCurrentProcess().Id; + GlobalContext.Properties["appDomainId"] = AppDomain.CurrentDomain.Id; } /// - /// Creates a logger with the default log4net configuration discovered (i.e. from the web.config) + /// Creates a logger with the default log4net configuration discovered (i.e. from the web.config). /// - /// + /// Used by UmbracoApplicationBase to get its logger. public static Logger CreateWithDefaultLog4NetConfiguration() { return new Logger(); } - public void Error(Type callingType, string message, Exception exception) + /// + public void Error(Type reporting, string message, Exception exception = null) { - var logger = LogManager.GetLogger(callingType); - if (logger != null) - logger.Error((message), exception); + var logger = LogManager.GetLogger(reporting); + logger?.Error(message, exception); } - public void Warn(Type callingType, string message, params Func[] formatItems) - { - var logger = LogManager.GetLogger(callingType); - if (logger == null || logger.IsWarnEnabled == false) return; - logger.WarnFormat((message), formatItems.Select(x => x.Invoke()).ToArray()); - } - - public void Warn(Type callingType, string message, bool showHttpTrace, params Func[] formatItems) - { - Mandate.ParameterNotNull(callingType, "callingType"); - Mandate.ParameterNotNullOrEmpty(message, "message"); - - if (showHttpTrace && HttpContext.Current != null) - { - HttpContext.Current.Trace.Warn(callingType.Name, string.Format(message, formatItems.Select(x => x.Invoke()).ToArray())); - } - - var logger = LogManager.GetLogger(callingType); - if (logger == null || logger.IsWarnEnabled == false) return; - logger.WarnFormat((message), formatItems.Select(x => x.Invoke()).ToArray()); - - } - - public void WarnWithException(Type callingType, string message, Exception e, params Func[] formatItems) - { - Mandate.ParameterNotNull(e, "e"); - Mandate.ParameterNotNull(callingType, "callingType"); - Mandate.ParameterNotNullOrEmpty(message, "message"); - - var logger = LogManager.GetLogger(callingType); + /// + public void Warn(Type reporting, string message) + { + var logger = LogManager.GetLogger(reporting); if (logger == null || logger.IsWarnEnabled == false) return; - var executedParams = formatItems.Select(x => x.Invoke()).ToArray(); - logger.WarnFormat((message) + ". Exception: " + e, executedParams); + logger.Warn(message); + } + + /// + public void Warn(Type reporting, Func messageBuilder) + { + var logger = LogManager.GetLogger(reporting); + if (logger == null || logger.IsWarnEnabled == false) return; + logger.Warn(messageBuilder()); + } + + /// + public void Warn(Type reporting, string format, params object[] args) + { + var logger = LogManager.GetLogger(reporting); + if (logger == null || logger.IsWarnEnabled == false) return; + logger.WarnFormat(format, args); + } + + /// + public void Warn(Type reporting, string format, params Func[] args) + { + var logger = LogManager.GetLogger(reporting); + if (logger == null || logger.IsWarnEnabled == false) return; + logger.WarnFormat(format, args.Select(x => x.Invoke()).ToArray()); } - /// - /// Traces if tracing is enabled. - /// - /// - /// - public void Info(Type callingType, Func generateMessage) + /// + public void Warn(Type reporting, Exception exception, string message) + { + var logger = LogManager.GetLogger(reporting); + if (logger == null || logger.IsWarnEnabled == false) return; + logger.Warn(message, exception); + } + + /// + public void Warn(Type reporting, Exception exception, Func messageBuilder) + { + var logger = LogManager.GetLogger(reporting); + if (logger == null || logger.IsWarnEnabled == false) return; + logger.Warn(messageBuilder(), exception); + } + + /// + public void Warn(Type reporting, Exception exception, string format, params object[] args) + { + var logger = LogManager.GetLogger(reporting); + if (logger == null || logger.IsWarnEnabled == false) return; + // there is no WarnFormat overload that accepts an exception + // format the message the way log4net would do it (see source code LogImpl.cs) + var message = new SystemStringFormat(CultureInfo.InvariantCulture, format, args); + logger.Warn(message, exception); + } + + /// + public void Warn(Type reporting, Exception exception, string format, params Func[] args) + { + var logger = LogManager.GetLogger(reporting); + if (logger == null || logger.IsWarnEnabled == false) return; + // there is no WarnFormat overload that accepts an exception + // format the message the way log4net would do it (see source code LogImpl.cs) + var message = new SystemStringFormat(CultureInfo.InvariantCulture, format, args.Select(x => x.Invoke()).ToArray()); + logger.Warn(message, exception); + } + + /// + public void Info(Type reporting, string message) + { + var logger = LogManager.GetLogger(reporting); + if (logger == null || logger.IsInfoEnabled == false) return; + logger.Info(message); + } + + /// + public void Info(Type reporting, Func generateMessage) { - var logger = LogManager.GetLogger(callingType); + var logger = LogManager.GetLogger(reporting); if (logger == null || logger.IsInfoEnabled == false) return; - logger.Info((generateMessage.Invoke())); + logger.Info(generateMessage()); } - /// - /// Traces if tracing is enabled. - /// - /// The type for the logging namespace. - /// The message format. - /// The format items. - public void Info(Type type, string generateMessageFormat, params Func[] formatItems) + /// + public void Info(Type reporting, string format, params object[] args) + { + var logger = LogManager.GetLogger(reporting); + if (logger == null || logger.IsInfoEnabled == false) return; + logger.InfoFormat(format, args); + } + + /// + public void Info(Type reporting, string format, params Func[] args) { - var logger = LogManager.GetLogger(type); + var logger = LogManager.GetLogger(reporting); if (logger == null || logger.IsInfoEnabled == false) return; - var executedParams = formatItems.Select(x => x.Invoke()).ToArray(); - logger.InfoFormat((generateMessageFormat), executedParams); + logger.InfoFormat(format, args.Select(x => x.Invoke()).ToArray()); } + /// + public void Debug(Type reporting, string message) + { + var logger = LogManager.GetLogger(reporting); + if (logger == null || logger.IsDebugEnabled == false) return; + logger.Debug(message); + } - /// - /// Debugs if tracing is enabled. - /// - /// - /// - public void Debug(Type callingType, Func generateMessage) + /// + public void Debug(Type reporting, Func messageBuilder) { - var logger = LogManager.GetLogger(callingType); + var logger = LogManager.GetLogger(reporting); if (logger == null || logger.IsDebugEnabled == false) return; - logger.Debug((generateMessage.Invoke())); + logger.Debug(messageBuilder()); } - /// - /// Debugs if tracing is enabled. - /// - /// The type for the logging namespace. - /// The message format. - /// The format items. - public void Debug(Type type, string generateMessageFormat, params Func[] formatItems) + /// + public void Debug(Type reporting, string format, params object[] args) + { + var logger = LogManager.GetLogger(reporting); + if (logger == null || logger.IsDebugEnabled == false) return; + logger.DebugFormat(format, args); + } + + /// + public void Debug(Type reporting, string format, params Func[] args) { - var logger = LogManager.GetLogger(type); + var logger = LogManager.GetLogger(reporting); if (logger == null || logger.IsDebugEnabled == false) return; - var executedParams = formatItems.Select(x => x.Invoke()).ToArray(); - logger.DebugFormat((generateMessageFormat), executedParams); + logger.DebugFormat(format, args.Select(x => x.Invoke()).ToArray()); } - - } } diff --git a/src/Umbraco.Core/Logging/LoggerExtensions.cs b/src/Umbraco.Core/Logging/LoggerExtensions.cs index 58bdc1da0b..4e47afa4a1 100644 --- a/src/Umbraco.Core/Logging/LoggerExtensions.cs +++ b/src/Umbraco.Core/Logging/LoggerExtensions.cs @@ -3,88 +3,208 @@ using System; namespace Umbraco.Core.Logging { /// - /// Allows for strongly typed log sources + /// Provides extension methods for the interface. /// public static class LoggerExtensions { /// - /// Adds an error log + /// Logs an error message. /// - /// - /// - /// - /// - public static void Error(this ILogger logger, string message, Exception exception) + /// The reporting type. + /// The logger. + /// A message. + /// An exception. + public static void Error(this ILogger logger, string message, Exception exception = null) { logger.Error(typeof(T), message, exception); } /// - /// Adds a warn log + /// Logs a warning message. /// - /// - /// - /// - /// - public static void Warn(this ILogger logger, string message, params Func[] formatItems) + /// The reporting type. + /// The logger. + /// A message. + public static void Warn(this ILogger logger, string message) { - logger.Warn(typeof(T), message, formatItems); - } - - public static void WarnWithException(this ILogger logger, string message, Exception e, params Func[] formatItems) - { - logger.WarnWithException(typeof(T), message, e, formatItems); - } - - - /// - /// Traces a message, only generating the message if tracing is actually enabled. Use this method to avoid calling any long-running methods such as "ToDebugString" if logging is disabled. - /// - /// - /// - /// The generate message format. - /// The format items. - /// - public static void Info(this ILogger logger, string generateMessageFormat, params Func[] formatItems) - { - logger.Info(typeof(T), generateMessageFormat, formatItems); + logger.Warn(typeof(T), message); } /// - /// Traces a message, only generating the message if tracing is actually enabled. Use this method to avoid calling any long-running methods such as "ToDebugString" if logging is disabled. + /// Logs a warning message. /// - /// - /// - /// The delegate to generate a message. - /// - public static void Info(this ILogger logger, Func generateMessage) + /// The reporting type. + /// The logger. + /// A message builder. + public static void Warn(this ILogger logger, Func messageBuilder) { - logger.Info(typeof(T), generateMessage); + logger.Warn(typeof(T), messageBuilder); } /// - /// Debugs a message, only generating the message if tracing is actually enabled. Use this method to avoid calling any long-running methods such as "ToDebugString" if logging is disabled. + /// Logs a formatted warning message. /// - /// - /// - /// The delegate to generate a message. - /// - public static void Debug(this ILogger logger, Func generateMessage) + /// The reporting type. + /// The logger. + /// A composite format string. + /// An array of objects to format. + public static void Warn(this ILogger logger, string format, params object[] args) { - logger.Debug(typeof(T), generateMessage); + logger.Warn(typeof(T), format, args); } /// - /// Debugs a message, only generating the message if debug is actually enabled. Use this method to avoid calling any long-running methods such as "ToDebugString" if logging is disabled. + /// Logs a formatted warning message. /// - /// - /// - /// The generate message format. - /// The format items. - /// - public static void Debug(this ILogger logger, string generateMessageFormat, params Func[] formatItems) + /// The reporting type. + /// The logger. + /// A composite format string. + /// An array of functions returning objects to format. + public static void Warn(this ILogger logger, string format, params Func[] args) { - logger.Debug(typeof(T), generateMessageFormat, formatItems); + logger.Warn(typeof(T), format, args); + } + + /// + /// Logs a formatted warning message with an exception. + /// + /// The reporting type. + /// The logger. + /// An exception. + /// A message builder. + public static void Warn(this ILogger logger, Exception exception, Func messageBuilder) + { + logger.Warn(typeof(T), exception, messageBuilder); + } + + /// + /// Logs a formatted warning message with an exception. + /// + /// The reporting type. + /// The logger. + /// An exception. + /// A message. + public static void Warn(this ILogger logger, Exception exception, string message) + { + logger.Warn(typeof(T), exception, message); + } + + /// + /// Logs a formatted warning message with an exception. + /// + /// The reporting type. + /// The logger. + /// An exception. + /// A composite format string. + /// An array of objects to format. + public static void Warn(this ILogger logger, Exception exception, string format, params object[] args) + { + logger.Warn(typeof(T), exception, format, args); + } + + /// + /// Logs a formatted warning message with an exception. + /// + /// The reporting type. + /// The logger. + /// An exception. + /// A composite format string. + /// An array of functions returning objects to format. + public static void Warn(this ILogger logger, Exception exception, string format, params Func[] args) + { + logger.Warn(typeof(T), exception, format, args); + } + + /// + /// Logs an information message. + /// + /// The reporting type. + /// The logger. + /// A message. + public static void Info(this ILogger logger, string message) + { + logger.Info(typeof(T), message); + } + + /// + /// Logs an information message. + /// + /// The reporting type. + /// The logger. + /// A message builder. + public static void Info(this ILogger logger, Func messageBuilder) + { + logger.Info(typeof(T), messageBuilder); + } + + /// + /// Logs a formatted information message. + /// + /// The reporting type. + /// The logger. + /// A composite format string. + /// An array of objects to format. + public static void Info(this ILogger logger, string format, params object[] args) + { + logger.Info(typeof(T), format, args); + } + + /// + /// Logs a formatted information message. + /// + /// The reporting type. + /// The logger. + /// A composite format string. + /// An array of functions returning objects to format. + public static void Info(this ILogger logger, string format, params Func[] args) + { + logger.Info(typeof(T), format, args); + } + + /// + /// Logs a debugging message. + /// + /// The reporting type. + /// The logger. + /// A message. + public static void Debug(this ILogger logger, string message) + { + logger.Debug(typeof(T), message); + } + + /// + /// Logs a debugging message. + /// + /// The reporting type. + /// The logger. + /// A message builder. + public static void Debug(this ILogger logger, Func messageBuilder) + { + logger.Debug(typeof(T), messageBuilder); + } + + /// + /// Logs a formatted debugging message. + /// + /// The reporting type. + /// The logger. + /// A composite format string. + /// An array of objects to format. + public static void Debug(this ILogger logger, string format, params object[] args) + { + logger.Debug(typeof(T), format, args); + } + + /// + /// Logs a formatted debugging message. + /// + /// The reporting type. + /// The logger. + /// A composite format string. + /// An array of functions returning objects to format. + public static void Debug(this ILogger logger, string format, params Func[] args) + { + logger.Debug(typeof(T), format, args); } } } \ No newline at end of file diff --git a/src/Umbraco.Core/Logging/ProfilerExtensions.cs b/src/Umbraco.Core/Logging/ProfilerExtensions.cs index 621cee65b2..70db34fc6d 100644 --- a/src/Umbraco.Core/Logging/ProfilerExtensions.cs +++ b/src/Umbraco.Core/Logging/ProfilerExtensions.cs @@ -5,31 +5,35 @@ namespace Umbraco.Core.Logging internal static class ProfilerExtensions { /// - /// Writes out a step prefixed with the type + /// Gets an that will time the code between its creation and disposal, + /// prefixing the name of the step with a reporting type name. /// - /// - /// - /// - /// + /// The reporting type. + /// The profiler. + /// The name of the step. + /// A step. + /// The returned is meant to be used within a using (...) {{ ... }} block. internal static IDisposable Step(this IProfiler profiler, string name) { - if (profiler == null) throw new ArgumentNullException("profiler"); + if (profiler == null) throw new ArgumentNullException(nameof(profiler)); return profiler.Step(typeof (T), name); } /// - /// Writes out a step prefixed with the type + /// Gets an that will time the code between its creation and disposal, + /// prefixing the name of the step with a reporting type name. /// - /// - /// - /// - /// - internal static IDisposable Step(this IProfiler profiler, Type objectType, string name) + /// The profiler. + /// The reporting type. + /// The name of the step. + /// A step. + /// The returned is meant to be used within a using (...) {{ ... }} block. + internal static IDisposable Step(this IProfiler profiler, Type reporting, string name) { - if (profiler == null) throw new ArgumentNullException("profiler"); - if (objectType == null) throw new ArgumentNullException("objectType"); - if (name == null) throw new ArgumentNullException("name"); - return profiler.Step(string.Format("[{0}] {1}", objectType.Name, name)); + if (profiler == null) throw new ArgumentNullException(nameof(profiler)); + if (reporting == null) throw new ArgumentNullException(nameof(reporting)); + if (name == null) throw new ArgumentNullException(nameof(name)); + return profiler.Step($"[{reporting.Name}] {name}"); } } } \ No newline at end of file diff --git a/src/Umbraco.Core/Logging/ProfilingLogger.cs b/src/Umbraco.Core/Logging/ProfilingLogger.cs index a64db5d732..190876dea3 100644 --- a/src/Umbraco.Core/Logging/ProfilingLogger.cs +++ b/src/Umbraco.Core/Logging/ProfilingLogger.cs @@ -3,59 +3,50 @@ using System; namespace Umbraco.Core.Logging { /// - /// Used to create DisposableTimer instances for debugging or tracing durations + /// Provides debug or trace logging with duration management. /// public sealed class ProfilingLogger { public ILogger Logger { get; } + public IProfiler Profiler { get; } public ProfilingLogger(ILogger logger, IProfiler profiler) { + if (logger == null) throw new ArgumentNullException(nameof(logger)); + if (profiler == null) throw new ArgumentNullException(nameof(profiler)); Logger = logger; Profiler = profiler; - if (logger == null) throw new ArgumentNullException("logger"); - if (profiler == null) throw new ArgumentNullException("profiler"); - } - - public DisposableTimer TraceDuration(string startMessage, string completeMessage) - { - return new DisposableTimer(Logger, DisposableTimer.LogType.Info, Profiler, typeof(T), startMessage, completeMessage); } public DisposableTimer TraceDuration(string startMessage) { - return new DisposableTimer(Logger, DisposableTimer.LogType.Info, Profiler, typeof(T), startMessage, "Complete"); + return TraceDuration(startMessage, "Completed."); } - public DisposableTimer TraceDuration(Type loggerType, string startMessage, string completeMessage) + public DisposableTimer TraceDuration(string startMessage, string completeMessage, string failMessage = null) { - return new DisposableTimer(Logger, DisposableTimer.LogType.Info, Profiler, loggerType, startMessage, completeMessage); + return new DisposableTimer(Logger, DisposableTimer.LogType.Info, Profiler, typeof(T), startMessage, completeMessage, failMessage); } - public DisposableTimer DebugDuration(string startMessage, string completeMessage) + public DisposableTimer TraceDuration(Type loggerType, string startMessage, string completeMessage, string failMessage = null) { - return new DisposableTimer(Logger, DisposableTimer.LogType.Debug, Profiler, typeof(T), startMessage, completeMessage); - } - - public DisposableTimer DebugDuration(string startMessage, string completeMessage, int minimumMsThreshold) - { - return new DisposableTimer(Logger, DisposableTimer.LogType.Debug, Profiler, typeof(T), startMessage, completeMessage, minimumMsThreshold); + return new DisposableTimer(Logger, DisposableTimer.LogType.Info, Profiler, loggerType, startMessage, completeMessage, failMessage); } public DisposableTimer DebugDuration(string startMessage) { - return new DisposableTimer(Logger, DisposableTimer.LogType.Debug, Profiler, typeof(T), startMessage, "Complete"); + return DebugDuration(startMessage, "Completed."); } - public DisposableTimer DebugDuration(Type loggerType, string startMessage, string completeMessage) + public DisposableTimer DebugDuration(string startMessage, string completeMessage, string failMessage = null, int thresholdMilliseconds = 0) { - return new DisposableTimer(Logger, DisposableTimer.LogType.Debug, Profiler, loggerType, startMessage, completeMessage); + return new DisposableTimer(Logger, DisposableTimer.LogType.Debug, Profiler, typeof(T), startMessage, completeMessage, failMessage, thresholdMilliseconds); } - public DisposableTimer DebugDuration(Type loggerType, string startMessage, string completeMessage, int minimumMsThreshold) + public DisposableTimer DebugDuration(Type loggerType, string startMessage, string completeMessage, string failMessage = null, int thresholdMilliseconds = 0) { - return new DisposableTimer(Logger, DisposableTimer.LogType.Debug, Profiler, loggerType, startMessage, completeMessage, minimumMsThreshold); + return new DisposableTimer(Logger, DisposableTimer.LogType.Debug, Profiler, loggerType, startMessage, completeMessage, failMessage, thresholdMilliseconds); } } } \ No newline at end of file diff --git a/src/Umbraco.Core/Logging/WebProfiler.cs b/src/Umbraco.Core/Logging/WebProfiler.cs index 8f0c52a8ba..fd8925bc1d 100644 --- a/src/Umbraco.Core/Logging/WebProfiler.cs +++ b/src/Umbraco.Core/Logging/WebProfiler.cs @@ -6,7 +6,7 @@ using StackExchange.Profiling.SqlFormatters; namespace Umbraco.Core.Logging { /// - /// A profiler used for web based activity based on the MiniProfiler framework. + /// Implements by using the MiniProfiler framework. /// internal class WebProfiler : IProfiler { @@ -35,34 +35,19 @@ namespace Umbraco.Core.Logging return request.Success && request.Result.Url.IsClientSideRequest() == false; } - /// - /// Render the UI to display the profiler - /// - /// - /// - /// Generally used for HTML displays - /// + /// public string Render() { return MiniProfiler.RenderIncludes(RenderPosition.Right).ToString(); } - /// - /// Profile a step - /// - /// - /// - /// - /// Use the 'using(' syntax - /// + /// public IDisposable Step(string name) { return _runtime.Debug ? MiniProfiler.Current.Step(name) : null; } - /// - /// Start the profiler - /// + /// public void Start() { MiniProfiler.Settings.SqlFormatter = new SqlServerFormatter(); @@ -70,23 +55,12 @@ namespace Umbraco.Core.Logging MiniProfiler.Start(); } - /// - /// Start the profiler - /// - /// - /// set discardResults to false when you want to abandon all profiling, this is useful for - /// when someone is not authenticated or you want to clear the results based on some other mechanism. - /// + /// public void Stop(bool discardResults = false) { MiniProfiler.Stop(discardResults); } - /// - /// Gets the request object from the app instance if it is available - /// - /// The application object - /// private static Attempt TryGetRequest(object sender) { var app = sender as HttpApplication; diff --git a/src/Umbraco.Core/Logging/WebProfilerComponent.cs b/src/Umbraco.Core/Logging/WebProfilerComponent.cs index 2f92e181c3..b324a36354 100644 --- a/src/Umbraco.Core/Logging/WebProfilerComponent.cs +++ b/src/Umbraco.Core/Logging/WebProfilerComponent.cs @@ -17,7 +17,7 @@ namespace Umbraco.Core.Logging private WebProfiler _profiler; - public void Initialize(IProfiler profiler, IRuntimeState runtime) + public void Initialize(IProfiler profiler, ILogger logger, IRuntimeState runtime) { // although registered in WebRuntime.Compose, ensure that we have // not been replaced by another component, and we are still "the" profiler @@ -27,12 +27,12 @@ namespace Umbraco.Core.Logging if (SystemUtilities.GetCurrentTrustLevel() < AspNetHostingPermissionLevel.High) { // if we don't have a high enough trust level we cannot bind to the events - LogHelper.Info("Cannot install when the application is running in Medium trust."); + logger.Info("Cannot install when the application is running in Medium trust."); } else if (runtime.Debug == false) { // only when debugging - LogHelper.Info("Cannot install when the application is not running in debug mode."); + logger.Info("Cannot install when the application is not running in debug mode."); } else { diff --git a/src/Umbraco.Core/Models/Member.cs b/src/Umbraco.Core/Models/Member.cs index 1b206645e7..3e9268f6aa 100644 --- a/src/Umbraco.Core/Models/Member.cs +++ b/src/Umbraco.Core/Models/Member.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Serialization; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.Logging; namespace Umbraco.Core.Models @@ -517,7 +518,7 @@ namespace Umbraco.Core.Models private Attempt WarnIfPropertyTypeNotFoundOnGet(string propertyAlias, string propertyName, T defaultVal) { - Action doLog = () => LogHelper.Warn( + Action doLog = () => Current.Logger.Warn( "Trying to access the '" + propertyName + "' property on " @@ -554,7 +555,7 @@ namespace Umbraco.Core.Models private bool WarnIfPropertyTypeNotFoundOnSet(string propertyAlias, string propertyname) { - Action doLog = () => LogHelper.Warn("An attempt was made to set a value on the property '" + Action doLog = () => Current.Logger.Warn("An attempt was made to set a value on the property '" + propertyname + "' on type " + typeof(Member) diff --git a/src/Umbraco.Core/Packaging/PackageBinaryInspector.cs b/src/Umbraco.Core/Packaging/PackageBinaryInspector.cs index 8852475543..f72219d542 100644 --- a/src/Umbraco.Core/Packaging/PackageBinaryInspector.cs +++ b/src/Umbraco.Core/Packaging/PackageBinaryInspector.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Reflection; using System.Security; using System.Security.Permissions; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.Logging; namespace Umbraco.Core.Packaging @@ -185,7 +186,7 @@ namespace Umbraco.Core.Packaging assemblyName.Name, "' see error log for full details.")); assembliesWithErrors.Add(a); - LogHelper.Error("An error occurred scanning package assemblies", ex); + Current.Logger.Error("An error occurred scanning package assemblies", ex); } } } @@ -229,7 +230,7 @@ namespace Umbraco.Core.Packaging a.GetName().Name, "' see error log for full details.")); assembliesWithErrors.Add(a); - LogHelper.Error("An error occurred scanning package assemblies", ex); + Current.Logger.Error("An error occurred scanning package assemblies", ex); } } diff --git a/src/Umbraco.Core/Persistence/DbConnectionExtensions.cs b/src/Umbraco.Core/Persistence/DbConnectionExtensions.cs index 7762978355..a0c42c5631 100644 --- a/src/Umbraco.Core/Persistence/DbConnectionExtensions.cs +++ b/src/Umbraco.Core/Persistence/DbConnectionExtensions.cs @@ -3,6 +3,7 @@ using System.Data; using System.Data.Common; using System.Linq; using NPoco; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.Logging; namespace Umbraco.Core.Persistence @@ -60,7 +61,7 @@ namespace Umbraco.Core.Persistence catch (DbException e) { // Don't swallow this error, the exception is super handy for knowing "why" its not available - LogHelper.WarnWithException("Configured database is reporting as not being available.", e); + Current.Logger.Warn(e, "Configured database is reporting as not being available."); return false; } diff --git a/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSevenThreeZero/MigrateAndRemoveTemplateMasterColumn.cs b/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSevenThreeZero/MigrateAndRemoveTemplateMasterColumn.cs index 452c5a4ff9..c81267b3d4 100644 --- a/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSevenThreeZero/MigrateAndRemoveTemplateMasterColumn.cs +++ b/src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSevenThreeZero/MigrateAndRemoveTemplateMasterColumn.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using NPoco; using Umbraco.Core.Configuration; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.Logging; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence.DatabaseModelDefinitions; @@ -61,7 +62,7 @@ namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSevenThreeZe { var sql = "SET parentID=@parentId WHERE id=@nodeId"; - LogHelper.Info("Executing sql statement: UPDATE umbracoNode " + sql); + Current.Logger.Info("Executing sql statement: UPDATE umbracoNode " + sql); database.Update(sql, new {parentId = template.master ?? -1, nodeId = template.nodeId}); @@ -82,7 +83,7 @@ namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSevenThreeZe "path=@buildPath", "id=@nodeId"); - LogHelper.Info("Executing sql statement: " + sql); + Current.Logger.Info("Executing sql statement: " + sql); //now build the correct path for the template database.Execute(sql, new diff --git a/src/Umbraco.Core/Plugins/PluginManager.cs b/src/Umbraco.Core/Plugins/PluginManager.cs index 331508eeae..c4a8431121 100644 --- a/src/Umbraco.Core/Plugins/PluginManager.cs +++ b/src/Umbraco.Core/Plugins/PluginManager.cs @@ -416,7 +416,7 @@ namespace Umbraco.Core.Plugins using (_logger.DebugDuration( $"Resolving {typeof(T).FullName}", $"Resolved {typeof(T).FullName}", // cannot contain typesFound.Count as it's evaluated before the find! - 50)) + thresholdMilliseconds: 50)) { // resolve within a lock & timer return ResolveTypes2(finder, resolutionType, cacheResult, rlock); diff --git a/src/Umbraco.Core/Plugins/TypeFinder.cs b/src/Umbraco.Core/Plugins/TypeFinder.cs index 2d02589154..265f69967b 100644 --- a/src/Umbraco.Core/Plugins/TypeFinder.cs +++ b/src/Umbraco.Core/Plugins/TypeFinder.cs @@ -7,6 +7,7 @@ using System.Security; using System.Text; using System.Web; using System.Web.Compilation; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.IO; using Umbraco.Core.Logging; @@ -115,7 +116,7 @@ namespace Umbraco.Core.Plugins catch (FileNotFoundException ex) { //this will occur if it cannot load the assembly - LogHelper.Error(typeof(TypeFinder), "Could not load assembly App_Code", ex); + Current.Logger.Error(typeof(TypeFinder), "Could not load assembly App_Code", ex); } } } @@ -394,7 +395,7 @@ namespace Umbraco.Core.Plugins } catch (TypeLoadException ex) { - LogHelper.Error(typeof(TypeFinder), string.Format("Could not query types on {0} assembly, this is most likely due to this assembly not being compatible with the current Umbraco version", a), ex); + Current.Logger.Error(typeof(TypeFinder), string.Format("Could not query types on {0} assembly, this is most likely due to this assembly not being compatible with the current Umbraco version", a), ex); continue; } @@ -539,7 +540,7 @@ namespace Umbraco.Core.Plugins } catch (TypeLoadException ex) { - LogHelper.Error(typeof(TypeFinder), string.Format("Could not query types on {0} assembly, this is most likely due to this assembly not being compatible with the current Umbraco version", a), ex); + Current.Logger.Error(typeof(TypeFinder), string.Format("Could not query types on {0} assembly, this is most likely due to this assembly not being compatible with the current Umbraco version", a), ex); continue; } diff --git a/src/Umbraco.Core/PropertyEditors/LegacyPropertyEditorIdToAliasConverter.cs b/src/Umbraco.Core/PropertyEditors/LegacyPropertyEditorIdToAliasConverter.cs index c15b2d0576..3c5fe9e0c9 100644 --- a/src/Umbraco.Core/PropertyEditors/LegacyPropertyEditorIdToAliasConverter.cs +++ b/src/Umbraco.Core/PropertyEditors/LegacyPropertyEditorIdToAliasConverter.cs @@ -3,6 +3,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Data; using System.Linq; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.Logging; namespace Umbraco.Core.PropertyEditors @@ -81,7 +82,7 @@ namespace Umbraco.Core.PropertyEditors var generated = alias.EncodeAsGuid(); CreateMap(generated, alias); - LogHelper.Warn(typeof(LegacyPropertyEditorIdToAliasConverter), "A legacy GUID id was generated for property editor " + alias + ". This occurs when the legacy APIs are used and done to attempt to maintain backwards compatibility. Consider upgrading all code to use the new Services APIs instead to avoid any potential issues."); + Current.Logger.Warn(typeof(LegacyPropertyEditorIdToAliasConverter), "A legacy GUID id was generated for property editor " + alias + ". This occurs when the legacy APIs are used and done to attempt to maintain backwards compatibility. Consider upgrading all code to use the new Services APIs instead to avoid any potential issues."); return generated; } diff --git a/src/Umbraco.Core/PropertyEditors/PreValueEditor.cs b/src/Umbraco.Core/PropertyEditors/PreValueEditor.cs index 939c57d066..dbf71a3190 100644 --- a/src/Umbraco.Core/PropertyEditors/PreValueEditor.cs +++ b/src/Umbraco.Core/PropertyEditors/PreValueEditor.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; using Newtonsoft.Json; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models; @@ -64,7 +65,7 @@ namespace Umbraco.Core.PropertyEditors } catch (Exception ex) { - LogHelper.WarnWithException("Could not create an instance of " + att.PreValueFieldType, ex); + Current.Logger.Warn(ex, "Could not create an instance of " + att.PreValueFieldType); } } else diff --git a/src/Umbraco.Core/PropertyEditors/PropertyValueEditor.cs b/src/Umbraco.Core/PropertyEditors/PropertyValueEditor.cs index 0b083025f7..eb0217ff51 100644 --- a/src/Umbraco.Core/PropertyEditors/PropertyValueEditor.cs +++ b/src/Umbraco.Core/PropertyEditors/PropertyValueEditor.cs @@ -4,6 +4,7 @@ using System.Globalization; using System.Linq; using System.Xml.Linq; using Newtonsoft.Json; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.Logging; using Umbraco.Core.Manifest; using Umbraco.Core.Models; @@ -251,7 +252,7 @@ namespace Umbraco.Core.PropertyEditors var result = TryConvertValueToCrlType(editorValue.Value); if (result.Success == false) { - LogHelper.Warn("The value " + editorValue.Value + " cannot be converted to the type " + GetDatabaseType()); + Current.Logger.Warn("The value " + editorValue.Value + " cannot be converted to the type " + GetDatabaseType()); return null; } return result.Result; diff --git a/src/Umbraco.Core/PropertyEditors/ValueConverters/GridValueConverter.cs b/src/Umbraco.Core/PropertyEditors/ValueConverters/GridValueConverter.cs index 57f268040e..22c699c223 100644 --- a/src/Umbraco.Core/PropertyEditors/ValueConverters/GridValueConverter.cs +++ b/src/Umbraco.Core/PropertyEditors/ValueConverters/GridValueConverter.cs @@ -102,7 +102,7 @@ namespace Umbraco.Core.PropertyEditors.ValueConverters } catch (Exception ex) { - LogHelper.Error("Could not parse the string " + sourceString + " to a json object", ex); + Current.Logger.Error("Could not parse the string " + sourceString + " to a json object", ex); } } diff --git a/src/Umbraco.Core/PropertyEditors/ValueConverters/ImageCropperValueConverter.cs b/src/Umbraco.Core/PropertyEditors/ValueConverters/ImageCropperValueConverter.cs index 54f64823fb..5a422f80dc 100644 --- a/src/Umbraco.Core/PropertyEditors/ValueConverters/ImageCropperValueConverter.cs +++ b/src/Umbraco.Core/PropertyEditors/ValueConverters/ImageCropperValueConverter.cs @@ -60,7 +60,7 @@ namespace Umbraco.Core.PropertyEditors.ValueConverters } catch (Exception ex) { - LogHelper.Error("Could not parse the string " + cropsString + " to a json object", ex); + Current.Logger.Error("Could not parse the string " + cropsString + " to a json object", ex); return; } @@ -118,7 +118,7 @@ namespace Umbraco.Core.PropertyEditors.ValueConverters } catch (Exception ex) { - LogHelper.Error("Could not parse the string " + sourceString + " to a json object", ex); + Current.Logger.Error("Could not parse the string " + sourceString + " to a json object", ex); return sourceString; } diff --git a/src/Umbraco.Core/PropertyEditors/ValueConverters/JsonValueConverter.cs b/src/Umbraco.Core/PropertyEditors/ValueConverters/JsonValueConverter.cs index bfee8768c3..4ca8c91531 100644 --- a/src/Umbraco.Core/PropertyEditors/ValueConverters/JsonValueConverter.cs +++ b/src/Umbraco.Core/PropertyEditors/ValueConverters/JsonValueConverter.cs @@ -52,7 +52,7 @@ namespace Umbraco.Core.PropertyEditors.ValueConverters } catch (Exception ex) { - LogHelper.Error("Could not parse the string " + sourceString + " to a json object", ex); + Current.Logger.Error("Could not parse the string " + sourceString + " to a json object", ex); } } diff --git a/src/Umbraco.Core/RuntimeLevel.cs b/src/Umbraco.Core/RuntimeLevel.cs index 456c0e3296..a15c513525 100644 --- a/src/Umbraco.Core/RuntimeLevel.cs +++ b/src/Umbraco.Core/RuntimeLevel.cs @@ -5,7 +5,7 @@ namespace Umbraco.Core /// /// The runtime has failed to boot and cannot run. /// - Failed = -1, + BootFailed = -1, /// /// The level is unknown. diff --git a/src/Umbraco.Core/Security/AuthenticationExtensions.cs b/src/Umbraco.Core/Security/AuthenticationExtensions.cs index 636d2c49a8..3761b1fadf 100644 --- a/src/Umbraco.Core/Security/AuthenticationExtensions.cs +++ b/src/Umbraco.Core/Security/AuthenticationExtensions.cs @@ -15,6 +15,7 @@ using AutoMapper; using Microsoft.Owin; using Newtonsoft.Json; using Umbraco.Core.Configuration; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.Models.Membership; using Umbraco.Core.Logging; @@ -122,7 +123,7 @@ namespace Umbraco.Core.Security catch (InvalidOperationException ex) { //This will occur if the required claim types are missing which would mean something strange is going on - LogHelper.Error(typeof(AuthenticationExtensions), "The current identity cannot be converted to " + typeof(UmbracoBackOfficeIdentity), ex); + Current.Logger.Error(typeof(AuthenticationExtensions), "The current identity cannot be converted to " + typeof(UmbracoBackOfficeIdentity), ex); } } diff --git a/src/Umbraco.Core/Security/MembershipProviderBase.cs b/src/Umbraco.Core/Security/MembershipProviderBase.cs index 3e02d6aec2..5c7b661b38 100644 --- a/src/Umbraco.Core/Security/MembershipProviderBase.cs +++ b/src/Umbraco.Core/Security/MembershipProviderBase.cs @@ -8,6 +8,7 @@ using System.Web; using System.Web.Configuration; using System.Web.Hosting; using System.Web.Security; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.Logging; namespace Umbraco.Core.Security @@ -262,7 +263,7 @@ namespace Umbraco.Core.Security if ((PasswordFormat == MembershipPasswordFormat.Hashed) && EnablePasswordRetrieval) { var ex = new ProviderException("Provider can not retrieve a hashed password"); - LogHelper.Error("Cannot specify a Hashed password format with the enabledPasswordRetrieval option set to true", ex); + Current.Logger.Error("Cannot specify a Hashed password format with the enabledPasswordRetrieval option set to true", ex); throw ex; } diff --git a/src/Umbraco.Core/Services/LocalizedTextServiceFileSources.cs b/src/Umbraco.Core/Services/LocalizedTextServiceFileSources.cs index c2e7cb1617..d02d6ad8c4 100644 --- a/src/Umbraco.Core/Services/LocalizedTextServiceFileSources.cs +++ b/src/Umbraco.Core/Services/LocalizedTextServiceFileSources.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Xml; using System.Xml.Linq; using Umbraco.Core.Cache; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.Logging; namespace Umbraco.Core.Services @@ -87,7 +88,7 @@ namespace Umbraco.Core.Services } catch (CultureNotFoundException) { - LogHelper.Warn( + Current.Logger.Warn( string.Format("The culture {0} found in the file {1} is not a valid culture", cultureVal, fileInfo.FullName)); //If the culture in the file is invalid, we'll just hope the file name is a valid culture below, otherwise // an exception will be thrown. @@ -125,7 +126,7 @@ namespace Umbraco.Core.Services if (fileSourceFolder.Exists == false) { - LogHelper.Warn("The folder does not exist: {0}, therefore no sources will be discovered", () => fileSourceFolder.FullName); + Current.Logger.Warn("The folder does not exist: {0}, therefore no sources will be discovered", () => fileSourceFolder.FullName); } else { diff --git a/src/Umbraco.Core/Services/TagExtractor.cs b/src/Umbraco.Core/Services/TagExtractor.cs index 0e6d605e41..0862971be5 100644 --- a/src/Umbraco.Core/Services/TagExtractor.cs +++ b/src/Umbraco.Core/Services/TagExtractor.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Newtonsoft.Json; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.Editors; @@ -40,7 +41,7 @@ namespace Umbraco.Core.Services } catch (Exception ex) { - LogHelper.Error("Could not create custom " + attribute.TagPropertyDefinitionType + " tag definition", ex); + Current.Logger.Error("Could not create custom " + attribute.TagPropertyDefinitionType + " tag definition", ex); throw; } SetPropertyTags(property, convertedPropertyValue, def.Delimiter, def.ReplaceTags, def.TagGroup, attribute.ValueType, def.StorageType); @@ -93,7 +94,7 @@ namespace Umbraco.Core.Services } catch (Exception ex) { - LogHelper.WarnWithException("Could not automatically convert stored json value to an enumerable string", ex); + Current.Logger.Warn(ex, "Could not automatically convert stored json value to an enumerable string"); } break; default: diff --git a/src/Umbraco.Core/Services/UserService.cs b/src/Umbraco.Core/Services/UserService.cs index 829543afe4..df56c24997 100644 --- a/src/Umbraco.Core/Services/UserService.cs +++ b/src/Umbraco.Core/Services/UserService.cs @@ -337,7 +337,7 @@ namespace Umbraco.Core.Services //Special case, if we are upgrading and an exception occurs, just continue if (IsUpgrading == false) throw; - Logger.WarnWithException("An error occurred attempting to save a user instance during upgrade, normally this warning can be ignored", ex); + Logger.Warn(ex, "An error occurred attempting to save a user instance during upgrade, normally this warning can be ignored"); return; } } diff --git a/src/Umbraco.Core/Sync/ServerMessengerBase.cs b/src/Umbraco.Core/Sync/ServerMessengerBase.cs index 5b15dce392..16be18ca21 100644 --- a/src/Umbraco.Core/Sync/ServerMessengerBase.cs +++ b/src/Umbraco.Core/Sync/ServerMessengerBase.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Umbraco.Core.Cache; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.Logging; namespace Umbraco.Core.Sync @@ -157,7 +158,7 @@ namespace Umbraco.Core.Sync { if (refresher == null) throw new ArgumentNullException(nameof(refresher)); - LogHelper.Debug("Invoking refresher {0} on local server for message type RefreshByPayload", + Current.Logger.Debug("Invoking refresher {0} on local server for message type RefreshByPayload", refresher.GetType); var payloadRefresher = refresher as IPayloadCacheRefresher; @@ -180,7 +181,7 @@ namespace Umbraco.Core.Sync { if (refresher == null) throw new ArgumentNullException(nameof(refresher)); - LogHelper.Debug("Invoking refresher {0} on local server for message type {1}", + Current.Logger.Debug("Invoking refresher {0} on local server for message type {1}", refresher.GetType, () => messageType); @@ -243,7 +244,7 @@ namespace Umbraco.Core.Sync { if (refresher == null) throw new ArgumentNullException(nameof(refresher)); - LogHelper.Debug("Invoking refresher {0} on local server for message type {1}", + Current.Logger.Debug("Invoking refresher {0} on local server for message type {1}", refresher.GetType, () => messageType); @@ -281,7 +282,7 @@ namespace Umbraco.Core.Sync //{ // if (refresher == null) throw new ArgumentNullException("refresher"); - // LogHelper.Debug("Invoking refresher {0} on local server for message type Notify", + // Current.Logger.Debug("Invoking refresher {0} on local server for message type Notify", // () => refresher.GetType()); // refresher.Notify(payload); diff --git a/src/Umbraco.Core/Sync/WebServiceServerMessenger.cs b/src/Umbraco.Core/Sync/WebServiceServerMessenger.cs index 221f32e31b..d249cc8f02 100644 --- a/src/Umbraco.Core/Sync/WebServiceServerMessenger.cs +++ b/src/Umbraco.Core/Sync/WebServiceServerMessenger.cs @@ -8,6 +8,7 @@ using Newtonsoft.Json; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Core.Cache; +using Umbraco.Core.DependencyInjection; namespace Umbraco.Core.Sync { @@ -108,7 +109,7 @@ namespace Umbraco.Core.Sync } catch (Exception ex) { - LogHelper.Error("Could not resolve username/password delegate, server distribution will be disabled", ex); + Current.Logger.Error("Could not resolve username/password delegate, server distribution will be disabled", ex); Login = null; Password = null; DistributedEnabled = false; @@ -157,7 +158,7 @@ namespace Umbraco.Core.Sync Type idArrayType = null, string jsonPayload = null) { - LogHelper.Debug( + Current.Logger.Debug( "Performing distributed call for {0}/{1} on servers ({2}), ids: {3}, json: {4}", refresher.GetType, () => messageType, @@ -356,28 +357,28 @@ namespace Umbraco.Core.Sync private static void LogDispatchBatchError(Exception ee) { - LogHelper.Error("Error refreshing distributed list", ee); + Current.Logger.Error("Error refreshing distributed list", ee); } private static void LogDispatchBatchResult(int errorCount) { - LogHelper.Debug(string.Format("Distributed server push completed with {0} nodes reporting an error", errorCount == 0 ? "no" : errorCount.ToString(CultureInfo.InvariantCulture))); + Current.Logger.Debug(string.Format("Distributed server push completed with {0} nodes reporting an error", errorCount == 0 ? "no" : errorCount.ToString(CultureInfo.InvariantCulture))); } private static void LogDispatchNodeError(Exception ex) { - LogHelper.Error("Error refreshing a node in the distributed list", ex); + Current.Logger.Error("Error refreshing a node in the distributed list", ex); } private static void LogDispatchNodeError(WebException ex) { string url = (ex.Response != null) ? ex.Response.ResponseUri.ToString() : "invalid url (responseUri null)"; - LogHelper.Error("Error refreshing a node in the distributed list, URI attempted: " + url, ex); + Current.Logger.Error("Error refreshing a node in the distributed list, URI attempted: " + url, ex); } private static void LogStartDispatch() { - LogHelper.Info("Submitting calls to distributed servers"); + Current.Logger.Info("Submitting calls to distributed servers"); } #endregion diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 8350275e89..697b42d959 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -1148,7 +1148,6 @@ - diff --git a/src/Umbraco.Tests/Integration/ContentEventsTests.cs b/src/Umbraco.Tests/Integration/ContentEventsTests.cs index ca5e789744..ab35a8b993 100644 --- a/src/Umbraco.Tests/Integration/ContentEventsTests.cs +++ b/src/Umbraco.Tests/Integration/ContentEventsTests.cs @@ -84,7 +84,7 @@ namespace Umbraco.Tests.Integration { _events = new List(); _msgCount = 0; - LogHelper.Debug("RESET EVENTS"); + Current.Logger.Debug("RESET EVENTS"); } private IContent CreateContent(int parentId = -1) diff --git a/src/Umbraco.Tests/Models/ContentTests.cs b/src/Umbraco.Tests/Models/ContentTests.cs index 0f2ba9994e..e775e35734 100644 --- a/src/Umbraco.Tests/Models/ContentTests.cs +++ b/src/Umbraco.Tests/Models/ContentTests.cs @@ -167,6 +167,13 @@ namespace Umbraco.Tests.Models Assert.AreNotSame(content.Properties, clone.Properties); } + private static ProfilingLogger GetTestProfilingLogger() + { + var logger = new DebugDiagnosticsLogger(); + var profiler = new TestProfiler(); + return new ProfilingLogger(logger, profiler); + } + [Ignore] [Test] public void Can_Deep_Clone_Perf_Test() @@ -206,7 +213,9 @@ namespace Umbraco.Tests.Models var runtimeCache = new ObjectCacheRuntimeCacheProvider(); runtimeCache.InsertCacheItem(content.Id.ToString(CultureInfo.InvariantCulture), () => content); - using (DisposableTimer.DebugDuration("STARTING PERF TEST WITH RUNTIME CACHE")) + var proflog = GetTestProfilingLogger(); + + using (proflog.DebugDuration("STARTING PERF TEST WITH RUNTIME CACHE")) { for (int j = 0; j < 1000; j++) { @@ -214,7 +223,7 @@ namespace Umbraco.Tests.Models } } - using (DisposableTimer.DebugDuration("STARTING PERF TEST WITHOUT RUNTIME CACHE")) + using (proflog.DebugDuration("STARTING PERF TEST WITHOUT RUNTIME CACHE")) { for (int j = 0; j < 1000; j++) { diff --git a/src/Umbraco.Tests/Models/ContentTypeTests.cs b/src/Umbraco.Tests/Models/ContentTypeTests.cs index 3ae6a62ee6..5742521f9b 100644 --- a/src/Umbraco.Tests/Models/ContentTypeTests.cs +++ b/src/Umbraco.Tests/Models/ContentTypeTests.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using System.Linq; using NUnit.Framework; using Umbraco.Core; +using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.EntityBase; using Umbraco.Core.Serialization; @@ -92,6 +93,13 @@ namespace Umbraco.Tests.Models } } + private static ProfilingLogger GetTestProfilingLogger() + { + var logger = new DebugDiagnosticsLogger(); + var profiler = new TestProfiler(); + return new ProfilingLogger(logger, profiler); + } + [Ignore] [Test] public void Can_Deep_Clone_Content_Type_Perf_Test() @@ -132,11 +140,13 @@ namespace Umbraco.Tests.Models ((IUmbracoEntity)contentType).AdditionalData.Add("test1", 123); ((IUmbracoEntity)contentType).AdditionalData.Add("test2", "hello"); - using (DisposableTimer.DebugDuration("STARTING PERF TEST")) + var proflog = GetTestProfilingLogger(); + + using (proflog.DebugDuration("STARTING PERF TEST")) { - for (int j = 0; j < 1000; j++) + for (var j = 0; j < 1000; j++) { - using (DisposableTimer.DebugDuration("Cloning content type")) + using (proflog.DebugDuration("Cloning content type")) { var clone = (ContentType)contentType.DeepClone(); } diff --git a/src/Umbraco.Tests/Plugins/TypeFinderTests.cs b/src/Umbraco.Tests/Plugins/TypeFinderTests.cs index b44ff14f4c..2ce4725aa2 100644 --- a/src/Umbraco.Tests/Plugins/TypeFinderTests.cs +++ b/src/Umbraco.Tests/Plugins/TypeFinderTests.cs @@ -19,7 +19,9 @@ using Umbraco.Core; using Umbraco.Core.IO; using umbraco.DataLayer; using umbraco.uicontrols; +using Umbraco.Core.Logging; using Umbraco.Core.Plugins; +using Umbraco.Tests.TestHelpers; using Umbraco.Web; using Umbraco.Web.Models.Trees; using Umbraco.Web.Trees; @@ -100,27 +102,35 @@ namespace Umbraco.Tests.Plugins Assert.AreEqual(22, typesFound.Count()); // 22 classes in Umbraco.Web are marked with [Tree] } + private static ProfilingLogger GetTestProfilingLogger() + { + var logger = new DebugDiagnosticsLogger(); + var profiler = new TestProfiler(); + return new ProfilingLogger(logger, profiler); + } + [Ignore] [Test] public void Benchmark_Original_Finder() { - using (DisposableTimer.TraceDuration("Starting test", "Finished test")) + var profilingLogger = GetTestProfilingLogger(); + using (profilingLogger.TraceDuration("Starting test", "Finished test")) { - using (DisposableTimer.TraceDuration("Starting FindClassesOfType", "Finished FindClassesOfType")) + using (profilingLogger.TraceDuration("Starting FindClassesOfType", "Finished FindClassesOfType")) { for (var i = 0; i < 1000; i++) { Assert.Greater(TypeFinderOriginal.FindClassesOfType(_assemblies).Count(), 0); } } - using (DisposableTimer.TraceDuration("Starting FindClassesOfTypeWithAttribute", "Finished FindClassesOfTypeWithAttribute")) + using (profilingLogger.TraceDuration("Starting FindClassesOfTypeWithAttribute", "Finished FindClassesOfTypeWithAttribute")) { for (var i = 0; i < 1000; i++) { Assert.Greater(TypeFinderOriginal.FindClassesOfTypeWithAttribute(_assemblies).Count(), 0); } } - using (DisposableTimer.TraceDuration("Starting FindClassesWithAttribute", "Finished FindClassesWithAttribute")) + using (profilingLogger.TraceDuration("Starting FindClassesWithAttribute", "Finished FindClassesWithAttribute")) { for (var i = 0; i < 1000; i++) { @@ -135,23 +145,24 @@ namespace Umbraco.Tests.Plugins [Test] public void Benchmark_New_Finder() { - using (DisposableTimer.TraceDuration("Starting test", "Finished test")) + var profilingLogger = GetTestProfilingLogger(); + using (profilingLogger.TraceDuration("Starting test", "Finished test")) { - using (DisposableTimer.TraceDuration("Starting FindClassesOfType", "Finished FindClassesOfType")) + using (profilingLogger.TraceDuration("Starting FindClassesOfType", "Finished FindClassesOfType")) { for (var i = 0; i < 1000; i++) { Assert.Greater(TypeFinder.FindClassesOfType(_assemblies).Count(), 0); } } - using (DisposableTimer.TraceDuration("Starting FindClassesOfTypeWithAttribute", "Finished FindClassesOfTypeWithAttribute")) + using (profilingLogger.TraceDuration("Starting FindClassesOfTypeWithAttribute", "Finished FindClassesOfTypeWithAttribute")) { for (var i = 0; i < 1000; i++) { Assert.Greater(TypeFinder.FindClassesOfTypeWithAttribute(_assemblies).Count(), 0); } } - using (DisposableTimer.TraceDuration("Starting FindClassesWithAttribute", "Finished FindClassesWithAttribute")) + using (profilingLogger.TraceDuration("Starting FindClassesWithAttribute", "Finished FindClassesWithAttribute")) { for (var i = 0; i < 1000; i++) { diff --git a/src/Umbraco.Tests/PropertyEditors/MultiValuePropertyEditorTests.cs b/src/Umbraco.Tests/PropertyEditors/MultiValuePropertyEditorTests.cs index d49af00e18..b32ae63930 100644 --- a/src/Umbraco.Tests/PropertyEditors/MultiValuePropertyEditorTests.cs +++ b/src/Umbraco.Tests/PropertyEditors/MultiValuePropertyEditorTests.cs @@ -30,7 +30,7 @@ namespace Umbraco.Tests.PropertyEditors { var dataTypeServiceMock = new Mock(); var dataTypeService = dataTypeServiceMock.Object; - var editor = new PublishValuesMultipleValueEditor(true, dataTypeService, new PropertyValueEditor()); + var editor = new PublishValuesMultipleValueEditor(true, dataTypeService, Mock.Of(), new PropertyValueEditor()); var prop = new Property(1, Guid.NewGuid(), new PropertyType(new DataTypeDefinition(1, "Test.TestEditor")), @@ -56,7 +56,7 @@ namespace Umbraco.Tests.PropertyEditors })); var dataTypeService = dataTypeServiceMock.Object; - var editor = new PublishValuesMultipleValueEditor(false, dataTypeService, new PropertyValueEditor()); + var editor = new PublishValuesMultipleValueEditor(false, dataTypeService, Mock.Of(), new PropertyValueEditor()); var prop = new Property(1, Guid.NewGuid(), new PropertyType(new DataTypeDefinition(1, "Test.TestEditor")), @@ -81,7 +81,7 @@ namespace Umbraco.Tests.PropertyEditors })); var dataTypeService = dataTypeServiceMock.Object; - var editor = new PublishValueValueEditor(dataTypeService, new PropertyValueEditor()); + var editor = new PublishValueValueEditor(dataTypeService, new PropertyValueEditor(), Mock.Of()); var prop = new Property(1, Guid.NewGuid(), new PropertyType(new DataTypeDefinition(1, "Test.TestEditor")), @@ -120,7 +120,7 @@ namespace Umbraco.Tests.PropertyEditors {"item3", new PreValue(3, "Item 3")} }); - var editor = new ValueListPreValueEditor(Mock.Of()); + var editor = new ValueListPreValueEditor(Mock.Of(), logger); var result = editor.ConvertDbToEditor(defaultVals, persisted); diff --git a/src/Umbraco.Tests/Services/ContentServicePerformanceTest.cs b/src/Umbraco.Tests/Services/ContentServicePerformanceTest.cs index d138f3f72f..f1cde2c002 100644 --- a/src/Umbraco.Tests/Services/ContentServicePerformanceTest.cs +++ b/src/Umbraco.Tests/Services/ContentServicePerformanceTest.cs @@ -40,6 +40,13 @@ namespace Umbraco.Tests.Services Assert.IsInstanceOf(Current.Profiler); } + private static ProfilingLogger GetTestProfilingLogger() + { + var logger = new DebugDiagnosticsLogger(); + var profiler = new TestProfiler(); + return new ProfilingLogger(logger, profiler); + } + [Test] public void Retrieving_All_Content_In_Site() { @@ -88,7 +95,8 @@ namespace Umbraco.Tests.Services } var total = new List(); - using (DisposableTimer.TraceDuration("Getting all content in site")) + + using (GetTestProfilingLogger().TraceDuration("Getting all content in site")) { TestProfiler.Enable(); total.AddRange(ServiceContext.ContentService.GetRootContent()); @@ -97,9 +105,8 @@ namespace Umbraco.Tests.Services total.AddRange(ServiceContext.ContentService.GetDescendants(content)); } TestProfiler.Disable(); - LogHelper.Info("Returned " + total.Count + " items"); + Current.Logger.Info("Returned " + total.Count + " items"); } - } [Test] diff --git a/src/Umbraco.Tests/Services/PerformanceTests.cs b/src/Umbraco.Tests/Services/PerformanceTests.cs index 1accdb705a..173dca66a2 100644 --- a/src/Umbraco.Tests/Services/PerformanceTests.cs +++ b/src/Umbraco.Tests/Services/PerformanceTests.cs @@ -9,6 +9,7 @@ using System.Xml.Linq; using NPoco; using NUnit.Framework; using Umbraco.Core; +using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence; @@ -62,6 +63,13 @@ namespace Umbraco.Tests.Services base.TearDown(); } + private static ProfilingLogger GetTestProfilingLogger() + { + var logger = new DebugDiagnosticsLogger(); + var profiler = new TestProfiler(); + return new ProfilingLogger(logger, profiler); + } + [Test] public void Get_All_Published_Content() { @@ -71,7 +79,8 @@ namespace Umbraco.Tests.Services var countOfPublished = result.Count(x => x.Published); var contentTypeId = result.First().ContentTypeId; - using (DisposableTimer.DebugDuration("Getting published content normally")) + var proflog = GetTestProfilingLogger(); + using (proflog.DebugDuration("Getting published content normally")) { //do this 10x! for (var i = 0; i < 10; i++) @@ -90,7 +99,7 @@ namespace Umbraco.Tests.Services } - using (DisposableTimer.DebugDuration("Getting published content optimized")) + using (proflog.DebugDuration("Getting published content optimized")) { //do this 10x! @@ -114,7 +123,8 @@ namespace Umbraco.Tests.Services var countOfPublished = result.Count(x => x.Published); var contentTypeId = result.First().ContentTypeId; - using (DisposableTimer.DebugDuration("Getting published content of type normally")) + var proflog = GetTestProfilingLogger(); + using (proflog.DebugDuration("Getting published content of type normally")) { //do this 10x! for (var i = 0; i < 10; i++) @@ -126,7 +136,7 @@ namespace Umbraco.Tests.Services } } - using (DisposableTimer.DebugDuration("Getting published content of type optimized")) + using (proflog.DebugDuration("Getting published content of type optimized")) { //do this 10x! @@ -145,10 +155,11 @@ namespace Umbraco.Tests.Services var customObjectType = Guid.NewGuid(); //chuck lots of data in the db var nodes = PrimeDbWithLotsOfContentXmlRecords(customObjectType); + var proflog = GetTestProfilingLogger(); //now we need to test the difference between truncating all records and re-inserting them as we do now, //vs updating them (which might result in checking if they exist for or listening on an exception). - using (DisposableTimer.DebugDuration("Starting truncate + normal insert test")) + using (proflog.DebugDuration("Starting truncate + normal insert test")) { //do this 10x! for (var i = 0; i < 10; i++) @@ -168,7 +179,7 @@ namespace Umbraco.Tests.Services } //now, isntead of truncating, we'll attempt to update and if it doesn't work then we insert - using (DisposableTimer.DebugDuration("Starting update test")) + using (proflog.DebugDuration("Starting update test")) { //do this 10x! for (var i = 0; i < 10; i++) @@ -183,7 +194,7 @@ namespace Umbraco.Tests.Services } //now, test truncating but then do bulk insertion of records - using (DisposableTimer.DebugDuration("Starting truncate + bulk insert test")) + using (proflog.DebugDuration("Starting truncate + bulk insert test")) { //do this 10x! for (var i = 0; i < 10; i++) @@ -200,7 +211,7 @@ namespace Umbraco.Tests.Services } //now, test truncating but then do bulk insertion of records - using (DisposableTimer.DebugDuration("Starting truncate + bulk insert test in one transaction")) + using (proflog.DebugDuration("Starting truncate + bulk insert test in one transaction")) { //do this 10x! for (var i = 0; i < 10; i++) diff --git a/src/Umbraco.Tests/TestHelpers/BaseDatabaseFactoryTest.cs b/src/Umbraco.Tests/TestHelpers/BaseDatabaseFactoryTest.cs index 48b9b65a72..e7b4813d6e 100644 --- a/src/Umbraco.Tests/TestHelpers/BaseDatabaseFactoryTest.cs +++ b/src/Umbraco.Tests/TestHelpers/BaseDatabaseFactoryTest.cs @@ -276,14 +276,15 @@ namespace Umbraco.Tests.TestHelpers ContentTypesCache = new PublishedContentTypeCache( Current.Services.ContentTypeService, Current.Services.MediaTypeService, - Current.Services.MemberTypeService); + Current.Services.MemberTypeService, + Current.Logger); // testing=true so XmlStore will not use the file nor the database var facadeAccessor = new TestFacadeAccessor(); var service = new FacadeService( Current.Services, _uowProvider, - cache, facadeAccessor, ContentTypesCache, null, true, enableRepositoryEvents); + cache, facadeAccessor, Current.Logger, ContentTypesCache, null, true, enableRepositoryEvents); // initialize PublishedCacheService content with an Xml source service.XmlStore.GetXmlDocument = () => @@ -406,7 +407,7 @@ namespace Umbraco.Tests.TestHelpers } catch (Exception ex) { - LogHelper.Error("Could not remove the old database file", ex); + Current.Logger.Error("Could not remove the old database file", ex); //We will swallow this exception! That's because a sub class might require further teardown logic. onFail?.Invoke(ex); diff --git a/src/Umbraco.Tests/TestHelpers/BaseRoutingTest.cs b/src/Umbraco.Tests/TestHelpers/BaseRoutingTest.cs index f693ebd580..7c43ec222b 100644 --- a/src/Umbraco.Tests/TestHelpers/BaseRoutingTest.cs +++ b/src/Umbraco.Tests/TestHelpers/BaseRoutingTest.cs @@ -31,7 +31,7 @@ namespace Umbraco.Tests.TestHelpers var umbracoContext = GetUmbracoContext(url, templateId, routeData); var urlProvider = new UrlProvider(umbracoContext, umbracoSettings.WebRouting, new IUrlProvider[] { - new DefaultUrlProvider(umbracoSettings.RequestHandler) + new DefaultUrlProvider(umbracoSettings.RequestHandler, Current.Logger) }); var routingContext = new RoutingContext( umbracoContext, diff --git a/src/Umbraco.Tests/TestHelpers/TestProfiler.cs b/src/Umbraco.Tests/TestHelpers/TestProfiler.cs index 46b798613d..841f99e260 100644 --- a/src/Umbraco.Tests/TestHelpers/TestProfiler.cs +++ b/src/Umbraco.Tests/TestHelpers/TestProfiler.cs @@ -2,7 +2,6 @@ using System; using StackExchange.Profiling; using StackExchange.Profiling.SqlFormatters; using Umbraco.Core.Logging; -using Umbraco.Core.Profiling; namespace Umbraco.Tests.TestHelpers { @@ -18,7 +17,7 @@ namespace Umbraco.Tests.TestHelpers _enabled = false; } - private static bool _enabled = false; + private static bool _enabled; public string Render() { @@ -32,21 +31,17 @@ namespace Umbraco.Tests.TestHelpers public void Start() { - if (_enabled) - { - MiniProfiler.Settings.SqlFormatter = new SqlServerFormatter(); - MiniProfiler.Settings.StackMaxLength = 5000; - MiniProfiler.Start(); - } - + if (_enabled == false) return; + + MiniProfiler.Settings.SqlFormatter = new SqlServerFormatter(); + MiniProfiler.Settings.StackMaxLength = 5000; + MiniProfiler.Start(); } public void Stop(bool discardResults = false) { if (_enabled) - { MiniProfiler.Stop(discardResults); - } } } } \ No newline at end of file diff --git a/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs b/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs index d60f3f77a9..556c7b1a60 100644 --- a/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs +++ b/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs @@ -399,7 +399,7 @@ namespace Umbraco.Tests.Web.Mvc var urlProvider = new UrlProvider(umbracoContext, settings.WebRouting, new IUrlProvider[] { - new DefaultUrlProvider(settings.RequestHandler) + new DefaultUrlProvider(settings.RequestHandler, Current.Logger) }); var routingContext = new RoutingContext( umbracoContext, @@ -438,7 +438,7 @@ namespace Umbraco.Tests.Web.Mvc var cache = new NullCacheProvider(); var provider = new NPocoUnitOfWorkProvider(databaseFactory, new RepositoryFactory(Mock.Of())); - _service = new FacadeService(svcCtx, provider, cache, Enumerable.Empty(), null, null, true, false); // no events + _service = new FacadeService(svcCtx, provider, cache, Enumerable.Empty(), null, Current.Logger, null, true, false); // no events var http = GetHttpContextFactory(url, routeData).HttpContext; diff --git a/src/Umbraco.Web.UI/umbraco/Install/Legacy/LoadStarterKits.ascx.cs b/src/Umbraco.Web.UI/umbraco/Install/Legacy/LoadStarterKits.ascx.cs index 013cd28c00..d205a93963 100644 --- a/src/Umbraco.Web.UI/umbraco/Install/Legacy/LoadStarterKits.ascx.cs +++ b/src/Umbraco.Web.UI/umbraco/Install/Legacy/LoadStarterKits.ascx.cs @@ -85,7 +85,7 @@ namespace Umbraco.Web.UI.Install.Steps.Skinning } catch (Exception ex) { - LogHelper.Error("Cannot connect to package repository", ex); + Current.Logger.Error("Cannot connect to package repository", ex); CannotConnect = true; } diff --git a/src/Umbraco.Web.UI/umbraco/developer/Packages/StarterKits.aspx.cs b/src/Umbraco.Web.UI/umbraco/developer/Packages/StarterKits.aspx.cs index f673156fbf..2afd4394fe 100644 --- a/src/Umbraco.Web.UI/umbraco/developer/Packages/StarterKits.aspx.cs +++ b/src/Umbraco.Web.UI/umbraco/developer/Packages/StarterKits.aspx.cs @@ -50,7 +50,7 @@ namespace Umbraco.Web.UI.Umbraco.Developer.Packages } catch (Exception ex) { - LogHelper.Error("Cannot connect to package repository", ex); + Current.Logger.Error("Cannot connect to package repository", ex); InstallationDirectoryNotAvailable.Visible = true; StarterKitNotInstalled.Visible = false; } diff --git a/src/Umbraco.Web.UI/umbraco/settings/views/EditView.aspx.cs b/src/Umbraco.Web.UI/umbraco/settings/views/EditView.aspx.cs index 1c22a125c7..07b57b768a 100644 --- a/src/Umbraco.Web.UI/umbraco/settings/views/EditView.aspx.cs +++ b/src/Umbraco.Web.UI/umbraco/settings/views/EditView.aspx.cs @@ -108,7 +108,7 @@ namespace Umbraco.Web.UI.Umbraco.Settings.Views } catch (Exception ex) { - LogHelper.Error("An error occurred setting a master template id", ex); + Current.Logger.Error("An error occurred setting a master template id", ex); } MasterTemplate.SelectedValue = selectedTemplate; diff --git a/src/Umbraco.Web/Cache/CacheRefresherComponent.cs b/src/Umbraco.Web/Cache/CacheRefresherComponent.cs index 3421e1946a..c1b443dda5 100644 --- a/src/Umbraco.Web/Cache/CacheRefresherComponent.cs +++ b/src/Umbraco.Web/Cache/CacheRefresherComponent.cs @@ -22,7 +22,7 @@ namespace Umbraco.Web.Cache { public void Initialize() { - LogHelper.Info("Initializing Umbraco internal event handlers for cache refreshing."); + Current.Logger.Info("Initializing Umbraco internal event handlers for cache refreshing."); AddHandlers(); } diff --git a/src/Umbraco.Web/Editors/ContentController.cs b/src/Umbraco.Web/Editors/ContentController.cs index 488526fe19..6735586525 100644 --- a/src/Umbraco.Web/Editors/ContentController.cs +++ b/src/Umbraco.Web/Editors/ContentController.cs @@ -485,14 +485,14 @@ namespace Umbraco.Web.Editors // Save content with new sort order and update content xml in db accordingly if (contentService.Sort(sortedContent) == false) { - LogHelper.Warn("Content sorting failed, this was probably caused by an event being cancelled"); + Logger.Warn("Content sorting failed, this was probably caused by an event being cancelled"); return Request.CreateValidationErrorResponse("Content sorting failed, this was probably caused by an event being cancelled"); } return Request.CreateResponse(HttpStatusCode.OK); } catch (Exception ex) { - LogHelper.Error("Could not update content sort order", ex); + Logger.Error("Could not update content sort order", ex); throw; } } @@ -591,7 +591,7 @@ namespace Umbraco.Web.Editors if (template == null && contentItem.TemplateAlias.IsNullOrWhiteSpace() == false) { //ModelState.AddModelError("Template", "No template exists with the specified alias: " + contentItem.TemplateAlias); - LogHelper.Warn("No template exists with the specified alias: " + contentItem.TemplateAlias); + Logger.Warn("No template exists with the specified alias: " + contentItem.TemplateAlias); } else { diff --git a/src/Umbraco.Web/Editors/ContentControllerBase.cs b/src/Umbraco.Web/Editors/ContentControllerBase.cs index 098388b547..75ffcf5c7d 100644 --- a/src/Umbraco.Web/Editors/ContentControllerBase.cs +++ b/src/Umbraco.Web/Editors/ContentControllerBase.cs @@ -89,7 +89,7 @@ namespace Umbraco.Web.Editors //get the deserialized value from the property editor if (p.PropertyEditor == null) { - LogHelper.Warn("No property editor found for property " + p.Alias); + Logger.Warn("No property editor found for property " + p.Alias); } else { diff --git a/src/Umbraco.Web/Editors/MediaController.cs b/src/Umbraco.Web/Editors/MediaController.cs index 3a5735576b..fc2d15fab8 100644 --- a/src/Umbraco.Web/Editors/MediaController.cs +++ b/src/Umbraco.Web/Editors/MediaController.cs @@ -383,14 +383,14 @@ namespace Umbraco.Web.Editors // Save Media with new sort order and update content xml in db accordingly if (mediaService.Sort(sortedMedia) == false) { - LogHelper.Warn("Media sorting failed, this was probably caused by an event being cancelled"); + Logger.Warn("Media sorting failed, this was probably caused by an event being cancelled"); return Request.CreateValidationErrorResponse("Media sorting failed, this was probably caused by an event being cancelled"); } return Request.CreateResponse(HttpStatusCode.OK); } catch (Exception ex) { - LogHelper.Error("Could not update media sort order", ex); + Logger.Error("Could not update media sort order", ex); throw; } } diff --git a/src/Umbraco.Web/Editors/MemberController.cs b/src/Umbraco.Web/Editors/MemberController.cs index 067e79cf25..34a74f3c34 100644 --- a/src/Umbraco.Web/Editors/MemberController.cs +++ b/src/Umbraco.Web/Editors/MemberController.cs @@ -408,7 +408,7 @@ namespace Umbraco.Web.Editors } catch (Exception ex) { - LogHelper.WarnWithException("Could not update member, the provider returned an error", ex); + Logger.Warn(ex, "Could not update member, the provider returned an error"); ModelState.AddPropertyError( //specify 'default' just so that it shows up as a notification - is not assigned to a property new ValidationResult("Could not update member, the provider returned an error: " + ex.Message + " (see log for full details)"), "default"); diff --git a/src/Umbraco.Web/Editors/PackageInstallController.cs b/src/Umbraco.Web/Editors/PackageInstallController.cs index 86b763b63b..b3bee3d72e 100644 --- a/src/Umbraco.Web/Editors/PackageInstallController.cs +++ b/src/Umbraco.Web/Editors/PackageInstallController.cs @@ -170,7 +170,7 @@ namespace Umbraco.Web.Editors var actionsXml = new XmlDocument(); actionsXml.LoadXml("" + pack.Data.Actions + ""); - LogHelper.Debug("executing undo actions: {0}", () => actionsXml.OuterXml); + Logger.Debug("executing undo actions: {0}", () => actionsXml.OuterXml); foreach (XmlNode n in actionsXml.DocumentElement.SelectNodes("//Action")) { @@ -181,13 +181,13 @@ namespace Umbraco.Web.Editors } catch (Exception ex) { - LogHelper.Error("An error occurred running undo actions", ex); + Logger.Error("An error occurred running undo actions", ex); } } } catch (Exception ex) { - LogHelper.Error("An error occurred running undo actions", ex); + Logger.Error("An error occurred running undo actions", ex); } } diff --git a/src/Umbraco.Web/HealthCheck/Checks/Config/ConfigurationService.cs b/src/Umbraco.Web/HealthCheck/Checks/Config/ConfigurationService.cs index fc3ae2b2bd..a6c6ad0e7c 100644 --- a/src/Umbraco.Web/HealthCheck/Checks/Config/ConfigurationService.cs +++ b/src/Umbraco.Web/HealthCheck/Checks/Config/ConfigurationService.cs @@ -57,7 +57,7 @@ namespace Umbraco.Web.HealthCheck.Checks.Config } catch (Exception exception) { - LogHelper.Error("Error trying to get configuration value", exception); + Current.Logger.Error("Error trying to get configuration value", exception); return new ConfigurationServiceResult { Success = false, @@ -103,7 +103,7 @@ namespace Umbraco.Web.HealthCheck.Checks.Config } catch (Exception exception) { - LogHelper.Error("Error trying to update configuration", exception); + Current.Logger.Error("Error trying to update configuration", exception); return new ConfigurationServiceResult { Success = false, diff --git a/src/Umbraco.Web/ImageCropperBaseExtensions.cs b/src/Umbraco.Web/ImageCropperBaseExtensions.cs index e993559f1e..394305e03b 100644 --- a/src/Umbraco.Web/ImageCropperBaseExtensions.cs +++ b/src/Umbraco.Web/ImageCropperBaseExtensions.cs @@ -28,7 +28,7 @@ namespace Umbraco.Web } catch (Exception ex) { - LogHelper.Error(typeof(ImageCropperBaseExtensions), "Could not parse the json string: " + json, ex); + Current.Logger.Error(typeof(ImageCropperBaseExtensions), "Could not parse the json string: " + json, ex); } } diff --git a/src/Umbraco.Web/Install/Controllers/InstallApiController.cs b/src/Umbraco.Web/Install/Controllers/InstallApiController.cs index 1d5a277f50..65792dc8e4 100644 --- a/src/Umbraco.Web/Install/Controllers/InstallApiController.cs +++ b/src/Umbraco.Web/Install/Controllers/InstallApiController.cs @@ -129,7 +129,7 @@ namespace Umbraco.Web.Install.Controllers catch (Exception ex) { - LogHelper.Error("An error occurred during installation step " + step.Name, ex); + _logger.Error("An error occurred during installation step " + step.Name, ex); if (ex is TargetInvocationException && ex.InnerException != null) { @@ -219,7 +219,7 @@ namespace Umbraco.Web.Install.Controllers } catch (Exception ex) { - LogHelper.Error("Checking if step requires execution (" + step.Name + ") failed.", ex); + _logger.Error("Checking if step requires execution (" + step.Name + ") failed.", ex); throw; } } @@ -240,7 +240,7 @@ namespace Umbraco.Web.Install.Controllers } catch (Exception ex) { - LogHelper.Error("Installation step " + step.Name + " failed.", ex); + _logger.Error("Installation step " + step.Name + " failed.", ex); throw; } } diff --git a/src/Umbraco.Web/Install/InstallHelper.cs b/src/Umbraco.Web/Install/InstallHelper.cs index 3cfcf5acc4..53b06981e1 100644 --- a/src/Umbraco.Web/Install/InstallHelper.cs +++ b/src/Umbraco.Web/Install/InstallHelper.cs @@ -49,8 +49,8 @@ namespace Umbraco.Web.Install new MajorVersion7UpgradeReport(Current.DatabaseContext, Current.RuntimeState), new Version73FileCleanup(_httpContext, _logger), new DatabaseConfigureStep(Current.DatabaseContext), - new DatabaseInstallStep(Current.DatabaseContext, Current.RuntimeState), - new DatabaseUpgradeStep(Current.DatabaseContext, Current.Services.MigrationEntryService, Current.RuntimeState, Current.MigrationCollectionBuilder), + new DatabaseInstallStep(Current.DatabaseContext, Current.RuntimeState, Current.Logger), + new DatabaseUpgradeStep(Current.DatabaseContext, Current.Services.MigrationEntryService, Current.RuntimeState, Current.MigrationCollectionBuilder, Current.Logger), new StarterKitDownloadStep(Current.Services.ContentService, this), new StarterKitInstallStep(_httpContext), new StarterKitCleanupStep(), @@ -141,7 +141,7 @@ namespace Umbraco.Web.Install } catch (Exception ex) { - LogHelper.Error("An error occurred in InstallStatus trying to check upgrades", ex); + Current.Logger.Error("An error occurred in InstallStatus trying to check upgrades", ex); } } @@ -230,7 +230,7 @@ namespace Umbraco.Web.Install } catch (AggregateException ex) { - LogHelper.Error("Could not download list of available starter kits", ex); + Current.Logger.Error("Could not download list of available starter kits", ex); } return packages; diff --git a/src/Umbraco.Web/Install/InstallSteps/DatabaseInstallStep.cs b/src/Umbraco.Web/Install/InstallSteps/DatabaseInstallStep.cs index 161341ce75..56c690ff57 100644 --- a/src/Umbraco.Web/Install/InstallSteps/DatabaseInstallStep.cs +++ b/src/Umbraco.Web/Install/InstallSteps/DatabaseInstallStep.cs @@ -14,11 +14,13 @@ namespace Umbraco.Web.Install.InstallSteps { private readonly DatabaseContext _databaseContext; private readonly IRuntimeState _runtime; + private readonly ILogger _logger; - public DatabaseInstallStep(DatabaseContext databaseContext, IRuntimeState runtime) + public DatabaseInstallStep(DatabaseContext databaseContext, IRuntimeState runtime, ILogger logger) { _databaseContext = databaseContext; _runtime = runtime; + _logger = logger; } public override InstallSetupResult Execute(object model) @@ -35,7 +37,7 @@ namespace Umbraco.Web.Install.InstallSteps if (result.RequiresUpgrade == false) { - HandleConnectionStrings(); + HandleConnectionStrings(_logger); return null; } @@ -46,7 +48,7 @@ namespace Umbraco.Web.Install.InstallSteps }); } - internal static void HandleConnectionStrings() + internal static void HandleConnectionStrings(ILogger logger) { // Remove legacy umbracoDbDsn configuration setting if it exists and connectionstring also exists if (ConfigurationManager.ConnectionStrings[GlobalSettings.UmbracoConnectionName] != null) @@ -56,7 +58,7 @@ namespace Umbraco.Web.Install.InstallSteps else { var ex = new ArgumentNullException(string.Format("ConfigurationManager.ConnectionStrings[{0}]", GlobalSettings.UmbracoConnectionName), "Install / upgrade did not complete successfully, umbracoDbDSN was not set in the connectionStrings section"); - LogHelper.Error("", ex); + logger.Error("", ex); throw ex; } } diff --git a/src/Umbraco.Web/Install/InstallSteps/DatabaseUpgradeStep.cs b/src/Umbraco.Web/Install/InstallSteps/DatabaseUpgradeStep.cs index f7d7a2b692..ac2326b42f 100644 --- a/src/Umbraco.Web/Install/InstallSteps/DatabaseUpgradeStep.cs +++ b/src/Umbraco.Web/Install/InstallSteps/DatabaseUpgradeStep.cs @@ -18,14 +18,16 @@ namespace Umbraco.Web.Install.InstallSteps private readonly DatabaseContext _databaseContext; private readonly IMigrationEntryService _migrationEntryService; private readonly IRuntimeState _runtime; + private readonly ILogger _logger; private readonly MigrationCollectionBuilder _migrationCollectionBuilder; - public DatabaseUpgradeStep(DatabaseContext databaseContext, IMigrationEntryService migrationEntryService, IRuntimeState runtime, MigrationCollectionBuilder migrationCollectionBuilder) + public DatabaseUpgradeStep(DatabaseContext databaseContext, IMigrationEntryService migrationEntryService, IRuntimeState runtime, MigrationCollectionBuilder migrationCollectionBuilder, ILogger logger) { _databaseContext = databaseContext; _migrationEntryService = migrationEntryService; _runtime = runtime; _migrationCollectionBuilder = migrationCollectionBuilder; + _logger = logger; } public override InstallSetupResult Execute(object model) @@ -36,7 +38,7 @@ namespace Umbraco.Web.Install.InstallSteps if (upgrade) { - LogHelper.Info("Running 'Upgrade' service"); + _logger.Info("Running 'Upgrade' service"); var result = _databaseContext.UpgradeSchemaAndData(_migrationEntryService, _migrationCollectionBuilder); @@ -45,7 +47,7 @@ namespace Umbraco.Web.Install.InstallSteps throw new InstallException("The database failed to upgrade. ERROR: " + result.Message); } - DatabaseInstallStep.HandleConnectionStrings(); + DatabaseInstallStep.HandleConnectionStrings(_logger); } return null; diff --git a/src/Umbraco.Web/Macros/MacroRenderer.cs b/src/Umbraco.Web/Macros/MacroRenderer.cs index 5ae5ec2bb8..4bef75e7bb 100644 --- a/src/Umbraco.Web/Macros/MacroRenderer.cs +++ b/src/Umbraco.Web/Macros/MacroRenderer.cs @@ -100,7 +100,7 @@ namespace Umbraco.Web.Macros if (macroContent == null) return null; - LogHelper.Debug("Macro content loaded from cache \"{0}\".", () => model.CacheIdentifier); + Current.Logger.Debug("Macro content loaded from cache \"{0}\".", () => model.CacheIdentifier); // ensure that the source has not changed // note: does not handle dependencies, and never has @@ -109,13 +109,13 @@ namespace Umbraco.Web.Macros { if (macroSource.Exists == false) { - LogHelper.Debug("Macro source does not exist anymore, ignore cache."); + Current.Logger.Debug("Macro source does not exist anymore, ignore cache."); return null; } if (macroContent.Date < macroSource.LastWriteTime) { - LogHelper.Debug("Macro source has changed, ignore cache."); + Current.Logger.Debug("Macro source has changed, ignore cache."); return null; } } @@ -165,7 +165,7 @@ namespace Umbraco.Web.Macros priority: CacheItemPriority.NotRemovable ); - LogHelper.Debug("Macro content saved to cache \"{0}\".", () => model.CacheIdentifier); + Current.Logger.Debug("Macro content saved to cache \"{0}\".", () => model.CacheIdentifier); } // gets the macro source file name @@ -322,7 +322,7 @@ namespace Umbraco.Web.Macros { Exceptions.Add(e); - _plogger.Logger.WarnWithException("Failed " + msgIn, e); + _plogger.Logger.Warn(e, "Failed " + msgIn); var macroErrorEventArgs = new MacroErrorEventArgs { diff --git a/src/Umbraco.Web/Macros/UserControlMacroEngine.cs b/src/Umbraco.Web/Macros/UserControlMacroEngine.cs index c43a7b7da3..aba5abc02f 100644 --- a/src/Umbraco.Web/Macros/UserControlMacroEngine.cs +++ b/src/Umbraco.Web/Macros/UserControlMacroEngine.cs @@ -30,7 +30,7 @@ namespace Umbraco.Web.Macros // note: we are not setting the 'CurrentNode' property on the control anymore, // as that was an INode which is gone in v8. Use UmbracoContext to access the // current content. - LogHelper.Info($"Loaded control \"{filename}\" with ID \"{control.ID}\"."); + Current.Logger.Info($"Loaded control \"{filename}\" with ID \"{control.ID}\"."); UpdateControlProperties(control, model); return new MacroContent { Control = control }; @@ -63,7 +63,7 @@ namespace Umbraco.Web.Macros var controlProperty = type.GetProperty(modelProperty.Key); if (controlProperty == null) { - LogHelper.Warn($"Control property \"{modelProperty.Key}\" doesn't exist or isn't accessible, skip."); + Current.Logger.Warn($"Control property \"{modelProperty.Key}\" doesn't exist or isn't accessible, skip."); continue; } @@ -73,16 +73,16 @@ namespace Umbraco.Web.Macros try { controlProperty.SetValue(control, tryConvert.Result, null); - LogHelper.Debug($"Set property \"{modelProperty.Key}\" value \"{modelProperty.Value}\"."); + Current.Logger.Debug($"Set property \"{modelProperty.Key}\" value \"{modelProperty.Value}\"."); } catch (Exception e) { - LogHelper.WarnWithException($"Failed to set property \"{modelProperty.Key}\" value \"{modelProperty.Value}\".", e); + Current.Logger.Warn(e, $"Failed to set property \"{modelProperty.Key}\" value \"{modelProperty.Value}\"."); } } else { - LogHelper.Warn($"Failed to set property \"{modelProperty.Key}\" value \"{modelProperty.Value}\"."); + Current.Logger.Warn($"Failed to set property \"{modelProperty.Key}\" value \"{modelProperty.Value}\"."); } } } diff --git a/src/Umbraco.Web/Macros/XsltMacroEngine.cs b/src/Umbraco.Web/Macros/XsltMacroEngine.cs index 6b682c266f..539c270354 100644 --- a/src/Umbraco.Web/Macros/XsltMacroEngine.cs +++ b/src/Umbraco.Web/Macros/XsltMacroEngine.cs @@ -61,13 +61,13 @@ namespace Umbraco.Web.Macros if (hasXslt == false && hasCode == false) { - LogHelper.Warn("Xslt is empty"); + Current.Logger.Warn("Xslt is empty"); return MacroContent.Empty; } if (hasCode && model.ScriptLanguage.InvariantEquals("xslt") == false) { - LogHelper.Warn("Unsupported script language \"" + model.ScriptLanguage + "\"."); + Current.Logger.Warn("Unsupported script language \"" + model.ScriptLanguage + "\"."); return MacroContent.Empty; } @@ -304,7 +304,7 @@ namespace Umbraco.Web.Macros // if no value is passed, then use the current "pageID" as value var contentId = macroPropertyValue == string.Empty ? UmbracoContext.Current.PageId.ToString() : macroPropertyValue; - LogHelper.Info($"Xslt node adding search start ({macroPropertyAlias},{macroPropertyValue})"); + Current.Logger.Info($"Xslt node adding search start ({macroPropertyAlias},{macroPropertyValue})"); switch (macroPropertyType) { @@ -368,10 +368,10 @@ namespace Umbraco.Web.Macros macroXmlNode.AppendChild(node); } else - LogHelper.Warn("Error adding random node - parent (" + macroPropertyValue + ") doesn't have children!"); + Current.Logger.Warn("Error adding random node - parent (" + macroPropertyValue + ") doesn't have children!"); } else - LogHelper.Warn("Error adding random node - parent (" + macroPropertyValue + ") doesn't exists!"); + Current.Logger.Warn("Error adding random node - parent (" + macroPropertyValue + ") doesn't exists!"); break; case "mediaCurrent": @@ -401,7 +401,7 @@ namespace Umbraco.Web.Macros // if no value is passed, then use the current "pageID" as value var contentId = macroPropertyValue == string.Empty ? UmbracoContext.Current.PageId.ToString() : macroPropertyValue; - LogHelper.Info($"Xslt node adding search start ({macroPropertyAlias},{macroPropertyValue})"); + Current.Logger.Info($"Xslt node adding search start ({macroPropertyAlias},{macroPropertyValue})"); // beware! do not use the raw content- or media- navigators, but clones !! @@ -463,10 +463,10 @@ namespace Umbraco.Web.Macros throw new InvalidOperationException("Iterator contains non-INavigableContent elements."); } else - LogHelper.Warn("Error adding random node - parent (" + macroPropertyValue + ") doesn't have children!"); + Current.Logger.Warn("Error adding random node - parent (" + macroPropertyValue + ") doesn't have children!"); } else - LogHelper.Warn("Error adding random node - parent (" + macroPropertyValue + ") doesn't exists!"); + Current.Logger.Warn("Error adding random node - parent (" + macroPropertyValue + ") doesn't exists!"); break; case "mediaCurrent": @@ -582,7 +582,7 @@ namespace Umbraco.Web.Macros { var extensionNamespace = "urn:" + extension.Key; xslArgs.AddExtensionObject(extensionNamespace, extension.Value); - LogHelper.Info($"Extension added: {extensionNamespace}, {extension.Value.GetType().Name}"); + Current.Logger.Info($"Extension added: {extensionNamespace}, {extension.Value.GetType().Name}"); } return xslArgs; diff --git a/src/Umbraco.Web/Models/Mapping/ContentPropertyBasicConverter.cs b/src/Umbraco.Web/Models/Mapping/ContentPropertyBasicConverter.cs index d944c48f48..82543f2620 100644 --- a/src/Umbraco.Web/Models/Mapping/ContentPropertyBasicConverter.cs +++ b/src/Umbraco.Web/Models/Mapping/ContentPropertyBasicConverter.cs @@ -33,7 +33,7 @@ namespace Umbraco.Web.Models.Mapping var editor = Current.PropertyEditors[property.PropertyType.PropertyEditorAlias]; if (editor == null) { - LogHelper.Error>( + Current.Logger.Error>( "No property editor found, converting to a Label", new NullReferenceException("The property editor with alias " + property.PropertyType.PropertyEditorAlias + " does not exist")); diff --git a/src/Umbraco.Web/Models/Mapping/MacroModelMapper.cs b/src/Umbraco.Web/Models/Mapping/MacroModelMapper.cs index c4807e9a01..fd5bf1e371 100644 --- a/src/Umbraco.Web/Models/Mapping/MacroModelMapper.cs +++ b/src/Umbraco.Web/Models/Mapping/MacroModelMapper.cs @@ -40,7 +40,7 @@ namespace Umbraco.Web.Models.Mapping { //we'll just map this to a text box paramEditor = Current.ParameterEditors[Constants.PropertyEditors.TextboxAlias]; - LogHelper.Warn("Could not resolve a parameter editor with alias " + property.EditorAlias + ", a textbox will be rendered in it's place"); + Current.Logger.Warn("Could not resolve a parameter editor with alias " + property.EditorAlias + ", a textbox will be rendered in it's place"); } parameter.View = paramEditor.ValueEditor.View; diff --git a/src/Umbraco.Web/Models/Mapping/PreValueDisplayResolver.cs b/src/Umbraco.Web/Models/Mapping/PreValueDisplayResolver.cs index 9b50daaf55..c96e5fbebc 100644 --- a/src/Umbraco.Web/Models/Mapping/PreValueDisplayResolver.cs +++ b/src/Umbraco.Web/Models/Mapping/PreValueDisplayResolver.cs @@ -35,7 +35,7 @@ namespace Umbraco.Web.Models.Mapping var found = preValues.Any(x => x.Key.InvariantEquals(field.Key)); if (found == false) { - LogHelper.Warn("Could not find persisted pre-value for field " + field.Key); + Current.Logger.Warn("Could not find persisted pre-value for field " + field.Key); continue; } field.Value = preValues.Single(x => x.Key.InvariantEquals(field.Key)).Value; diff --git a/src/Umbraco.Web/Mvc/AdminTokenAuthorizeAttribute.cs b/src/Umbraco.Web/Mvc/AdminTokenAuthorizeAttribute.cs index 8b06f2aadf..c68fda38d4 100644 --- a/src/Umbraco.Web/Mvc/AdminTokenAuthorizeAttribute.cs +++ b/src/Umbraco.Web/Mvc/AdminTokenAuthorizeAttribute.cs @@ -18,11 +18,14 @@ namespace Umbraco.Web.Mvc // see note in HttpInstallAuthorizeAttribute private readonly IUserService _userService; private readonly IRuntimeState _runtimeState; + private readonly ILogger _logger; private IUserService UserService => _userService ?? Current.Services.UserService; private IRuntimeState RuntimeState => _runtimeState ?? Current.RuntimeState; + private ILogger Logger => _logger ?? Current.Logger; + /// /// THIS SHOULD BE ONLY USED FOR UNIT TESTS /// @@ -115,7 +118,7 @@ namespace Umbraco.Web.Mvc } catch (Exception ex) { - LogHelper.Error("Failed to format passed in token value", ex); + Logger.Error("Failed to format passed in token value", ex); return false; } } diff --git a/src/Umbraco.Web/Mvc/RenderMvcController.cs b/src/Umbraco.Web/Mvc/RenderMvcController.cs index 055a6aedf5..afc8a76ac1 100644 --- a/src/Umbraco.Web/Mvc/RenderMvcController.cs +++ b/src/Umbraco.Web/Mvc/RenderMvcController.cs @@ -60,7 +60,7 @@ namespace Umbraco.Web.Mvc var result = ViewEngines.Engines.FindView(ControllerContext, template, null); if (result.View != null) return true; - LogHelper.Warn("No physical template file was found for template " + template); + Logger.Warn("No physical template file was found for template " + template); return false; } diff --git a/src/Umbraco.Web/Mvc/RenderRouteHandler.cs b/src/Umbraco.Web/Mvc/RenderRouteHandler.cs index 251eb541b0..74a9add44e 100644 --- a/src/Umbraco.Web/Mvc/RenderRouteHandler.cs +++ b/src/Umbraco.Web/Mvc/RenderRouteHandler.cs @@ -154,7 +154,7 @@ namespace Umbraco.Web.Mvc } catch (FormatException) { - LogHelper.Warn("A value was detected in the ufprt parameter but Umbraco could not decrypt the string"); + Current.Logger.Warn("A value was detected in the ufprt parameter but Umbraco could not decrypt the string"); return null; } @@ -325,7 +325,7 @@ namespace Umbraco.Web.Mvc } else { - LogHelper.Warn( + Current.Logger.Warn( "The current Document Type {0} matches a locally declared controller of type {1}. Custom Controllers for Umbraco routing must implement '{2}' and inherit from '{3}'.", () => publishedContentRequest.PublishedContent.DocumentTypeAlias, () => controllerType.FullName, @@ -405,7 +405,7 @@ namespace Umbraco.Web.Mvc // HandleHttpResponseStatus returns a value indicating that the request should // not be processed any further, eg because it has been redirect. then, exit. - if (UmbracoModule.HandleHttpResponseStatus(requestContext.HttpContext, publishedContentRequest)) + if (UmbracoModule.HandleHttpResponseStatus(requestContext.HttpContext, publishedContentRequest, Current.Logger)) return null; var handler = GetHandlerOnMissingTemplate(publishedContentRequest); diff --git a/src/Umbraco.Web/NotificationServiceExtensions.cs b/src/Umbraco.Web/NotificationServiceExtensions.cs index a5e4434f3b..af51fe7aab 100644 --- a/src/Umbraco.Web/NotificationServiceExtensions.cs +++ b/src/Umbraco.Web/NotificationServiceExtensions.cs @@ -21,7 +21,7 @@ namespace Umbraco.Web { if (Current.UmbracoContext == null) { - LogHelper.Warn(typeof(NotificationServiceExtensions), "Cannot send notifications, there is no current UmbracoContext"); + Current.Logger.Warn(typeof(NotificationServiceExtensions), "Cannot send notifications, there is no current UmbracoContext"); return; } service.SendNotification(entity, action, Current.UmbracoContext); @@ -31,7 +31,7 @@ namespace Umbraco.Web { if (Current.UmbracoContext == null) { - LogHelper.Warn(typeof(NotificationServiceExtensions), "Cannot send notifications, there is no current UmbracoContext"); + Current.Logger.Warn(typeof(NotificationServiceExtensions), "Cannot send notifications, there is no current UmbracoContext"); return; } service.SendNotification(entities, action, Current.UmbracoContext); @@ -41,7 +41,7 @@ namespace Umbraco.Web //{ // if (umbracoContext == null) // { - // LogHelper.Warn(typeof(NotificationServiceExtensions), "Cannot send notifications, there is no current UmbracoContext"); + // Current.Logger.Warn(typeof(NotificationServiceExtensions), "Cannot send notifications, there is no current UmbracoContext"); // return; // } // service.SendNotification(entity, action, umbracoContext); @@ -51,7 +51,7 @@ namespace Umbraco.Web //{ // if (umbracoContext == null) // { - // LogHelper.Warn(typeof(NotificationServiceExtensions), "Cannot send notifications, there is no current UmbracoContext"); + // Current.Logger.Warn(typeof(NotificationServiceExtensions), "Cannot send notifications, there is no current UmbracoContext"); // return; // } // service.SendNotification(entities, action, umbracoContext); @@ -61,7 +61,7 @@ namespace Umbraco.Web { if (umbracoContext == null) { - LogHelper.Warn(typeof(NotificationServiceExtensions), "Cannot send notifications, there is no current UmbracoContext"); + Current.Logger.Warn(typeof(NotificationServiceExtensions), "Cannot send notifications, there is no current UmbracoContext"); return; } @@ -71,11 +71,11 @@ namespace Umbraco.Web //if there is no current user, then use the admin if (user == null) { - LogHelper.Debug(typeof(NotificationServiceExtensions), "There is no current Umbraco user logged in, the notifications will be sent from the administrator"); + Current.Logger.Debug(typeof(NotificationServiceExtensions), "There is no current Umbraco user logged in, the notifications will be sent from the administrator"); user = userService.GetUserById(0); if (user == null) { - LogHelper.Warn(typeof(NotificationServiceExtensions), "Noticiations can not be sent, no admin user with id 0 could be resolved"); + Current.Logger.Warn(typeof(NotificationServiceExtensions), "Noticiations can not be sent, no admin user with id 0 could be resolved"); return; } } @@ -86,7 +86,7 @@ namespace Umbraco.Web { if (umbracoContext == null) { - LogHelper.Warn(typeof(NotificationServiceExtensions), "Cannot send notifications, there is no current UmbracoContext"); + Current.Logger.Warn(typeof(NotificationServiceExtensions), "Cannot send notifications, there is no current UmbracoContext"); return; } @@ -96,11 +96,11 @@ namespace Umbraco.Web //if there is no current user, then use the admin if (user == null) { - LogHelper.Debug(typeof(NotificationServiceExtensions), "There is no current Umbraco user logged in, the notifications will be sent from the administrator"); + Current.Logger.Debug(typeof(NotificationServiceExtensions), "There is no current Umbraco user logged in, the notifications will be sent from the administrator"); user = userService.GetUserById(0); if (user == null) { - LogHelper.Warn(typeof(NotificationServiceExtensions), "Noticiations can not be sent, no admin user with id 0 could be resolved"); + Current.Logger.Warn(typeof(NotificationServiceExtensions), "Noticiations can not be sent, no admin user with id 0 could be resolved"); return; } } diff --git a/src/Umbraco.Web/PropertyEditors/CheckBoxListPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/CheckBoxListPropertyEditor.cs index e1b72f0ad4..c7c99564f8 100644 --- a/src/Umbraco.Web/PropertyEditors/CheckBoxListPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/CheckBoxListPropertyEditor.cs @@ -35,7 +35,7 @@ namespace Umbraco.Web.PropertyEditors /// protected override PreValueEditor CreatePreValueEditor() { - return new ValueListPreValueEditor(_textService); + return new ValueListPreValueEditor(_textService, Logger); } /// diff --git a/src/Umbraco.Web/PropertyEditors/ColorListPreValueEditor.cs b/src/Umbraco.Web/PropertyEditors/ColorListPreValueEditor.cs index e9e721c108..a3473948c8 100644 --- a/src/Umbraco.Web/PropertyEditors/ColorListPreValueEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/ColorListPreValueEditor.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Text.RegularExpressions; using Newtonsoft.Json.Linq; using Umbraco.Core; +using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; @@ -13,7 +14,8 @@ namespace Umbraco.Web.PropertyEditors internal class ColorListPreValueEditor : ValueListPreValueEditor { - public ColorListPreValueEditor(ILocalizedTextService textService) : base(textService) + public ColorListPreValueEditor(ILocalizedTextService textService, ILogger logger) + : base(textService, logger) { var field = Fields.First(); diff --git a/src/Umbraco.Web/PropertyEditors/ColorPickerPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/ColorPickerPropertyEditor.cs index 3d2beb64fb..1f79d569ff 100644 --- a/src/Umbraco.Web/PropertyEditors/ColorPickerPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/ColorPickerPropertyEditor.cs @@ -27,7 +27,7 @@ namespace Umbraco.Web.PropertyEditors /// protected override PreValueEditor CreatePreValueEditor() { - return new ColorListPreValueEditor(_textService); + return new ColorListPreValueEditor(_textService, Logger); } } diff --git a/src/Umbraco.Web/PropertyEditors/DropDownMultipleWithKeysPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/DropDownMultipleWithKeysPropertyEditor.cs index f16d9872ec..392745cc95 100644 --- a/src/Umbraco.Web/PropertyEditors/DropDownMultipleWithKeysPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/DropDownMultipleWithKeysPropertyEditor.cs @@ -34,7 +34,7 @@ namespace Umbraco.Web.PropertyEditors protected override PreValueEditor CreatePreValueEditor() { - return new DropDownMultiplePreValueEditor(_textService); + return new DropDownMultiplePreValueEditor(_textService, Logger); } /// @@ -46,7 +46,8 @@ namespace Umbraco.Web.PropertyEditors /// internal class DropDownMultiplePreValueEditor : ValueListPreValueEditor { - public DropDownMultiplePreValueEditor(ILocalizedTextService textService) : base(textService) + public DropDownMultiplePreValueEditor(ILocalizedTextService textService, ILogger logger) + : base(textService, logger) { //add the multiple field, we'll make it hidden so it is not seen in the pre-value editor Fields.Add(new PreValueField diff --git a/src/Umbraco.Web/PropertyEditors/DropDownPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/DropDownPropertyEditor.cs index 51a4913b97..4da84a6454 100644 --- a/src/Umbraco.Web/PropertyEditors/DropDownPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/DropDownPropertyEditor.cs @@ -34,7 +34,7 @@ namespace Umbraco.Web.PropertyEditors /// protected override PropertyValueEditor CreateValueEditor() { - return new PublishValueValueEditor(base.CreateValueEditor()); + return new PublishValueValueEditor(base.CreateValueEditor(), Logger); } } diff --git a/src/Umbraco.Web/PropertyEditors/DropDownWithKeysPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/DropDownWithKeysPropertyEditor.cs index a6106836b7..604a3416c0 100644 --- a/src/Umbraco.Web/PropertyEditors/DropDownWithKeysPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/DropDownWithKeysPropertyEditor.cs @@ -32,7 +32,7 @@ namespace Umbraco.Web.PropertyEditors /// protected override PreValueEditor CreatePreValueEditor() { - return new ValueListPreValueEditor(_textService); + return new ValueListPreValueEditor(_textService, Logger); } } } \ No newline at end of file diff --git a/src/Umbraco.Web/PropertyEditors/FileUploadPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/FileUploadPropertyEditor.cs index 576ffb2887..0b9dca3882 100644 --- a/src/Umbraco.Web/PropertyEditors/FileUploadPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/FileUploadPropertyEditor.cs @@ -45,7 +45,7 @@ namespace Umbraco.Web.PropertyEditors protected override PreValueEditor CreatePreValueEditor() { - return new FileUploadPreValueEditor(_textService); + return new FileUploadPreValueEditor(_textService, Logger); } /// @@ -168,8 +168,8 @@ namespace Umbraco.Web.PropertyEditors /// internal class FileUploadPreValueEditor : ValueListPreValueEditor { - public FileUploadPreValueEditor(ILocalizedTextService textService) - : base(textService) + public FileUploadPreValueEditor(ILocalizedTextService textService, ILogger logger) + : base(textService, logger) { var field = Fields.First(); field.Description = "Enter a max width/height for each thumbnail"; diff --git a/src/Umbraco.Web/PropertyEditors/ImageCropperPropertyValueEditor.cs b/src/Umbraco.Web/PropertyEditors/ImageCropperPropertyValueEditor.cs index 1dcefe6c40..b65dc4f4d6 100644 --- a/src/Umbraco.Web/PropertyEditors/ImageCropperPropertyValueEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/ImageCropperPropertyValueEditor.cs @@ -87,7 +87,7 @@ namespace Umbraco.Web.PropertyEditors catch (Exception ex) { //for some reason the value is invalid so continue as if there was no value there - _logger.WarnWithException("Could not parse current db value to a JObject", ex); + _logger.Warn(ex, "Could not parse current db value to a JObject"); } if (oldJson != null && oldJson["src"] != null) diff --git a/src/Umbraco.Web/PropertyEditors/MultipleTextStringPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/MultipleTextStringPropertyEditor.cs index 6125d9fde6..7379c0b1b8 100644 --- a/src/Umbraco.Web/PropertyEditors/MultipleTextStringPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/MultipleTextStringPropertyEditor.cs @@ -1,7 +1,5 @@ using System; -using System.ComponentModel.DataAnnotations; using System.Linq; -using System.Collections; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -21,8 +19,7 @@ namespace Umbraco.Web.PropertyEditors /// The constructor will setup the property editor based on the attribute if one is found /// public MultipleTextStringPropertyEditor(ILogger logger) : base(logger) - { - } + { } protected override PropertyValueEditor CreateValueEditor() { @@ -31,7 +28,7 @@ namespace Umbraco.Web.PropertyEditors protected override PreValueEditor CreatePreValueEditor() { - return new MultipleTextStringPreValueEditor(); + return new MultipleTextStringPreValueEditor(Logger); } /// @@ -39,8 +36,11 @@ namespace Umbraco.Web.PropertyEditors /// internal class MultipleTextStringPreValueEditor : PreValueEditor { - public MultipleTextStringPreValueEditor() + private readonly ILogger _logger; + + public MultipleTextStringPreValueEditor(ILogger logger) { + _logger = logger; //create the fields Fields.Add(new PreValueField(new IntegerValidator()) { @@ -103,8 +103,8 @@ namespace Umbraco.Web.PropertyEditors } catch (Exception e) { - //this shouldn't happen unless there's already a bad formatted pre-value - LogHelper.WarnWithException("Could not deserialize value to json " + stringVal, e); + // this shouldn't happen unless there's already a bad formatted pre-value + _logger.Warn(e, "Could not deserialize value to json " + stringVal); return returnVal; } } diff --git a/src/Umbraco.Web/PropertyEditors/PublishValueValueEditor.cs b/src/Umbraco.Web/PropertyEditors/PublishValueValueEditor.cs index 1024fa968f..5e83f54487 100644 --- a/src/Umbraco.Web/PropertyEditors/PublishValueValueEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/PublishValueValueEditor.cs @@ -18,15 +18,17 @@ namespace Umbraco.Web.PropertyEditors internal class PublishValueValueEditor : PropertyValueEditorWrapper { private readonly IDataTypeService _dataTypeService; + private readonly ILogger _logger; - internal PublishValueValueEditor(IDataTypeService dataTypeService, PropertyValueEditor wrapped) + internal PublishValueValueEditor(IDataTypeService dataTypeService, PropertyValueEditor wrapped, ILogger logger) : base(wrapped) { _dataTypeService = dataTypeService; + _logger = logger; } - public PublishValueValueEditor(PropertyValueEditor wrapped) - : this(Current.Services.DataTypeService, wrapped) + public PublishValueValueEditor(PropertyValueEditor wrapped, ILogger logger) + : this(Current.Services.DataTypeService, wrapped, logger) { } @@ -54,7 +56,7 @@ namespace Umbraco.Web.PropertyEditors return preVals.Single(x => x.Value.Id == preValId).Value.Value; } - LogHelper.Warn("Could not find a pre value with ID " + preValId + " for property alias " + property.Alias); + _logger.Warn("Could not find a pre value with ID " + preValId + " for property alias " + property.Alias); } } diff --git a/src/Umbraco.Web/PropertyEditors/PublishValuesMultipleValueEditor.cs b/src/Umbraco.Web/PropertyEditors/PublishValuesMultipleValueEditor.cs index fe3dcfc5ef..edcc90cf8e 100644 --- a/src/Umbraco.Web/PropertyEditors/PublishValuesMultipleValueEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/PublishValuesMultipleValueEditor.cs @@ -2,6 +2,7 @@ using System; using System.Linq; using Newtonsoft.Json.Linq; using Umbraco.Core; +using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; @@ -19,16 +20,15 @@ namespace Umbraco.Web.PropertyEditors { private readonly bool _publishIds; - internal PublishValuesMultipleValueEditor(bool publishIds, IDataTypeService dataTypeService, PropertyValueEditor wrapped) - : base(dataTypeService, wrapped) + internal PublishValuesMultipleValueEditor(bool publishIds, IDataTypeService dataTypeService, ILogger logger, PropertyValueEditor wrapped) + : base(dataTypeService, wrapped, logger) { _publishIds = publishIds; } public PublishValuesMultipleValueEditor(bool publishIds, PropertyValueEditor wrapped) - : this(publishIds, Current.Services.DataTypeService, wrapped) - { - } + : this(publishIds, Current.Services.DataTypeService, Current.Logger, wrapped) + { } /// /// If publishing ids, we don't need to do anything, otherwise we need to look up the pre-values and get the string values diff --git a/src/Umbraco.Web/PropertyEditors/RteEmbedController.cs b/src/Umbraco.Web/PropertyEditors/RteEmbedController.cs index 744511dbc5..25ff1324d5 100644 --- a/src/Umbraco.Web/PropertyEditors/RteEmbedController.cs +++ b/src/Umbraco.Web/PropertyEditors/RteEmbedController.cs @@ -62,7 +62,7 @@ namespace Umbraco.Web.PropertyEditors } catch(Exception ex) { - LogHelper.Error(string.Format("Error embedding url {0} - width: {1} height: {2}", url, width, height), ex); + Logger.Error(string.Format("Error embedding url {0} - width: {1} height: {2}", url, width, height), ex); result.Status = Status.Error; } diff --git a/src/Umbraco.Web/PropertyEditors/ValueConverters/RelatedLinksEditorValueConvertor.cs b/src/Umbraco.Web/PropertyEditors/ValueConverters/RelatedLinksEditorValueConvertor.cs index 2f08b27dc6..36c09cb075 100644 --- a/src/Umbraco.Web/PropertyEditors/ValueConverters/RelatedLinksEditorValueConvertor.cs +++ b/src/Umbraco.Web/PropertyEditors/ValueConverters/RelatedLinksEditorValueConvertor.cs @@ -19,12 +19,14 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters private readonly IUmbracoContextAccessor _umbracoContextAccessor; private readonly ServiceContext _services; private readonly CacheHelper _appCache; + private readonly ILogger _logger; - public RelatedLinksEditorValueConvertor(IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, CacheHelper appCache) + public RelatedLinksEditorValueConvertor(IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, CacheHelper appCache, ILogger logger) { _umbracoContextAccessor = umbracoContextAccessor; _services = services; _appCache = appCache; + _logger = logger; } public override bool IsConverter(PublishedPropertyType propertyType) @@ -72,7 +74,7 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters } catch (Exception ex) { - LogHelper.Error("Could not parse the string " + sourceString + " to a json object", ex); + _logger.Error("Could not parse the string " + sourceString + " to a json object", ex); } } @@ -111,7 +113,7 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters } catch (Exception ex) { - LogHelper.Error("Could not parse the string " + sourceString + " to a json object", ex); + _logger.Error("Could not parse the string " + sourceString + " to a json object", ex); } } diff --git a/src/Umbraco.Web/PropertyEditors/ValueListPreValueEditor.cs b/src/Umbraco.Web/PropertyEditors/ValueListPreValueEditor.cs index e11a969bfe..d57e237fa9 100644 --- a/src/Umbraco.Web/PropertyEditors/ValueListPreValueEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/ValueListPreValueEditor.cs @@ -23,10 +23,12 @@ namespace Umbraco.Web.PropertyEditors internal class ValueListPreValueEditor : PreValueEditor { private readonly ILocalizedTextService _textService; + private readonly ILogger _logger; - public ValueListPreValueEditor(ILocalizedTextService textService) + public ValueListPreValueEditor(ILocalizedTextService textService, ILogger logger) { _textService = textService; + _logger = logger; Fields.AddRange(CreatePreValueFields()); } @@ -127,7 +129,7 @@ namespace Umbraco.Web.PropertyEditors } catch (Exception ex) { - LogHelper.Error("Could not deserialize the posted value: " + val, ex); + _logger.Error("Could not deserialize the posted value: " + val, ex); } return result; diff --git a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/Database.cs b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/Database.cs index 9b9e6eb5ac..eec84c4f0d 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/Database.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/Database.cs @@ -195,7 +195,7 @@ ORDER BY n.level, n.sortOrder if (dto.DraftData == null) { //throw new Exception("Missing cmsContentNu content for node " + dto.Id + ", consider rebuilding."); - LogHelper.Warn("Missing cmsContentNu content for node " + dto.Id + ", consider rebuilding."); + Current.Logger.Warn("Missing cmsContentNu content for node " + dto.Id + ", consider rebuilding."); } else { @@ -217,7 +217,7 @@ ORDER BY n.level, n.sortOrder if (dto.PubData == null) { //throw new Exception("Missing cmsContentNu content for node " + dto.Id + ", consider rebuilding."); - LogHelper.Warn("Missing cmsContentNu content for node " + dto.Id + ", consider rebuilding."); + Current.Logger.Warn("Missing cmsContentNu content for node " + dto.Id + ", consider rebuilding."); } else { diff --git a/src/Umbraco.Web/PublishedCache/NuCache/FacadeService.cs b/src/Umbraco.Web/PublishedCache/NuCache/FacadeService.cs index e5d5d7fa2a..8b19f5a865 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/FacadeService.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/FacadeService.cs @@ -676,7 +676,7 @@ namespace Umbraco.Web.PublishedCache.NuCache return; foreach (var payload in payloads) - LogHelper.Debug($"Notified {payload.ChangeTypes} for {payload.ItemType} {payload.Id}"); + _logger.Debug($"Notified {payload.ChangeTypes} for {payload.ItemType} {payload.Id}"); var removedIds = payloads .Where(x => x.ItemType == typeof(IContentType).Name && x.ChangeTypes.HasType(ContentTypeChangeTypes.Remove)) @@ -726,7 +726,7 @@ namespace Umbraco.Web.PublishedCache.NuCache var idsA = payloads.Select(x => x.Id).ToArray(); foreach (var payload in payloads) - LogHelper.Debug($"Notified {(payload.Removed ? "Removed" : "Refreshed")} for data type {payload.Id}"); + _logger.Debug($"Notified {(payload.Removed ? "Removed" : "Refreshed")} for data type {payload.Id}"); _contentStore.WriteLocked(() => _mediaStore.WriteLocked(() => @@ -936,7 +936,7 @@ namespace Umbraco.Web.PublishedCache.NuCache var facadeCache = _options.FacadeCacheIsApplicationRequestCache ? Current.ApplicationCache.RequestCache : new StaticCacheProvider(); // assuming that's OK for tests, etc - var memberTypeCache = new PublishedContentTypeCache(null, null, _serviceContext.MemberTypeService); + var memberTypeCache = new PublishedContentTypeCache(null, null, _serviceContext.MemberTypeService, _logger); var domainCache = new DomainCache(domainSnap); diff --git a/src/Umbraco.Web/PublishedCache/PublishedContentTypeCache.cs b/src/Umbraco.Web/PublishedCache/PublishedContentTypeCache.cs index 0f73ac95a7..ff38a6a9ed 100644 --- a/src/Umbraco.Web/PublishedCache/PublishedContentTypeCache.cs +++ b/src/Umbraco.Web/PublishedCache/PublishedContentTypeCache.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading; using Umbraco.Core; +using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Services; @@ -18,22 +19,26 @@ namespace Umbraco.Web.PublishedCache private readonly IContentTypeService _contentTypeService; private readonly IMediaTypeService _mediaTypeService; private readonly IMemberTypeService _memberTypeService; + public readonly ILogger _logger; private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); - internal PublishedContentTypeCache(IContentTypeService contentTypeService, IMediaTypeService mediaTypeService, IMemberTypeService memberTypeService) + internal PublishedContentTypeCache(IContentTypeService contentTypeService, IMediaTypeService mediaTypeService, IMemberTypeService memberTypeService, ILogger logger) { _contentTypeService = contentTypeService; _mediaTypeService = mediaTypeService; _memberTypeService = memberTypeService; + _logger = logger; } // for unit tests ONLY - internal PublishedContentTypeCache() - { } + internal PublishedContentTypeCache(ILogger logger) + { + _logger = logger; + } public void ClearAll() { - Core.Logging.LogHelper.Debug("Clear all."); + _logger.Debug("Clear all."); using (new WriteLock(_lock)) { @@ -44,7 +49,7 @@ namespace Umbraco.Web.PublishedCache public void ClearContentType(int id) { - Core.Logging.LogHelper.Debug("Clear content type w/id {0}.", () => id); + _logger.Debug("Clear content type w/id {0}.", () => id); using (var l = new UpgradeableReadLock(_lock)) { @@ -61,7 +66,7 @@ namespace Umbraco.Web.PublishedCache public void ClearDataType(int id) { - Core.Logging.LogHelper.Debug("Clear data type w/id {0}.", () => id); + _logger.Debug("Clear data type w/id {0}.", () => id); // there is no recursion to handle here because a PublishedContentType contains *all* its // properties ie both its own properties and those that were inherited (it's based upon an diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/FacadeService.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/FacadeService.cs index e94456310a..ed59952a0b 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/FacadeService.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/FacadeService.cs @@ -4,6 +4,7 @@ using System.Linq; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.IO; +using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Models.PublishedContent; @@ -37,9 +38,10 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache ICacheProvider requestCache, IEnumerable segmentProviders, IFacadeAccessor facadeAccessor, + ILogger logger, MainDom mainDom, bool testing = false, bool enableRepositoryEvents = true) - : this(serviceContext, uowProvider, requestCache, segmentProviders, facadeAccessor, null, mainDom, testing, enableRepositoryEvents) + : this(serviceContext, uowProvider, requestCache, segmentProviders, facadeAccessor, logger, null, mainDom, testing, enableRepositoryEvents) { } // used in some tests @@ -47,10 +49,11 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache IDatabaseUnitOfWorkProvider uowProvider, ICacheProvider requestCache, IFacadeAccessor facadeAccessor, + ILogger logger, PublishedContentTypeCache contentTypeCache, MainDom mainDom, bool testing, bool enableRepositoryEvents) - : this(serviceContext, uowProvider, requestCache, Enumerable.Empty(), facadeAccessor, contentTypeCache, mainDom, testing, enableRepositoryEvents) + : this(serviceContext, uowProvider, requestCache, Enumerable.Empty(), facadeAccessor, logger, contentTypeCache, mainDom, testing, enableRepositoryEvents) { } private FacadeService(ServiceContext serviceContext, @@ -58,6 +61,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache ICacheProvider requestCache, IEnumerable segmentProviders, IFacadeAccessor facadeAccessor, + ILogger logger, PublishedContentTypeCache contentTypeCache, MainDom mainDom, bool testing, bool enableRepositoryEvents) @@ -65,7 +69,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache { _routesCache = new RoutesCache(); _contentTypeCache = contentTypeCache - ?? new PublishedContentTypeCache(serviceContext.ContentTypeService, serviceContext.MediaTypeService, serviceContext.MemberTypeService); + ?? new PublishedContentTypeCache(serviceContext.ContentTypeService, serviceContext.MediaTypeService, serviceContext.MemberTypeService, logger); _xmlStore = new XmlStore(serviceContext, uowProvider, _routesCache, _contentTypeCache, segmentProviders, facadeAccessor, mainDom, testing, enableRepositoryEvents); diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PreviewContent.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PreviewContent.cs index 57dbbb4c36..5a42a8df1b 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PreviewContent.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PreviewContent.cs @@ -39,7 +39,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache } catch (Exception ex) { - LogHelper.Error($"Could not load preview set {_previewSet} for user {_userId}.", ex); + Current.Logger.Error($"Could not load preview set {_previewSet} for user {_userId}.", ex); ClearPreviewSet(); @@ -145,7 +145,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache } catch (Exception ex) { - LogHelper.Error($"Couldn't delete preview set {file.Name} for user {userId}", ex); + Current.Logger.Error($"Couldn't delete preview set {file.Name} for user {userId}", ex); } } diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs index ef091f42db..1202bb879f 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs @@ -210,13 +210,13 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache var indexer = eMgr.IndexProviderCollection["InternalIndexer"]; if (indexer.IndexerData.IncludeNodeTypes.Any() || indexer.IndexerData.ExcludeNodeTypes.Any()) { - LogHelper.Warn("The InternalIndexer for examine is configured incorrectly, it should not list any include/exclude node types or field names, it should simply be configured as: " + ""); + Current.Logger.Warn("The InternalIndexer for examine is configured incorrectly, it should not list any include/exclude node types or field names, it should simply be configured as: " + ""); } return indexer; } catch (Exception ex) { - LogHelper.Error("Could not retrieve the InternalIndexer", ex); + Current.Logger.Error("Could not retrieve the InternalIndexer", ex); //something didn't work, continue returning null. } return null; @@ -291,11 +291,11 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache //See this thread: http://examine.cdodeplex.com/discussions/264341 //Catch the exception here for the time being, and just fallback to GetMedia //TODO: Need to fix examine in LB scenarios! - LogHelper.Error("Could not load data from Examine index for media", ex); + Current.Logger.Error("Could not load data from Examine index for media", ex); } } - LogHelper.Warn( + Current.Logger.Warn( "Could not retrieve media {0} from Examine index, reverting to looking up media via legacy library.GetMedia method", () => id); @@ -312,7 +312,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache : ConvertFromXPathNavigator(media.Current); } - LogHelper.Warn( + Current.Logger.Warn( "Could not retrieve media {0} from Examine index or from legacy library.GetMedia method", () => id); @@ -665,7 +665,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache else { // this is a property that does not correspond to anything, ignore and log - LogHelper.Warn("Dropping property \"" + i.Key + "\" because it does not belong to the content type."); + Current.Logger.Warn("Dropping property \"" + i.Key + "\" because it does not belong to the content type."); } } } diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlCacheComponent.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlCacheComponent.cs index f823017ea2..a2d63fdb51 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlCacheComponent.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlCacheComponent.cs @@ -6,6 +6,7 @@ using Umbraco.Core.Persistence.UnitOfWork; using Umbraco.Core.Services; using Umbraco.Core.Strings; using Umbraco.Core.DependencyInjection; +using Umbraco.Core.Logging; using Umbraco.Web.HealthCheck; using Umbraco.Web.HealthCheck.Checks.DataIntegrity; @@ -25,6 +26,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache factory.GetInstance().RequestCache, factory.GetAllInstances(), factory.GetInstance(), + factory.GetInstance(), factory.GetInstance())); // add the Xml cache health check (hidden from type finder) diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlStore.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlStore.cs index 94cab16071..74cd28954b 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlStore.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlStore.cs @@ -289,8 +289,8 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache throw new Exception("Cannot run with both ContinouslyUpdateXmlDiskCache and XmlContentCheckForDiskChanges being true."); if (XmlIsImmutable == false) - //LogHelper.Warn("Running with CloneXmlContent being false is a bad idea."); - LogHelper.Warn("CloneXmlContent is false - ignored, we always clone."); + //Current.Logger.Warn("Running with CloneXmlContent being false is a bad idea."); + Current.Logger.Warn("CloneXmlContent is false - ignored, we always clone."); // note: if SyncFromXmlFile then we should also disable / warn that local edits are going to cause issues... } @@ -412,7 +412,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache } catch (Exception exception) { - LogHelper.Error("Failed to build a DTD for the Xml cache.", exception); + Current.Logger.Error("Failed to build a DTD for the Xml cache.", exception); } dtd.AppendLine("]>"); @@ -423,7 +423,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache // assumes xml lock (file is always locked) private void LoadXmlLocked(SafeXmlReaderWriter safeXml, out bool registerXmlChange) { - LogHelper.Debug("Loading Xml..."); + Current.Logger.Debug("Loading Xml..."); // try to get it from the file if (XmlFileEnabled && (safeXml.Xml = LoadXmlFromFile()) != null) @@ -736,7 +736,7 @@ AND (umbracoNode.id=@id)"; // (no need to test _released) internal void SaveXmlToFile() { - LogHelper.Info("Save Xml to file..."); + Current.Logger.Info("Save Xml to file..."); try { @@ -760,14 +760,14 @@ AND (umbracoNode.id=@id)"; fs.Write(bytes, 0, bytes.Length); } - LogHelper.Info("Saved Xml to file."); + Current.Logger.Info("Saved Xml to file."); } catch (Exception e) { // if something goes wrong remove the file DeleteXmlFile(); - LogHelper.Error("Failed to save Xml to file.", e); + Current.Logger.Error("Failed to save Xml to file.", e); } } @@ -776,7 +776,7 @@ AND (umbracoNode.id=@id)"; // (no need to test _released) internal async Task SaveXmlToFileAsync() { - LogHelper.Info("Save Xml to file..."); + Current.Logger.Info("Save Xml to file..."); try { @@ -800,14 +800,14 @@ AND (umbracoNode.id=@id)"; await fs.WriteAsync(bytes, 0, bytes.Length); } - LogHelper.Info("Saved Xml to file."); + Current.Logger.Info("Saved Xml to file."); } catch (Exception e) { // if something goes wrong remove the file DeleteXmlFile(); - LogHelper.Error("Failed to save Xml to file.", e); + Current.Logger.Error("Failed to save Xml to file.", e); } } @@ -844,7 +844,7 @@ AND (umbracoNode.id=@id)"; // do NOT try to load if we are not the main domain anymore if (_released) return null; - LogHelper.Info("Load Xml from file..."); + Current.Logger.Info("Load Xml from file..."); try { @@ -854,17 +854,17 @@ AND (umbracoNode.id=@id)"; xml.Load(fs); } _lastFileRead = DateTime.UtcNow; - LogHelper.Info("Loaded Xml from file."); + Current.Logger.Info("Loaded Xml from file."); return xml; } catch (FileNotFoundException) { - LogHelper.Warn("Failed to load Xml, file does not exist."); + Current.Logger.Warn("Failed to load Xml, file does not exist."); return null; } catch (Exception e) { - LogHelper.Error("Failed to load Xml from file.", e); + Current.Logger.Error("Failed to load Xml from file.", e); DeleteXmlFile(); return null; } @@ -888,7 +888,7 @@ AND (umbracoNode.id=@id)"; _nextFileCheck = now.AddSeconds(1); // check every 1s if (XmlFileLastWriteTime <= _lastFileRead) return; - LogHelper.Debug("Xml file change detected, reloading."); + Current.Logger.Debug("Xml file change detected, reloading."); // time to read @@ -1098,7 +1098,7 @@ ORDER BY umbracoNode.level, umbracoNode.sortOrder"; { foreach (var payload in payloads) { - LogHelper.Debug($"Notified {payload.ChangeTypes} for content {payload.Id}."); + Current.Logger.Debug($"Notified {payload.ChangeTypes} for content {payload.Id}."); if (payload.ChangeTypes.HasType(TreeChangeTypes.RefreshAll)) { @@ -1131,7 +1131,7 @@ ORDER BY umbracoNode.level, umbracoNode.sortOrder"; if (content == null || content.HasPublishedVersion == false || content.Trashed) { // no published version - LogHelper.Debug($"Notified, content {payload.Id} has no published version."); + Current.Logger.Debug($"Notified, content {payload.Id} has no published version."); if (current != null) { // remove from xml if exists @@ -1169,7 +1169,7 @@ ORDER BY umbracoNode.level, umbracoNode.sortOrder"; if (dtos.MoveNext() == false) { // gone fishing, remove (possible race condition) - LogHelper.Debug($"Notifified, content {payload.Id} gone fishing."); + Current.Logger.Debug($"Notifified, content {payload.Id} gone fishing."); if (current != null) { // remove from xml if exists @@ -1285,7 +1285,7 @@ ORDER BY umbracoNode.level, umbracoNode.sortOrder"; .ToArray(); foreach (var payload in payloads) - LogHelper.Debug($"Notified {payload.ChangeTypes} for content type {payload.Id}."); + Current.Logger.Debug($"Notified {payload.ChangeTypes} for content type {payload.Id}."); if (ids.Length > 0) // must have refreshes, not only removes RefreshContentTypes(ids); @@ -1306,7 +1306,7 @@ ORDER BY umbracoNode.level, umbracoNode.sortOrder"; _contentTypeCache.ClearDataType(payload.Id); foreach (var payload in payloads) - LogHelper.Debug($"Notified {(payload.Removed ? "Removed" : "Refreshed")} for data type {payload.Id}."); + Current.Logger.Debug($"Notified {(payload.Removed ? "Removed" : "Refreshed")} for data type {payload.Id}."); // that's all we need to do as the changes have NO impact whatsoever on the Xml content diff --git a/src/Umbraco.Web/Routing/ContentFinderByRedirectUrl.cs b/src/Umbraco.Web/Routing/ContentFinderByRedirectUrl.cs index e94e7369e2..0ad80e3ed0 100644 --- a/src/Umbraco.Web/Routing/ContentFinderByRedirectUrl.cs +++ b/src/Umbraco.Web/Routing/ContentFinderByRedirectUrl.cs @@ -14,10 +14,12 @@ namespace Umbraco.Web.Routing public class ContentFinderByRedirectUrl : IContentFinder { private readonly IRedirectUrlService _redirectUrlService; + private readonly ILogger _logger; - public ContentFinderByRedirectUrl(IRedirectUrlService redirectUrlService) + public ContentFinderByRedirectUrl(IRedirectUrlService redirectUrlService, ILogger logger) { _redirectUrlService = redirectUrlService; + _logger = logger; } /// @@ -36,7 +38,7 @@ namespace Umbraco.Web.Routing if (redirectUrl == null) { - LogHelper.Debug("No match for route: \"{0}\".", () => route); + _logger.Debug("No match for route: \"{0}\".", () => route); return false; } @@ -44,12 +46,12 @@ namespace Umbraco.Web.Routing var url = content == null ? "#" : content.Url; if (url.StartsWith("#")) { - LogHelper.Debug("Route \"{0}\" matches content {1} which has no url.", + _logger.Debug("Route \"{0}\" matches content {1} which has no url.", () => route, () => redirectUrl.ContentId); return false; } - LogHelper.Debug("Route \"{0}\" matches content {1} with url \"{2}\", redirecting.", + _logger.Debug("Route \"{0}\" matches content {1} with url \"{2}\", redirecting.", () => route, () => content.Id, () => url); contentRequest.SetRedirectPermanent(url); return true; diff --git a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs index 8df1e83718..8daa4f3201 100644 --- a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs +++ b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs @@ -18,10 +18,12 @@ namespace Umbraco.Web.Routing public class DefaultUrlProvider : IUrlProvider { private readonly IRequestHandlerSection _requestSettings; + private readonly ILogger _logger; - public DefaultUrlProvider(IRequestHandlerSection requestSettings) + public DefaultUrlProvider(IRequestHandlerSection requestSettings, ILogger logger) { _requestSettings = requestSettings; + _logger = logger; } #region GetUrl @@ -48,7 +50,7 @@ namespace Umbraco.Web.Routing if (string.IsNullOrWhiteSpace(route)) { - LogHelper.Debug( + _logger.Debug( "Couldn't find any page with nodeId={0}. This is most likely caused by the page not being published.", () => id); return null; @@ -56,7 +58,7 @@ namespace Umbraco.Web.Routing if (route.StartsWith("err/")) { - LogHelper.Debug( + _logger.Debug( "Page with nodeId={0} has a colliding url with page with nodeId={1}.", () => id, () => route.Substring(4)); return "#err-" + route.Substring(4); @@ -98,7 +100,7 @@ namespace Umbraco.Web.Routing if (string.IsNullOrWhiteSpace(route)) { - LogHelper.Debug( + _logger.Debug( "Couldn't find any page with nodeId={0}. This is most likely caused by the page not being published.", () => id); return null; diff --git a/src/Umbraco.Web/Routing/NotFoundHandlerHelper.cs b/src/Umbraco.Web/Routing/NotFoundHandlerHelper.cs index 0119484d37..7a9ed2cafd 100644 --- a/src/Umbraco.Web/Routing/NotFoundHandlerHelper.cs +++ b/src/Umbraco.Web/Routing/NotFoundHandlerHelper.cs @@ -106,7 +106,7 @@ namespace Umbraco.Web.Routing } catch (Exception ex) { - LogHelper.Error("Could not parse xpath expression: " + errorPage.ContentXPath, ex); + Current.Logger.Error("Could not parse xpath expression: " + errorPage.ContentXPath, ex); return null; } } diff --git a/src/Umbraco.Web/Routing/PublishedContentRequestEngine.cs b/src/Umbraco.Web/Routing/PublishedContentRequestEngine.cs index d4044b421d..ba7b717ff1 100644 --- a/src/Umbraco.Web/Routing/PublishedContentRequestEngine.cs +++ b/src/Umbraco.Web/Routing/PublishedContentRequestEngine.cs @@ -398,7 +398,7 @@ namespace Umbraco.Web.Routing //iterate but return on first one that finds it var found = _routingContext.PublishedContentFinders.Any(finder => { - LogHelper.Debug("Finder " + finder.GetType().FullName); + Current.Logger.Debug("Finder " + finder.GetType().FullName); return finder.TryFindContent(_pcr); }); } diff --git a/src/Umbraco.Web/Scheduling/KeepAlive.cs b/src/Umbraco.Web/Scheduling/KeepAlive.cs index d5618e4be2..75dc0aed7d 100644 --- a/src/Umbraco.Web/Scheduling/KeepAlive.cs +++ b/src/Umbraco.Web/Scheduling/KeepAlive.cs @@ -10,12 +10,16 @@ namespace Umbraco.Web.Scheduling internal class KeepAlive : RecurringTaskBase { private readonly IRuntimeState _runtime; + private readonly ILogger _logger; + private readonly ProfilingLogger _proflog; public KeepAlive(IBackgroundTaskRunner runner, int delayMilliseconds, int periodMilliseconds, - IRuntimeState runtime) + IRuntimeState runtime, ILogger logger, ProfilingLogger proflog) : base(runner, delayMilliseconds, periodMilliseconds) { _runtime = runtime; + _logger = logger; + _proflog = proflog; } public override bool PerformRun() @@ -28,11 +32,11 @@ namespace Umbraco.Web.Scheduling // ensure we do not run if not main domain, but do NOT lock it if (_runtime.IsMainDom == false) { - LogHelper.Debug("Does not run if not MainDom."); + _logger.Debug("Does not run if not MainDom."); return false; // do NOT repeat, going down } - using (DisposableTimer.DebugDuration(() => "Keep alive executing", () => "Keep alive complete")) + using (_proflog.DebugDuration("Keep alive executing", "Keep alive complete")) { string umbracoAppUrl = null; @@ -41,7 +45,7 @@ namespace Umbraco.Web.Scheduling umbracoAppUrl = _runtime.ApplicationUrl.ToString(); if (umbracoAppUrl.IsNullOrWhiteSpace()) { - LogHelper.Warn("No url for service (yet), skip."); + _logger.Warn("No url for service (yet), skip."); return true; // repeat } @@ -54,7 +58,7 @@ namespace Umbraco.Web.Scheduling } catch (Exception e) { - LogHelper.Error(string.Format("Failed (at \"{0}\").", umbracoAppUrl), e); + _logger.Error(string.Format("Failed (at \"{0}\").", umbracoAppUrl), e); } } diff --git a/src/Umbraco.Web/Scheduling/LogScrubber.cs b/src/Umbraco.Web/Scheduling/LogScrubber.cs index 7a62ce5278..1daf4ba691 100644 --- a/src/Umbraco.Web/Scheduling/LogScrubber.cs +++ b/src/Umbraco.Web/Scheduling/LogScrubber.cs @@ -14,18 +14,22 @@ namespace Umbraco.Web.Scheduling private readonly IRuntimeState _runtime; private readonly IAuditService _auditService; private readonly IUmbracoSettingsSection _settings; + private readonly ILogger _logger; + private readonly ProfilingLogger _proflog; public LogScrubber(IBackgroundTaskRunner runner, int delayMilliseconds, int periodMilliseconds, - IRuntimeState runtime, IAuditService auditService, IUmbracoSettingsSection settings) + IRuntimeState runtime, IAuditService auditService, IUmbracoSettingsSection settings, ILogger logger, ProfilingLogger proflog) : base(runner, delayMilliseconds, periodMilliseconds) { _runtime = runtime; _auditService = auditService; _settings = settings; + _logger = logger; + _proflog = proflog; } // maximum age, in minutes - private static int GetLogScrubbingMaximumAge(IUmbracoSettingsSection settings) + private int GetLogScrubbingMaximumAge(IUmbracoSettingsSection settings) { var maximumAge = 24 * 60; // 24 hours, in minutes try @@ -35,13 +39,13 @@ namespace Umbraco.Web.Scheduling } catch (Exception e) { - LogHelper.Error("Unable to locate a log scrubbing maximum age. Defaulting to 24 hours.", e); + _logger.Error("Unable to locate a log scrubbing maximum age. Defaulting to 24 hours.", e); } return maximumAge; } - public static int GetLogScrubbingInterval(IUmbracoSettingsSection settings) + public static int GetLogScrubbingInterval(IUmbracoSettingsSection settings, ILogger logger) { var interval = 4 * 60 * 60 * 1000; // 4 hours, in milliseconds try @@ -51,7 +55,7 @@ namespace Umbraco.Web.Scheduling } catch (Exception e) { - LogHelper.Error("Unable to locate a log scrubbing interval. Defaulting to 4 hours.", e); + logger.Error("Unable to locate a log scrubbing interval. Defaulting to 4 hours.", e); } return interval; } @@ -61,21 +65,21 @@ namespace Umbraco.Web.Scheduling switch (_runtime.ServerRole) { case ServerRole.Slave: - LogHelper.Debug("Does not run on slave servers."); + _logger.Debug("Does not run on slave servers."); return true; // DO repeat, server role can change case ServerRole.Unknown: - LogHelper.Debug("Does not run on servers with unknown role."); + _logger.Debug("Does not run on servers with unknown role."); return true; // DO repeat, server role can change } // ensure we do not run if not main domain, but do NOT lock it if (_runtime.IsMainDom == false) { - LogHelper.Debug("Does not run if not MainDom."); + _logger.Debug("Does not run if not MainDom."); return false; // do NOT repeat, going down } - using (DisposableTimer.DebugDuration("Log scrubbing executing", "Log scrubbing complete")) + using (_proflog.DebugDuration("Log scrubbing executing", "Log scrubbing complete")) { _auditService.CleanLogs(GetLogScrubbingMaximumAge(_settings)); } diff --git a/src/Umbraco.Web/Scheduling/ScheduledPublishing.cs b/src/Umbraco.Web/Scheduling/ScheduledPublishing.cs index 123c48a715..d99aa932fc 100644 --- a/src/Umbraco.Web/Scheduling/ScheduledPublishing.cs +++ b/src/Umbraco.Web/Scheduling/ScheduledPublishing.cs @@ -14,13 +14,17 @@ namespace Umbraco.Web.Scheduling { private readonly IRuntimeState _runtime; private readonly IUserService _userService; + private readonly ILogger _logger; + private readonly ProfilingLogger _proflog; public ScheduledPublishing(IBackgroundTaskRunner runner, int delayMilliseconds, int periodMilliseconds, - IRuntimeState runtime, IUserService userService) + IRuntimeState runtime, IUserService userService, ILogger logger, ProfilingLogger proflog) : base(runner, delayMilliseconds, periodMilliseconds) { _runtime = runtime; _userService = userService; + _logger = logger; + _proflog = proflog; } public override bool PerformRun() @@ -33,21 +37,21 @@ namespace Umbraco.Web.Scheduling switch (_runtime.ServerRole) { case ServerRole.Slave: - LogHelper.Debug("Does not run on slave servers."); + _logger.Debug("Does not run on slave servers."); return true; // DO repeat, server role can change case ServerRole.Unknown: - LogHelper.Debug("Does not run on servers with unknown role."); + _logger.Debug("Does not run on servers with unknown role."); return true; // DO repeat, server role can change } // ensure we do not run if not main domain, but do NOT lock it if (_runtime.IsMainDom == false) { - LogHelper.Debug("Does not run if not MainDom."); + _logger.Debug("Does not run if not MainDom."); return false; // do NOT repeat, going down } - using (DisposableTimer.DebugDuration(() => "Scheduled publishing executing", () => "Scheduled publishing complete")) + using (_proflog.DebugDuration("Scheduled publishing executing", "Scheduled publishing complete")) { string umbracoAppUrl = null; @@ -56,7 +60,7 @@ namespace Umbraco.Web.Scheduling umbracoAppUrl = _runtime.ApplicationUrl.ToString(); if (umbracoAppUrl.IsNullOrWhiteSpace()) { - LogHelper.Warn("No url for service (yet), skip."); + _logger.Warn("No url for service (yet), skip."); return true; // repeat } @@ -75,7 +79,7 @@ namespace Umbraco.Web.Scheduling } catch (Exception e) { - LogHelper.Error(string.Format("Failed (at \"{0}\").", umbracoAppUrl), e); + _logger.Error(string.Format("Failed (at \"{0}\").", umbracoAppUrl), e); } } diff --git a/src/Umbraco.Web/Scheduling/ScheduledTasks.cs b/src/Umbraco.Web/Scheduling/ScheduledTasks.cs index 3bb841b388..3a45b144b1 100644 --- a/src/Umbraco.Web/Scheduling/ScheduledTasks.cs +++ b/src/Umbraco.Web/Scheduling/ScheduledTasks.cs @@ -19,14 +19,18 @@ namespace Umbraco.Web.Scheduling { private readonly IRuntimeState _runtime; private readonly IUmbracoSettingsSection _settings; + private readonly ILogger _logger; + private readonly ProfilingLogger _proflog; private static readonly Hashtable ScheduledTaskTimes = new Hashtable(); public ScheduledTasks(IBackgroundTaskRunner runner, int delayMilliseconds, int periodMilliseconds, - IRuntimeState runtime, IUmbracoSettingsSection settings) + IRuntimeState runtime, IUmbracoSettingsSection settings, ILogger logger, ProfilingLogger proflog) : base(runner, delayMilliseconds, periodMilliseconds) { _runtime = runtime; _settings = settings; + _logger = logger; + _proflog = proflog; } private async Task ProcessTasksAsync(CancellationToken token) @@ -54,7 +58,7 @@ namespace Umbraco.Web.Scheduling { var taskResult = await GetTaskByHttpAync(t.Url, token); if (t.Log) - LogHelper.Info(string.Format("{0} has been called with response: {1}", t.Alias, taskResult)); + _logger.Info(string.Format("{0} has been called with response: {1}", t.Alias, taskResult)); } } } @@ -75,7 +79,7 @@ namespace Umbraco.Web.Scheduling } catch (Exception ex) { - LogHelper.Error("An error occurred calling web task for url: " + url, ex); + _logger.Error("An error occurred calling web task for url: " + url, ex); } return false; } @@ -91,21 +95,21 @@ namespace Umbraco.Web.Scheduling switch (_runtime.ServerRole) { case ServerRole.Slave: - LogHelper.Debug("Does not run on slave servers."); + _logger.Debug("Does not run on slave servers."); return true; // DO repeat, server role can change case ServerRole.Unknown: - LogHelper.Debug("Does not run on servers with unknown role."); + _logger.Debug("Does not run on servers with unknown role."); return true; // DO repeat, server role can change } // ensure we do not run if not main domain, but do NOT lock it if (_runtime.IsMainDom == false) { - LogHelper.Debug("Does not run if not MainDom."); + _logger.Debug("Does not run if not MainDom."); return false; // do NOT repeat, going down } - using (DisposableTimer.DebugDuration(() => "Scheduled tasks executing", () => "Scheduled tasks complete")) + using (_proflog.DebugDuration("Scheduled tasks executing", "Scheduled tasks complete")) { try { @@ -113,7 +117,7 @@ namespace Umbraco.Web.Scheduling } catch (Exception ee) { - LogHelper.Error("Error executing scheduled task", ee); + _logger.Error("Error executing scheduled task", ee); } } diff --git a/src/Umbraco.Web/Scheduling/SchedulerComponent.cs b/src/Umbraco.Web/Scheduling/SchedulerComponent.cs index 94eebd27fb..6f7f756e7b 100644 --- a/src/Umbraco.Web/Scheduling/SchedulerComponent.cs +++ b/src/Umbraco.Web/Scheduling/SchedulerComponent.cs @@ -21,6 +21,8 @@ namespace Umbraco.Web.Scheduling private IRuntimeState _runtime; private IUserService _userService; private IAuditService _auditService; + private ILogger _logger; + private ProfilingLogger _proflog; private BackgroundTaskRunner _keepAliveRunner; private BackgroundTaskRunner _publishingRunner; @@ -31,11 +33,13 @@ namespace Umbraco.Web.Scheduling private object _locker = new object(); private IBackgroundTask[] _tasks; - public void Initialize(IRuntimeState runtime, IUserService userService, IAuditService auditService, ILogger logger) + public void Initialize(IRuntimeState runtime, IUserService userService, IAuditService auditService, ILogger logger, ProfilingLogger proflog) { _runtime = runtime; _userService = userService; _auditService = auditService; + _logger = logger; + _proflog = proflog; // backgrounds runners are web aware, if the app domain dies, these tasks will wind down correctly _keepAliveRunner = new BackgroundTaskRunner("KeepAlive", logger); @@ -65,15 +69,15 @@ namespace Umbraco.Web.Scheduling LazyInitializer.EnsureInitialized(ref _tasks, ref _started, ref _locker, () => { - LogHelper.Debug(() => "Initializing the scheduler"); + _logger.Debug(() => "Initializing the scheduler"); var settings = UmbracoConfig.For.UmbracoSettings(); var tasks = new List { - new KeepAlive(_keepAliveRunner, 60000, 300000, _runtime), - new ScheduledPublishing(_publishingRunner, 60000, 60000, _runtime, _userService), - new ScheduledTasks(_tasksRunner, 60000, 60000, _runtime, settings), - new LogScrubber(_scrubberRunner, 60000, LogScrubber.GetLogScrubbingInterval(settings), _runtime, _auditService, settings) + new KeepAlive(_keepAliveRunner, 60000, 300000, _runtime, _logger, _proflog), + new ScheduledPublishing(_publishingRunner, 60000, 60000, _runtime, _userService, _logger, _proflog), + new ScheduledTasks(_tasksRunner, 60000, 60000, _runtime, settings, _logger, _proflog), + new LogScrubber(_scrubberRunner, 60000, LogScrubber.GetLogScrubbingInterval(settings, _logger), _runtime, _auditService, settings, _logger, _proflog) }; // ping/keepalive diff --git a/src/Umbraco.Web/Search/ExamineComponent.cs b/src/Umbraco.Web/Search/ExamineComponent.cs index 47eab1c9b7..cee52f7ddb 100644 --- a/src/Umbraco.Web/Search/ExamineComponent.cs +++ b/src/Umbraco.Web/Search/ExamineComponent.cs @@ -26,9 +26,9 @@ namespace Umbraco.Web.Search /// public sealed class ExamineComponent : UmbracoComponentBase, IUmbracoCoreComponent { - public void Initialize() + public void Initialize(ILogger logger) { - LogHelper.Info("Initializing Examine and binding to business logic events"); + logger.Info("Initializing Examine and binding to business logic events"); //TODO: For now we'll make this true, it means that indexes will be near real time // we'll see about what implications this may have - should be great in most scenarios @@ -37,7 +37,7 @@ namespace Umbraco.Web.Search var registeredProviders = ExamineManager.Instance.IndexProviderCollection .OfType().Count(x => x.EnableDefaultEventHandler); - LogHelper.Info("Adding examine event handlers for index providers: {0}", () => registeredProviders); + logger.Info("Adding examine event handlers for index providers: {0}", () => registeredProviders); // don't bind event handlers if we're not suppose to listen if (registeredProviders == 0) diff --git a/src/Umbraco.Web/Security/Identity/AuthenticationOptionsExtensions.cs b/src/Umbraco.Web/Security/Identity/AuthenticationOptionsExtensions.cs index fa31e5f888..d7f1ac02c1 100644 --- a/src/Umbraco.Web/Security/Identity/AuthenticationOptionsExtensions.cs +++ b/src/Umbraco.Web/Security/Identity/AuthenticationOptionsExtensions.cs @@ -98,7 +98,7 @@ namespace Umbraco.Web.Security.Identity } catch (System.Exception ex) { - LogHelper.Error(typeof (AuthenticationOptionsExtensions), "Could not read AuthenticationOptions properties", ex); + Current.Logger.Error(typeof (AuthenticationOptionsExtensions), "Could not read AuthenticationOptions properties", ex); } } else diff --git a/src/Umbraco.Web/Security/MembershipHelper.cs b/src/Umbraco.Web/Security/MembershipHelper.cs index 390642e54c..0bf3ef776d 100644 --- a/src/Umbraco.Web/Security/MembershipHelper.cs +++ b/src/Umbraco.Web/Security/MembershipHelper.cs @@ -236,7 +236,7 @@ namespace Umbraco.Web.Security if (member == null) { //this should not happen - LogHelper.Warn("The member validated but then no member was returned with the username " + username); + Current.Logger.Warn("The member validated but then no member was returned with the username " + username); return false; } //Log them in @@ -647,7 +647,7 @@ namespace Umbraco.Web.Security } catch (Exception ex) { - LogHelper.WarnWithException("Could not reset member password", ex); + Current.Logger.Warn(ex, "Could not reset member password"); return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not reset password, error: " + ex.Message + " (see log for full details)", new[] { "resetPassword" }) }); } } @@ -673,7 +673,7 @@ namespace Umbraco.Web.Security } catch (Exception ex) { - LogHelper.WarnWithException("Could not change member password", ex); + Current.Logger.Warn(ex, "Could not change member password"); return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex.Message + " (see log for full details)", new[] { "value" }) }); } } @@ -698,7 +698,7 @@ namespace Umbraco.Web.Security } catch (Exception ex) { - LogHelper.WarnWithException("Could not change member password", ex); + Current.Logger.Warn(ex, "Could not change member password"); return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex.Message + " (see log for full details)", new[] { "value" }) }); } } @@ -730,14 +730,14 @@ namespace Umbraco.Web.Security } catch (Exception ex1) { - LogHelper.WarnWithException("Could not change member password", ex1); + Current.Logger.Warn(ex1, "Could not change member password"); return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex1.Message + " (see log for full details)", new[] { "value" }) }); } } catch (Exception ex2) { - LogHelper.WarnWithException("Could not retrieve member password", ex2); + Current.Logger.Warn(ex2, "Could not retrieve member password"); return Attempt.Fail(new PasswordChangedModel { ChangeError = new ValidationResult("Could not change password, error: " + ex2.Message + " (see log for full details)", new[] { "value" }) }); } } diff --git a/src/Umbraco.Web/Security/Providers/UmbracoMembershipProvider.cs b/src/Umbraco.Web/Security/Providers/UmbracoMembershipProvider.cs index ce7e9e14ec..7ff6afffe6 100644 --- a/src/Umbraco.Web/Security/Providers/UmbracoMembershipProvider.cs +++ b/src/Umbraco.Web/Security/Providers/UmbracoMembershipProvider.cs @@ -146,7 +146,7 @@ namespace Umbraco.Web.Security.Providers if (MemberService.Exists(username)) { status = MembershipCreateStatus.DuplicateUserName; - LogHelper.Warn>("Cannot create member as username already exists: " + username); + Current.Logger.Warn>("Cannot create member as username already exists: " + username); return null; } @@ -154,7 +154,7 @@ namespace Umbraco.Web.Security.Providers if (MemberService.GetByEmail(email) != null && RequiresUniqueEmail) { status = MembershipCreateStatus.DuplicateEmail; - LogHelper.Warn>( + Current.Logger.Warn>( "Cannot create member as a member with the same email address exists: " + email); return null; } @@ -523,7 +523,7 @@ namespace Umbraco.Web.Security.Providers if (member == null) { - LogHelper.Info( + Current.Logger.Info( string.Format( "Login attempt failed for username {0} from IP address {1}, the user does not exist", username, @@ -534,7 +534,7 @@ namespace Umbraco.Web.Security.Providers if (member.IsApproved == false) { - LogHelper.Info( + Current.Logger.Info( string.Format( "Login attempt failed for username {0} from IP address {1}, the user is not approved", username, @@ -544,7 +544,7 @@ namespace Umbraco.Web.Security.Providers } if (member.IsLockedOut) { - LogHelper.Info( + Current.Logger.Info( string.Format( "Login attempt failed for username {0} from IP address {1}, the user is locked", username, @@ -568,7 +568,7 @@ namespace Umbraco.Web.Security.Providers member.IsLockedOut = true; member.LastLockoutDate = DateTime.Now; - LogHelper.Info( + Current.Logger.Info( string.Format( "Login attempt failed for username {0} from IP address {1}, the user is now locked out, max invalid password attempts exceeded", username, @@ -576,7 +576,7 @@ namespace Umbraco.Web.Security.Providers } else { - LogHelper.Info( + Current.Logger.Info( string.Format( "Login attempt failed for username {0} from IP address {1}", username, @@ -588,7 +588,7 @@ namespace Umbraco.Web.Security.Providers member.FailedPasswordAttempts = 0; member.LastLoginDate = DateTime.Now; - LogHelper.Info( + Current.Logger.Info( string.Format( "Login attempt succeeded for username {0} from IP address {1}", username, diff --git a/src/Umbraco.Web/Security/WebSecurity.cs b/src/Umbraco.Web/Security/WebSecurity.cs index 635003824d..591da4b034 100644 --- a/src/Umbraco.Web/Security/WebSecurity.cs +++ b/src/Umbraco.Web/Security/WebSecurity.cs @@ -285,7 +285,7 @@ namespace Umbraco.Web.Security return true; var user = umbracoUser; - LogHelper.Info("User {0} has insufficient permissions in UmbracoEnsuredPage: '{1}', '{2}', '{3}'", () => user.Name, () => path, () => string.Join(",", permission.AssignedPermissions), () => action); + Current.Logger.Info("User {0} has insufficient permissions in UmbracoEnsuredPage: '{1}', '{2}', '{3}'", () => user.Name, () => path, () => string.Join(",", permission.AssignedPermissions), () => action); return false; } diff --git a/src/Umbraco.Web/Strategies/DatabaseServerRegistrationComponent.cs b/src/Umbraco.Web/Strategies/DatabaseServerRegistrationComponent.cs index f1aa07413c..bf989f0d27 100644 --- a/src/Umbraco.Web/Strategies/DatabaseServerRegistrationComponent.cs +++ b/src/Umbraco.Web/Strategies/DatabaseServerRegistrationComponent.cs @@ -27,6 +27,7 @@ namespace Umbraco.Web.Strategies private object _locker = new object(); private DatabaseServerRegistrar _registrar; private IRuntimeState _runtime; + private ILogger _logger; private IServerRegistrationService _registrationService; private BackgroundTaskRunner _backgroundTaskRunner; private bool _started; @@ -40,6 +41,7 @@ namespace Umbraco.Web.Strategies if (_registrar == null) return; _runtime = runtime; + _logger = logger; _registrationService = registrationService; _backgroundTaskRunner = new BackgroundTaskRunner( @@ -86,7 +88,7 @@ namespace Umbraco.Web.Strategies var task = new TouchServerTask(_backgroundTaskRunner, 15000, //delay before first execution _registrar.Options.RecurringSeconds*1000, //amount of ms between executions - svc, _registrar, serverAddress); + svc, _registrar, serverAddress, _logger); // perform the rest async, we don't want to block the startup sequence // this will just reoccur on a background thread @@ -101,6 +103,7 @@ namespace Umbraco.Web.Strategies private readonly IServerRegistrationService _svc; private readonly DatabaseServerRegistrar _registrar; private readonly string _serverAddress; + private readonly ILogger _logger; /// /// Initializes a new instance of the class. @@ -111,15 +114,17 @@ namespace Umbraco.Web.Strategies /// /// /// + /// /// The task will repeat itself periodically. Use this constructor to create a new task. public TouchServerTask(IBackgroundTaskRunner runner, int delayMilliseconds, int periodMilliseconds, - IServerRegistrationService svc, DatabaseServerRegistrar registrar, string serverAddress) + IServerRegistrationService svc, DatabaseServerRegistrar registrar, string serverAddress, ILogger logger) : base(runner, delayMilliseconds, periodMilliseconds) { if (svc == null) throw new ArgumentNullException(nameof(svc)); _svc = svc; _registrar = registrar; _serverAddress = serverAddress; + _logger = logger; } public override bool IsAsync => false; @@ -139,7 +144,7 @@ namespace Umbraco.Web.Strategies } catch (Exception ex) { - LogHelper.Error("Failed to update server record in database.", ex); + _logger.Error("Failed to update server record in database.", ex); return false; // probably stop if we have an error } } diff --git a/src/Umbraco.Web/Strategies/Migrations/ClearMediaXmlCacheForDeletedItemsAfterUpgrade.cs b/src/Umbraco.Web/Strategies/Migrations/ClearMediaXmlCacheForDeletedItemsAfterUpgrade.cs index a13396fc91..d13147dc22 100644 --- a/src/Umbraco.Web/Strategies/Migrations/ClearMediaXmlCacheForDeletedItemsAfterUpgrade.cs +++ b/src/Umbraco.Web/Strategies/Migrations/ClearMediaXmlCacheForDeletedItemsAfterUpgrade.cs @@ -17,6 +17,13 @@ namespace Umbraco.Web.Strategies.Migrations /// public class ClearMediaXmlCacheForDeletedItemsAfterUpgrade : IPostMigration { + private readonly ILogger _logger; + + public ClearMediaXmlCacheForDeletedItemsAfterUpgrade(ILogger logger) + { + _logger = logger; + } + public void Migrated(MigrationRunner sender, MigrationEventArgs args) { if (args.ProductName != GlobalSettings.UmbracoMigrationName) return; @@ -37,7 +44,7 @@ namespace Umbraco.Web.Strategies.Migrations var count = args.MigrationContext.Database.Execute(sql); - LogHelper.Info("Cleared " + count + " items from the media xml cache that were trashed and not meant to be there"); + _logger.Info("Cleared " + count + " items from the media xml cache that were trashed and not meant to be there"); } } } diff --git a/src/Umbraco.Web/Templates/TemplateUtilities.cs b/src/Umbraco.Web/Templates/TemplateUtilities.cs index 253dfbe9aa..aa4fb2716a 100644 --- a/src/Umbraco.Web/Templates/TemplateUtilities.cs +++ b/src/Umbraco.Web/Templates/TemplateUtilities.cs @@ -72,11 +72,11 @@ namespace Umbraco.Web.Templates { if (UmbracoConfig.For.UmbracoSettings().Content.ResolveUrlsFromTextString == false) return text; - using (var timer = DisposableTimer.DebugDuration(typeof(IOHelper), "ResolveUrlsFromTextString starting", "ResolveUrlsFromTextString complete")) + using (var timer = Current.ProfilingLogger.DebugDuration(typeof(IOHelper), "ResolveUrlsFromTextString starting", "ResolveUrlsFromTextString complete")) { // find all relative urls (ie. urls that contain ~) var tags = ResolveUrlPattern.Matches(text); - LogHelper.Debug(typeof(IOHelper), "After regex: " + timer.Stopwatch.ElapsedMilliseconds + " matched: " + tags.Count); + Current.Logger.Debug(typeof(IOHelper), "After regex: " + timer.Stopwatch.ElapsedMilliseconds + " matched: " + tags.Count); foreach (Match tag in tags) { var url = ""; diff --git a/src/Umbraco.Web/Trees/ContentTreeControllerBase.cs b/src/Umbraco.Web/Trees/ContentTreeControllerBase.cs index 223fee3c39..9b9296f40f 100644 --- a/src/Umbraco.Web/Trees/ContentTreeControllerBase.cs +++ b/src/Umbraco.Web/Trees/ContentTreeControllerBase.cs @@ -92,7 +92,7 @@ namespace Umbraco.Web.Trees // TODO: in the future we could return a validation statement so we can have some UI to notify the user they don't have access if (HasPathAccess(id, queryStrings) == false) { - LogHelper.Warn("The user " + Security.CurrentUser.Username + " does not have access to the tree node " + id); + Logger.Warn("The user " + Security.CurrentUser.Username + " does not have access to the tree node " + id); return new TreeNodeCollection(); } diff --git a/src/Umbraco.Web/Trees/LegacyTreeController.cs b/src/Umbraco.Web/Trees/LegacyTreeController.cs index 04edcb8063..5bfe20c4ab 100644 --- a/src/Umbraco.Web/Trees/LegacyTreeController.cs +++ b/src/Umbraco.Web/Trees/LegacyTreeController.cs @@ -39,7 +39,7 @@ namespace Umbraco.Web.Trees if (attempt.Success == false) { var msg = "Could not render tree " + queryStrings.GetRequiredString("treeType") + " for node id " + id; - LogHelper.Error(msg, attempt.Exception); + Logger.Error(msg, attempt.Exception); throw new ApplicationException(msg); } @@ -66,7 +66,7 @@ namespace Umbraco.Web.Trees if (attempt.Success == false) { var msg = "Could not render menu for root node for treeType " + queryStrings.GetRequiredString("treeType"); - LogHelper.Error(msg, attempt.Exception); + Logger.Error(msg, attempt.Exception); throw new ApplicationException(msg); } @@ -82,7 +82,7 @@ namespace Umbraco.Web.Trees if (attempt.Success == false) { var msg = "Could not render menu for treeType " + queryStrings.GetRequiredString("treeType") + " for node id " + parentId; - LogHelper.Error(msg, attempt.Exception); + Logger.Error(msg, attempt.Exception); throw new ApplicationException(msg); } foreach (var menuItem in attempt.Result.Items) diff --git a/src/Umbraco.Web/Trees/LegacyTreeDataConverter.cs b/src/Umbraco.Web/Trees/LegacyTreeDataConverter.cs index 7f17b4d0ba..e960705495 100644 --- a/src/Umbraco.Web/Trees/LegacyTreeDataConverter.cs +++ b/src/Umbraco.Web/Trees/LegacyTreeDataConverter.cs @@ -36,7 +36,7 @@ namespace Umbraco.Web.Trees var legacyAtt = controllerAttempt.Result.GetCustomAttribute(false); if (legacyAtt == null) { - LogHelper.Warn("Cannot render tree: " + appTree.Alias + ". Cannot render a " + typeof(TreeController) + " tree type with the legacy web services unless attributed with " + typeof(LegacyBaseTreeAttribute)); + Current.Logger.Warn("Cannot render tree: " + appTree.Alias + ". Cannot render a " + typeof(TreeController) + " tree type with the legacy web services unless attributed with " + typeof(LegacyBaseTreeAttribute)); return null; } diff --git a/src/Umbraco.Web/Trees/LegacyTreeJavascript.cs b/src/Umbraco.Web/Trees/LegacyTreeJavascript.cs index 30e677455e..24bc084d3d 100644 --- a/src/Umbraco.Web/Trees/LegacyTreeJavascript.cs +++ b/src/Umbraco.Web/Trees/LegacyTreeJavascript.cs @@ -33,7 +33,7 @@ namespace Umbraco.Web.Trees } catch (Exception ex) { - LogHelper.Error(typeof(LegacyTreeJavascript), "Could not load the JS from the legacy tree " + bTree.TreeAlias, ex); + Current.Logger.Error(typeof(LegacyTreeJavascript), "Could not load the JS from the legacy tree " + bTree.TreeAlias, ex); } } @@ -65,7 +65,7 @@ namespace Umbraco.Web.Trees } catch (Exception ee) { - LogHelper.Error(typeof(LegacyTreeJavascript), "Error initializing tree action", ee); + Current.Logger.Error(typeof(LegacyTreeJavascript), "Error initializing tree action", ee); } } diff --git a/src/Umbraco.Web/UI/CdfLogger.cs b/src/Umbraco.Web/UI/CdfLogger.cs index 32d12f8293..f4924d99f1 100644 --- a/src/Umbraco.Web/UI/CdfLogger.cs +++ b/src/Umbraco.Web/UI/CdfLogger.cs @@ -1,41 +1,46 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using ClientDependency.Core.Logging; using Umbraco.Core.Logging; -using ILogger = ClientDependency.Core.Logging.ILogger; +using ICdfLogger = ClientDependency.Core.Logging.ILogger; +using ICoreLogger = Umbraco.Core.Logging.ILogger; namespace Umbraco.Web.UI { /// /// A logger for ClientDependency /// - public class CdfLogger : ILogger + public class CdfLogger : ICdfLogger { + private readonly ICoreLogger _logger; + + // Client Dependency doesn't know how to inject + public CdfLogger(/*ICoreLogger logger*/) + { + _logger = Current.Logger; + } + public void Debug(string msg) { - LogHelper.Debug(msg); + _logger.Debug(msg); } public void Info(string msg) { - LogHelper.Info(msg); + _logger.Info(msg); } public void Warn(string msg) { - LogHelper.Warn(msg); + _logger.Warn(msg); } public void Error(string msg, Exception ex) { - LogHelper.Error(msg, ex); + _logger.Error(msg, ex); } public void Fatal(string msg, Exception ex) { - LogHelper.Error(msg, ex); + _logger.Error(msg, ex); } } } diff --git a/src/Umbraco.Web/UI/Pages/UmbracoEnsuredPage.cs b/src/Umbraco.Web/UI/Pages/UmbracoEnsuredPage.cs index d1f9e282bd..30f0ed33bf 100644 --- a/src/Umbraco.Web/UI/Pages/UmbracoEnsuredPage.cs +++ b/src/Umbraco.Web/UI/Pages/UmbracoEnsuredPage.cs @@ -61,7 +61,7 @@ namespace Umbraco.Web.UI.Pages if (!Security.ValidateUserApp(CurrentApp)) { var ex = new SecurityException(String.Format("The current user doesn't have access to the section/app '{0}'", CurrentApp)); - LogHelper.Error(String.Format("Tried to access '{0}'", CurrentApp), ex); + Current.Logger.Error(String.Format("Tried to access '{0}'", CurrentApp), ex); throw ex; } diff --git a/src/Umbraco.Web/UmbracoContext.cs b/src/Umbraco.Web/UmbracoContext.cs index a7b06ce656..3753ed4d5b 100644 --- a/src/Umbraco.Web/UmbracoContext.cs +++ b/src/Umbraco.Web/UmbracoContext.cs @@ -44,6 +44,17 @@ namespace Umbraco.Web /// during the startup process as well. /// See: http://issues.umbraco.org/issue/U4-1890, http://issues.umbraco.org/issue/U4-1717 /// + // used by + // UmbracoModule BeginRequest (since it's a request it has an UmbracoContext) + // in BeginRequest so *late* ie *after* the HttpApplication has started (+ init? check!) + // WebRuntimeComponent (and I'm not quite sure why) + // -> because an UmbracoContext seems to be required by UrlProvider to get the "current" facade? + // note: at startup not sure we have an HttpContext.Current + // at startup not sure we have an httpContext.Request => hard to tell "current" url + // should we have a post-boot event of some sort for ppl that *need* ?! + // can we have issues w/ routing context? + // and tests + // can .ContentRequest be null? of course! public static UmbracoContext EnsureContext( HttpContextBase httpContext, IFacadeService facadeService, @@ -64,6 +75,7 @@ namespace Umbraco.Web // create, assign the singleton, and return umbracoContext = CreateContext(httpContext, facadeService, webSecurity, umbracoSettings, urlProviders); + // fixme... ?! Web.Current.SetUmbracoContext(umbracoContext, replaceContext); // will dispose the one that is being replaced return umbracoContext; } @@ -80,6 +92,7 @@ namespace Umbraco.Web /// /// A new instance of UmbracoContext /// + // internal for tests internal static UmbracoContext CreateContext( HttpContextBase httpContext, IFacadeService facadeService, diff --git a/src/Umbraco.Web/UmbracoDefaultOwinStartup.cs b/src/Umbraco.Web/UmbracoDefaultOwinStartup.cs index a2a229c9a0..c08ec09ad8 100644 --- a/src/Umbraco.Web/UmbracoDefaultOwinStartup.cs +++ b/src/Umbraco.Web/UmbracoDefaultOwinStartup.cs @@ -28,6 +28,11 @@ namespace Umbraco.Web public virtual void Configuration(IAppBuilder app) { app.SanitizeThreadCulture(); + + // there's nothing we can do really + if (Core.DependencyInjection.Current.RuntimeState.Level == RuntimeLevel.BootFailed) + return; + ConfigureServices(app, Current.Services); ConfigureMiddleware(app); ConfigureSignalR(app); diff --git a/src/Umbraco.Web/UmbracoModule.cs b/src/Umbraco.Web/UmbracoModule.cs index b65eb5ed80..67e58c226b 100644 --- a/src/Umbraco.Web/UmbracoModule.cs +++ b/src/Umbraco.Web/UmbracoModule.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.IO; using System.Web; using System.Web.Routing; +using LightInject; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.IO; @@ -11,6 +12,8 @@ using Umbraco.Core.Logging; using Umbraco.Web.Routing; using Umbraco.Web.Security; using Umbraco.Core.Collections; +using Umbraco.Core.Exceptions; +using Umbraco.Core.Services; using Umbraco.Core.Sync; using Umbraco.Web.PublishedCache; using GlobalSettings = Umbraco.Core.Configuration.GlobalSettings; @@ -25,13 +28,41 @@ namespace Umbraco.Web public class UmbracoModule : IHttpModule { - #region HttpModule event handlers + #region Dependencies - /// - /// Begins to process a request. - /// - /// - static void BeginRequest(HttpContextBase httpContext) + // modules are *not* instanciated by the container so we have to + // get our dependencies injected manually, through properties, in + // Init(). works for dependencies that are singletons. + + [Inject] + public IFacadeService FacadeService { get; set; } + + [Inject] + public IUserService UserService { get; set; } + + [Inject] + public UrlProviderCollection UrlProviders { get; set; } + + [Inject] + public IRuntimeState Runtime { get; set; } + + [Inject] + public ILogger Logger { get; set; } + + #endregion + + public UmbracoModule() + { + _combinedRouteCollection = new Lazy(CreateRouteCollection); + } + + #region HttpModule event handlers + + /// + /// Begins to process a request. + /// + /// + private void BeginRequest(HttpContextBase httpContext) { // ensure application url is initialized ((RuntimeState)Current.RuntimeState).EnsureApplicationUrl(httpContext.Request); @@ -54,10 +85,10 @@ namespace Umbraco.Web // NOTE: we assign 'true' to ensure the context is replaced if it is already set (i.e. during app startup) UmbracoContext.EnsureContext( httpContext, - Current.FacadeService, - new WebSecurity(httpContext, Current.Services.UserService), + FacadeService, + new WebSecurity(httpContext, UserService), UmbracoConfig.For.UmbracoSettings(), - Current.UrlProviders, + UrlProviders, true); } @@ -117,7 +148,7 @@ namespace Umbraco.Web // HandleHttpResponseStatus returns a value indicating that the request should // not be processed any further, eg because it has been redirect. then, exit. - if (HandleHttpResponseStatus(httpContext, pcr)) + if (HandleHttpResponseStatus(httpContext, pcr, Logger)) return; if (pcr.HasPublishedContent == false) @@ -209,16 +240,16 @@ namespace Umbraco.Web //NOTE: No need to warn, plus if we do we should log the document, as this message doesn't really tell us anything :) //if (!maybeDoc) //{ - // LogHelper.Warn("Not a document"); + // Logger.Warn("Not a document"); //} return maybeDoc; } - private static bool EnsureRuntime(HttpContextBase httpContext, Uri uri) + private bool EnsureRuntime(HttpContextBase httpContext, Uri uri) { - var debug = Current.RuntimeState.Debug; - var level = Current.RuntimeState.Level; + var debug = Runtime.Debug; + var level = Runtime.Level; switch (level) { case RuntimeLevel.Unknown: @@ -237,7 +268,7 @@ namespace Umbraco.Web httpContext.RewritePath(UriUtility.ToAbsolute(bootUrl) + "?url=" + HttpUtility.UrlEncode(uri.ToString())); return false; // cannot serve content - case RuntimeLevel.Failed: + case RuntimeLevel.BootFailed: // redirect to death page ReportRuntime(level, "Umbraco has failed."); @@ -268,23 +299,23 @@ namespace Umbraco.Web private static bool _reported; private static RuntimeLevel _reportedLevel; - private static void ReportRuntime(RuntimeLevel level, string message) + private void ReportRuntime(RuntimeLevel level, string message) { if (_reported && _reportedLevel == level) return; _reported = true; _reportedLevel = level; - Current.Logger.Warn(message); + Logger.Warn(message); } // ensures Umbraco has at least one published node // if not, rewrites to splash and return false // if yes, return true - private static bool EnsureHasContent(UmbracoContext context, HttpContextBase httpContext) + private bool EnsureHasContent(UmbracoContext context, HttpContextBase httpContext) { if (context.ContentCache.HasContent()) return true; - LogHelper.Warn("Umbraco has no content"); + Logger.Warn("Umbraco has no content"); const string noContentUrl = "~/config/splashes/noNodes.aspx"; httpContext.RewritePath(UriUtility.ToAbsolute(noContentUrl)); @@ -295,12 +326,12 @@ namespace Umbraco.Web // returns a value indicating whether redirection took place and the request has // been completed - because we don't want to Response.End() here to terminate // everything properly. - internal static bool HandleHttpResponseStatus(HttpContextBase context, PublishedContentRequest pcr) + internal static bool HandleHttpResponseStatus(HttpContextBase context, PublishedContentRequest pcr, ILogger logger) { var end = false; var response = context.Response; - LogHelper.Debug("Response status: Redirect={0}, Is404={1}, StatusCode={2}", + logger.Debug("Response status: Redirect={0}, Is404={1}, StatusCode={2}", () => pcr.IsRedirect ? (pcr.IsRedirectPermanent ? "permanent" : "redirect") : "none", () => pcr.Is404 ? "true" : "false", () => pcr.ResponseStatusCode); @@ -318,7 +349,7 @@ namespace Umbraco.Web response.TrySkipIisCustomErrors = UmbracoConfig.For.UmbracoSettings().WebRouting.TrySkipIisCustomErrors; if (response.TrySkipIisCustomErrors == false) - LogHelper.Warn("Status code is 404 yet TrySkipIisCustomErrors is false - IIS will take over."); + logger.Warn("Status code is 404 yet TrySkipIisCustomErrors is false - IIS will take over."); } if (pcr.ResponseStatusCode > 0) @@ -337,7 +368,7 @@ namespace Umbraco.Web context.ApplicationInstance.CompleteRequest(); // though some say that .CompleteRequest() does not properly shutdown the response // and the request will hang until the whole code has run... would need to test? - LogHelper.Debug("Response status: redirecting, complete request now."); + logger.Debug("Response status: redirecting, complete request now."); return end; } @@ -404,7 +435,7 @@ namespace Umbraco.Web /// Any object that is in the HttpContext.Items collection that is IDisposable will get disposed on the end of the request /// /// - private static void DisposeHttpContextItems(HttpContext http) + private void DisposeHttpContextItems(HttpContext http) { // do not process if client-side request if (http.Request.Url.IsClientSideRequest()) @@ -428,7 +459,7 @@ namespace Umbraco.Web } catch (Exception ex) { - LogHelper.Error("Could not dispose item with key " + k, ex); + Logger.Error("Could not dispose item with key " + k, ex); } try { @@ -436,7 +467,7 @@ namespace Umbraco.Web } catch (Exception ex) { - LogHelper.Error("Could not dispose item key " + k, ex); + Logger.Error("Could not dispose item key " + k, ex); } } } @@ -452,52 +483,62 @@ namespace Umbraco.Web /// public void Init(HttpApplication app) { - app.BeginRequest += (sender, e) => - { - var httpContext = ((HttpApplication)sender).Context; - LogHelper.Debug("Begin request: {0}.", () => httpContext.Request.Url); - BeginRequest(new HttpContextWrapper(httpContext)); - }; + if (Core.DependencyInjection.Current.RuntimeState.Level == RuntimeLevel.BootFailed) + { + // there's nothing we can do really + app.BeginRequest += (sender, args) => { throw new BootFailedException("Boot failed. Umbraco cannot run. Umbraco's log file contains details about what caused the boot to fail."); }; + return; + } - //disable asp.net headers (security) - // This is the correct place to modify headers according to MS: - // https://our.umbraco.org/forum/umbraco-7/using-umbraco-7/65241-Heap-error-from-header-manipulation?p=0#comment220889 - app.PostReleaseRequestState += (sender, args) => + // modules are *not* instanciated by the container so we have to + // get our dependencies injected manually, through properties. + Core.DependencyInjection.Current.Container.InjectProperties(this); + + app.BeginRequest += (sender, e) => { - var httpContext = ((HttpApplication)sender).Context; - try - { - httpContext.Response.Headers.Remove("Server"); - //this doesn't normally work since IIS sets it but we'll keep it here anyways. - httpContext.Response.Headers.Remove("X-Powered-By"); - httpContext.Response.Headers.Remove("X-AspNet-Version"); - httpContext.Response.Headers.Remove("X-AspNetMvc-Version"); - } - catch (PlatformNotSupportedException) - { - // can't remove headers this way on IIS6 or cassini. - } + var httpContext = ((HttpApplication) sender).Context; + Logger.Debug("Begin request: {0}.", () => httpContext.Request.Url); + BeginRequest(new HttpContextWrapper(httpContext)); }; - app.PostResolveRequestCache += (sender, e) => - { - var httpContext = ((HttpApplication)sender).Context; - ProcessRequest(new HttpContextWrapper(httpContext)); - }; + //disable asp.net headers (security) + // This is the correct place to modify headers according to MS: + // https://our.umbraco.org/forum/umbraco-7/using-umbraco-7/65241-Heap-error-from-header-manipulation?p=0#comment220889 + app.PostReleaseRequestState += (sender, args) => + { + var httpContext = ((HttpApplication) sender).Context; + try + { + httpContext.Response.Headers.Remove("Server"); + //this doesn't normally work since IIS sets it but we'll keep it here anyways. + httpContext.Response.Headers.Remove("X-Powered-By"); + httpContext.Response.Headers.Remove("X-AspNet-Version"); + httpContext.Response.Headers.Remove("X-AspNetMvc-Version"); + } + catch (PlatformNotSupportedException) + { + // can't remove headers this way on IIS6 or cassini. + } + }; - app.EndRequest += (sender, args) => - { - var httpContext = ((HttpApplication)sender).Context; - if (UmbracoContext.Current != null && UmbracoContext.Current.IsFrontEndUmbracoRequest) - { - LogHelper.Debug( - "Total milliseconds for umbraco request to process: {0}", () => DateTime.Now.Subtract(UmbracoContext.Current.ObjectCreated).TotalMilliseconds); - } + app.PostResolveRequestCache += (sender, e) => + { + var httpContext = ((HttpApplication) sender).Context; + ProcessRequest(new HttpContextWrapper(httpContext)); + }; - OnEndRequest(new EventArgs()); + app.EndRequest += (sender, args) => + { + var httpContext = ((HttpApplication) sender).Context; + if (UmbracoContext.Current != null && UmbracoContext.Current.IsFrontEndUmbracoRequest) + { + Logger.Debug($"End Request. ({DateTime.Now.Subtract(UmbracoContext.Current.ObjectCreated).TotalMilliseconds}ms)"); + } - DisposeHttpContextItems(httpContext); - }; + OnEndRequest(new EventArgs()); + + DisposeHttpContextItems(httpContext); + }; } public void Dispose() @@ -530,28 +571,30 @@ namespace Umbraco.Web /// /// This is basically used to reserve paths dynamically /// - private readonly Lazy _combinedRouteCollection = new Lazy(() => - { - var allRoutes = new RouteCollection(); + private readonly Lazy _combinedRouteCollection; + + private RouteCollection CreateRouteCollection() + { + var routes = new RouteCollection(); + foreach (var route in RouteTable.Routes) - { - allRoutes.Add(route); - } + routes.Add(route); + foreach (var reservedPath in ReservedPaths) { try { - allRoutes.Add("_umbreserved_" + reservedPath.ReplaceNonAlphanumericChars(""), - new Route(reservedPath.TrimStart('/'), new StopRoutingHandler())); + routes.Add("_umbreserved_" + reservedPath.ReplaceNonAlphanumericChars(""), + new Route(reservedPath.TrimStart('/'), new StopRoutingHandler())); } catch (Exception ex) { - LogHelper.Error("Could not add reserved path route", ex); + Logger.Error("Could not add reserved path route", ex); } } - return allRoutes; - }); + return routes; + } /// /// This is used internally to track any registered callback paths for Identity providers. If the request path matches diff --git a/src/Umbraco.Web/WebApi/Filters/AngularAntiForgeryHelper.cs b/src/Umbraco.Web/WebApi/Filters/AngularAntiForgeryHelper.cs index 962183f7ef..d1262bb657 100644 --- a/src/Umbraco.Web/WebApi/Filters/AngularAntiForgeryHelper.cs +++ b/src/Umbraco.Web/WebApi/Filters/AngularAntiForgeryHelper.cs @@ -62,7 +62,7 @@ namespace Umbraco.Web.WebApi.Filters } catch (Exception ex) { - LogHelper.Error(typeof(AngularAntiForgeryHelper), "Could not validate XSRF token", ex); + Current.Logger.Error(typeof(AngularAntiForgeryHelper), "Could not validate XSRF token", ex); return false; } return true; diff --git a/src/Umbraco.Web/WebApi/Filters/ContentItemValidationHelper.cs b/src/Umbraco.Web/WebApi/Filters/ContentItemValidationHelper.cs index 88eda3c64e..adcb56f6d1 100644 --- a/src/Umbraco.Web/WebApi/Filters/ContentItemValidationHelper.cs +++ b/src/Umbraco.Web/WebApi/Filters/ContentItemValidationHelper.cs @@ -119,7 +119,7 @@ namespace Umbraco.Web.WebApi.Filters if (editor == null) { var message = string.Format("The property editor with alias: {0} was not found for property with id {1}", p.DataType.PropertyEditorAlias, p.Id); - LogHelper.Warn>(message); + Current.Logger.Warn>(message); //actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.NotFound, message); //return false; continue; diff --git a/src/Umbraco.Web/WebApi/Filters/FileUploadCleanupFilterAttribute.cs b/src/Umbraco.Web/WebApi/Filters/FileUploadCleanupFilterAttribute.cs index ef2b70e44c..3236d80b33 100644 --- a/src/Umbraco.Web/WebApi/Filters/FileUploadCleanupFilterAttribute.cs +++ b/src/Umbraco.Web/WebApi/Filters/FileUploadCleanupFilterAttribute.cs @@ -65,7 +65,7 @@ namespace Umbraco.Web.WebApi.Filters } catch (System.Exception ex) { - LogHelper.Error("Could not delete temp file " + f.TempFilePath, ex); + Current.Logger.Error("Could not delete temp file " + f.TempFilePath, ex); } } } @@ -75,17 +75,17 @@ namespace Umbraco.Web.WebApi.Filters { if (actionExecutedContext == null) { - LogHelper.Warn("The actionExecutedContext is null!!??"); + Current.Logger.Warn("The actionExecutedContext is null!!??"); return; } if (actionExecutedContext.Request == null) { - LogHelper.Warn("The actionExecutedContext.Request is null!!??"); + Current.Logger.Warn("The actionExecutedContext.Request is null!!??"); return; } if (actionExecutedContext.Request.Content == null) { - LogHelper.Warn("The actionExecutedContext.Request.Content is null!!??"); + Current.Logger.Warn("The actionExecutedContext.Request.Content is null!!??"); return; } @@ -97,7 +97,7 @@ namespace Umbraco.Web.WebApi.Filters } catch (System.Exception ex) { - LogHelper.Error("Could not acquire actionExecutedContext.Response.Content", ex); + Current.Logger.Error("Could not acquire actionExecutedContext.Response.Content", ex); return; } @@ -120,7 +120,7 @@ namespace Umbraco.Web.WebApi.Filters tempFolders.Add(dir); } - LogHelper.Debug("Removing temp file " + f.TempFilePath); + Current.Logger.Debug("Removing temp file " + f.TempFilePath); try { @@ -128,7 +128,7 @@ namespace Umbraco.Web.WebApi.Filters } catch (System.Exception ex) { - LogHelper.Error("Could not delete temp file " + f.TempFilePath, ex); + Current.Logger.Error("Could not delete temp file " + f.TempFilePath, ex); } //clear out the temp path so it's not returned in the response @@ -136,23 +136,23 @@ namespace Umbraco.Web.WebApi.Filters } else { - LogHelper.Warn("The f.TempFilePath is null or whitespace!!??"); + Current.Logger.Warn("The f.TempFilePath is null or whitespace!!??"); } } } else { - LogHelper.Warn("The uploadedFiles.UploadedFiles is null!!??"); + Current.Logger.Warn("The uploadedFiles.UploadedFiles is null!!??"); } } else { - LogHelper.Warn("The actionExecutedContext.Request.Content.Value is not IHaveUploadedFiles, it is " + objectContent.Value.GetType()); + Current.Logger.Warn("The actionExecutedContext.Request.Content.Value is not IHaveUploadedFiles, it is " + objectContent.Value.GetType()); } } else { - LogHelper.Warn("The actionExecutedContext.Request.Content is not ObjectContent, it is " + actionExecutedContext.Request.Content.GetType()); + Current.Logger.Warn("The actionExecutedContext.Request.Content is not ObjectContent, it is " + actionExecutedContext.Request.Content.GetType()); } } @@ -170,7 +170,7 @@ namespace Umbraco.Web.WebApi.Filters } catch (System.Exception ex) { - LogHelper.Error("Could not delete temp file " + file, ex); + Current.Logger.Error("Could not delete temp file " + file, ex); } } } diff --git a/src/Umbraco.Web/WebRuntimeComponent.cs b/src/Umbraco.Web/WebRuntimeComponent.cs index 6538641509..628cd9c66a 100644 --- a/src/Umbraco.Web/WebRuntimeComponent.cs +++ b/src/Umbraco.Web/WebRuntimeComponent.cs @@ -290,15 +290,19 @@ namespace Umbraco.Web // set routes CreateRoutes(surfaceControllerTypes, apiControllerTypes); + // get an http context + // fixme - although HttpContext.Current is NOT null during Application_Start + // it does NOT have a request and therefore no request ... + var httpContext = new HttpContextWrapper(HttpContext.Current); + //before we do anything, we'll ensure the umbraco context //see: http://issues.umbraco.org/issue/U4-1717 - var httpContext = new HttpContextWrapper(HttpContext.Current); UmbracoContext.EnsureContext( // fixme - refactor! UmbracoContext & UmbracoRequestContext! + inject, accessor, etc httpContext, - Current.FacadeService, - new WebSecurity(httpContext, Current.Services.UserService), + Current.FacadeService, // fixme inject! stop using current here! + new WebSecurity(httpContext, Current.Services.UserService),// fixme inject! stop using current here! UmbracoConfig.For.UmbracoSettings(), - Current.UrlProviders, + Current.UrlProviders,// fixme inject! stop using current here! false); // rebuild any empty indexes diff --git a/src/Umbraco.Web/WebServices/ExamineManagementApiController.cs b/src/Umbraco.Web/WebServices/ExamineManagementApiController.cs index 73c3d393a3..ef1c774df5 100644 --- a/src/Umbraco.Web/WebServices/ExamineManagementApiController.cs +++ b/src/Umbraco.Web/WebServices/ExamineManagementApiController.cs @@ -190,7 +190,7 @@ namespace Umbraco.Web.WebServices { //ensure it's not listening indexer.IndexOperationComplete -= Indexer_IndexOperationComplete; - LogHelper.Error("An error occurred rebuilding index", ex); + Logger.Error("An error occurred rebuilding index", ex); var response = Request.CreateResponse(HttpStatusCode.Conflict); response.Content = new StringContent(string.Format("The index could not be rebuilt at this time, most likely there is another thread currently writing to the index. Error: {0}", ex)); response.ReasonPhrase = "Could Not Rebuild"; @@ -273,7 +273,7 @@ namespace Umbraco.Web.WebServices var val = p.GetValue(indexer, null); if (val == null) { - LogHelper.Warn("Property value was null when setting up property on indexer: " + indexer.Key + " property: " + p.Name); + Logger.Warn("Property value was null when setting up property on indexer: " + indexer.Key + " property: " + p.Name); val = string.Empty; } indexerModel.ProviderProperties.Add(p.Name, val.ToString()); diff --git a/src/Umbraco.Web/WebServices/SaveFileController.cs b/src/Umbraco.Web/WebServices/SaveFileController.cs index 280e924083..b6091ff4a5 100644 --- a/src/Umbraco.Web/WebServices/SaveFileController.cs +++ b/src/Umbraco.Web/WebServices/SaveFileController.cs @@ -305,7 +305,7 @@ namespace Umbraco.Web.WebServices private JsonResult Failed(string message, string header, Exception exception = null) { if (exception != null) - LogHelper.Error("An error occurred saving a file. " + message, exception); + Logger.Error("An error occurred saving a file. " + message, exception); return Json(new { success = false, diff --git a/src/Umbraco.Web/WebServices/ScheduledPublishController.cs b/src/Umbraco.Web/WebServices/ScheduledPublishController.cs index c1ba4f4bdb..dc6afe1f52 100644 --- a/src/Umbraco.Web/WebServices/ScheduledPublishController.cs +++ b/src/Umbraco.Web/WebServices/ScheduledPublishController.cs @@ -41,7 +41,7 @@ namespace Umbraco.Web.WebServices } catch (Exception ee) { - LogHelper.Error("Error executing scheduled task", ee); + Logger.Error("Error executing scheduled task", ee); Response.StatusCode = 400; diff --git a/src/Umbraco.Web/_Legacy/Actions/Action.cs b/src/Umbraco.Web/_Legacy/Actions/Action.cs index 9da231e1ad..3ef807e984 100644 --- a/src/Umbraco.Web/_Legacy/Actions/Action.cs +++ b/src/Umbraco.Web/_Legacy/Actions/Action.cs @@ -107,7 +107,7 @@ namespace Umbraco.Web._Legacy.Actions } catch (Exception ee) { - LogHelper.Error("Error registrering action to javascript", ee); + Current.Logger.Error("Error registrering action to javascript", ee); } } diff --git a/src/Umbraco.Web/_Legacy/PackageActions/addStringToHtmlElement.cs b/src/Umbraco.Web/_Legacy/PackageActions/addStringToHtmlElement.cs index 788cb0bd83..36073bb574 100644 --- a/src/Umbraco.Web/_Legacy/PackageActions/addStringToHtmlElement.cs +++ b/src/Umbraco.Web/_Legacy/PackageActions/addStringToHtmlElement.cs @@ -122,12 +122,12 @@ namespace Umbraco.Web._Legacy.PackageActions } catch (Exception ex) { - LogHelper.Error("An error occurred", ex); + Current.Logger.Error("An error occurred", ex); } } else { - LogHelper.Debug("template not found"); + Current.Logger.Debug("template not found"); } } @@ -170,12 +170,12 @@ namespace Umbraco.Web._Legacy.PackageActions } catch (Exception ex) { - LogHelper.Error("An error occurred", ex); + Current.Logger.Error("An error occurred", ex); } } else { - LogHelper.Debug("template not found"); + Current.Logger.Debug("template not found"); } } diff --git a/src/Umbraco.Web/umbraco.presentation/default.aspx.cs b/src/Umbraco.Web/umbraco.presentation/default.aspx.cs index 0ae9c52af5..c2aa38c663 100644 --- a/src/Umbraco.Web/umbraco.presentation/default.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/default.aspx.cs @@ -54,7 +54,7 @@ namespace umbraco protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); - using (DisposableTimer.DebugDuration("PreInit")) + using (Current.ProfilingLogger.DebugDuration("PreInit")) { // handle the infamous umbDebugShowTrace, etc @@ -91,7 +91,7 @@ namespace umbraco protected override void OnInit(EventArgs e) { - using (DisposableTimer.DebugDuration("Init")) + using (Current.ProfilingLogger.DebugDuration("Init")) { base.OnInit(e); @@ -138,7 +138,7 @@ namespace umbraco protected override void OnLoad(EventArgs e) { - using (DisposableTimer.DebugDuration("Load")) + using (Current.ProfilingLogger.DebugDuration("Load")) { base.OnLoad(e); @@ -149,7 +149,7 @@ namespace umbraco protected override void Render(HtmlTextWriter writer) { - using (DisposableTimer.DebugDuration("Render")) + using (Current.ProfilingLogger.DebugDuration("Render")) { // do the original rendering @@ -163,7 +163,7 @@ namespace umbraco // filter / add preview banner if (UmbracoContext.Current.InPreviewMode) { - LogHelper.Debug("Umbraco is running in preview mode.", true); + Current.Logger.Debug("Umbraco is running in preview mode."); if (Response.ContentType.InvariantEquals("text/html")) // ASP.NET default value { diff --git a/src/Umbraco.Web/umbraco.presentation/item.cs b/src/Umbraco.Web/umbraco.presentation/item.cs index 193b0a7c27..bcecdfd043 100644 --- a/src/Umbraco.Web/umbraco.presentation/item.cs +++ b/src/Umbraco.Web/umbraco.presentation/item.cs @@ -120,7 +120,7 @@ namespace umbraco /// private string GetRecursiveValueLegacy(IDictionary elements) { - using (DisposableTimer.DebugDuration("Checking recusively")) + using (Current.ProfilingLogger.DebugDuration("Checking recusively")) { var content = ""; @@ -156,7 +156,7 @@ namespace umbraco private void ParseItem(IDictionary attributes) { - using (DisposableTimer.DebugDuration("Start parsing " + _fieldName)) + using (Current.ProfilingLogger.DebugDuration("Start parsing " + _fieldName)) { HttpContext.Current.Trace.Write("item", "Start parsing '" + _fieldName + "'"); if (helper.FindAttribute(attributes, "textIfEmpty") != "" && _fieldContent == "") diff --git a/src/Umbraco.Web/umbraco.presentation/library.cs b/src/Umbraco.Web/umbraco.presentation/library.cs index 3cf140f56f..3dc29c9c12 100644 --- a/src/Umbraco.Web/umbraco.presentation/library.cs +++ b/src/Umbraco.Web/umbraco.presentation/library.cs @@ -338,10 +338,10 @@ namespace umbraco } catch(Exception ex) { - LogHelper.Error("An error occurred looking up media", ex); + Current.Logger.Error("An error occurred looking up media", ex); } - LogHelper.Debug("No media result for id {0}", () => MediaId); + Current.Logger.Debug("No media result for id {0}", () => MediaId); var errorXml = new XElement("error", string.Format("No media is maching '{0}'", MediaId)); return errorXml.CreateNavigator().Select("/"); @@ -393,10 +393,10 @@ namespace umbraco } catch (Exception ex) { - LogHelper.Error("An error occurred looking up member", ex); + Current.Logger.Error("An error occurred looking up member", ex); } - LogHelper.Debug("No member result for id {0}", () => MemberId); + Current.Logger.Debug("No member result for id {0}", () => MemberId); var xd = new XmlDocument(); xd.LoadXml(string.Format("No member is maching '{0}'", MemberId)); @@ -1217,7 +1217,7 @@ namespace umbraco } catch (Exception ex) { - LogHelper.Error("Could not retrieve current xml node", ex); + Current.Logger.Error("Could not retrieve current xml node", ex); } XmlDocument xd = new XmlDocument(); @@ -1442,7 +1442,7 @@ namespace umbraco } catch (Exception ee) { - LogHelper.Error("umbraco.library.SendMail: Error sending mail.", ee); + Current.Logger.Error("umbraco.library.SendMail: Error sending mail.", ee); } } diff --git a/src/Umbraco.Web/umbraco.presentation/page.cs b/src/Umbraco.Web/umbraco.presentation/page.cs index e22928cc14..aa6a0b3491 100644 --- a/src/Umbraco.Web/umbraco.presentation/page.cs +++ b/src/Umbraco.Web/umbraco.presentation/page.cs @@ -329,16 +329,14 @@ namespace umbraco if (_elements.ContainsKey(alias)) { - LogHelper.Debug( - string.Format("Aliases must be unique, an element with alias \"{0}\" has already been loaded!", alias), - true); + Current.Logger.Debug( + string.Format("Aliases must be unique, an element with alias \"{0}\" has already been loaded!", alias)); } else { _elements[alias] = value; - LogHelper.Debug( - string.Format("Load element \"{0}\"", alias), - true); + Current.Logger.Debug( + string.Format("Load element \"{0}\"", alias)); } } } diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/controls/Tree/JTreeContextMenu.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/controls/Tree/JTreeContextMenu.cs index 60109160f9..920fbe5c7d 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/controls/Tree/JTreeContextMenu.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/controls/Tree/JTreeContextMenu.cs @@ -46,7 +46,7 @@ namespace umbraco.controls.Tree } catch (Exception ee) { - LogHelper.Error("Error initializing tree action", ee); + Current.Logger.Error("Error initializing tree action", ee); } } diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/create/CreatedPackageTasks.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/create/CreatedPackageTasks.cs index dd295515ca..3245be350b 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/create/CreatedPackageTasks.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/create/CreatedPackageTasks.cs @@ -1,6 +1,7 @@ using Umbraco.Core.Logging; using Umbraco.Web.UI; using Umbraco.Core; +using Umbraco.Web; using Umbraco.Web._Legacy.UI; namespace umbraco @@ -10,7 +11,7 @@ namespace umbraco public override bool PerformSave() { - LogHelper.Info("Xml save started"); + Current.Logger.Info("Xml save started"); int id = cms.businesslogic.packager.CreatedPackage.MakeNew(Alias).Data.Id; _returnUrl = string.Format("developer/packages/editPackage.aspx?id={0}", id); return true; diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/create/XsltTasks.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/create/XsltTasks.cs index a4040a4b5b..3c92126422 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/create/XsltTasks.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/create/XsltTasks.cs @@ -91,7 +91,7 @@ namespace umbraco } catch (Exception ex) { - LogHelper.Error(string.Format("Could not remove XSLT file {0} - User {1}", Alias, UmbracoContext.Current.Security.GetUserId()), ex); + Current.Logger.Error(string.Format("Could not remove XSLT file {0} - User {1}", Alias, UmbracoContext.Current.Security.GetUserId()), ex); } return true; } diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/create/dictionaryTasks.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/create/dictionaryTasks.cs index 355b2aa5fe..89a87dc8da 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/create/dictionaryTasks.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/create/dictionaryTasks.cs @@ -33,7 +33,7 @@ namespace umbraco public override bool PerformDelete() { - LogHelper.Debug(TypeID + " " + ParentID + " deleting " + Alias); + Current.Logger.Debug(TypeID + " " + ParentID + " deleting " + Alias); var di = Current.Services.LocalizationService.GetDictionaryItemById(ParentID); if (di == null) return true; diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/create/userTasks.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/create/userTasks.cs index d2a04d5214..239b1f4e50 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/create/userTasks.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/create/userTasks.cs @@ -64,7 +64,7 @@ namespace umbraco } catch (Exception ex) { - LogHelper.Error(string.Format("Failed to create the user. Error from provider: {0}", status.ToString()), ex); + Current.Logger.Error(string.Format("Failed to create the user. Error from provider: {0}", status.ToString()), ex); return false; } } diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/dashboard/FeedProxy.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/dashboard/FeedProxy.aspx.cs index b6f1f1a0b6..08a314392d 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/dashboard/FeedProxy.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/dashboard/FeedProxy.aspx.cs @@ -46,7 +46,7 @@ namespace dashboardUtilities } else { - LogHelper.Debug(string.Format("Access to unallowed feedproxy attempted: {0}", requestUri)); + Current.Logger.Debug(string.Format("Access to unallowed feedproxy attempted: {0}", requestUri)); } } } @@ -54,7 +54,7 @@ namespace dashboardUtilities } catch (Exception ex) { - LogHelper.Error("Exception occurred", ex); + Current.Logger.Error("Exception occurred", ex); } } } diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Packages/LoadNitros.ascx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Packages/LoadNitros.ascx.cs index 9c9921810b..6e7f432e2b 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Packages/LoadNitros.ascx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Packages/LoadNitros.ascx.cs @@ -188,7 +188,7 @@ namespace umbraco.presentation.developer.packages { } catch (Exception ex) { - LogHelper.Error("An error occurred", ex); + Current.Logger.Error("An error occurred", ex); loadNitros.Controls.Clear(); loadNitros.Controls.Add(fb); diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Packages/installedPackage.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Packages/installedPackage.aspx.cs index 64e36ba6ee..a7f6816959 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Packages/installedPackage.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Packages/installedPackage.aspx.cs @@ -508,7 +508,7 @@ namespace umbraco.presentation.developer.packages var actionsXml = new XmlDocument(); actionsXml.LoadXml("" + _pack.Data.Actions + ""); - LogHelper.Debug("executing undo actions: {0}", () => actionsXml.OuterXml); + Current.Logger.Debug("executing undo actions: {0}", () => actionsXml.OuterXml); foreach (XmlNode n in actionsXml.DocumentElement.SelectNodes("//Action")) { @@ -518,13 +518,13 @@ namespace umbraco.presentation.developer.packages } catch (Exception ex) { - LogHelper.Error("An error occurred running undo actions", ex); + Current.Logger.Error("An error occurred running undo actions", ex); } } } catch (Exception ex) { - LogHelper.Error("An error occurred running undo actions", ex); + Current.Logger.Error("An error occurred running undo actions", ex); } //moved remove of files here so custom package actions can still undo diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/importDocumenttype.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/importDocumenttype.aspx.cs index 9f7f8d0527..3de9de8501 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/importDocumenttype.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/importDocumenttype.aspx.cs @@ -89,7 +89,7 @@ namespace umbraco.presentation.umbraco.dialogs } catch(Exception ex) { - Umbraco.Core.Logging.LogHelper.Error(typeof(importDocumentType), "Error cleaning up temporary udt file in App_Data: " + ex.Message, ex); + Current.Logger.Error(typeof(importDocumentType), "Error cleaning up temporary udt file in App_Data: " + ex.Message, ex); } Wizard.Visible = false; diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/protectPage.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/protectPage.aspx.cs index 49df700caf..8082ad0be5 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/protectPage.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/protectPage.aspx.cs @@ -248,7 +248,7 @@ namespace umbraco.presentation.umbraco.dialogs } catch (Exception ex) { - LogHelper.Error("An error occurred initializing the protect page editor", ex); + Current.Logger.Error("An error occurred initializing the protect page editor", ex); } if (GetProtectionType(documentId) == ProtectionType.Simple) diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/sendToTranslation.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/sendToTranslation.aspx.cs index 85a1bcac3f..6433c01aba 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/sendToTranslation.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/sendToTranslation.aspx.cs @@ -178,14 +178,14 @@ namespace umbraco.presentation.dialogs } catch (Exception ex) { - LogHelper.Error("Error sending translation e-mail", ex); + Current.Logger.Error("Error sending translation e-mail", ex); } } } else { - LogHelper.Warn("Could not send translation e-mail because either user or translator lacks e-mail in settings"); + Current.Logger.Warn("Could not send translation e-mail because either user or translator lacks e-mail in settings"); } } diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/ItemRenderer.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/ItemRenderer.cs index 625b93e37f..0e11e510a5 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/ItemRenderer.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/ItemRenderer.cs @@ -146,7 +146,7 @@ namespace umbraco.presentation.templateControls /// The item. public virtual void Load(Item item) { - using (DisposableTimer.DebugDuration(string.Format("Item: {0}", item.Field))) + using (Current.ProfilingLogger.DebugDuration(string.Format("Item: {0}", item.Field))) { ParseMacros(item); } @@ -172,7 +172,7 @@ namespace umbraco.presentation.templateControls } else { - using (DisposableTimer.DebugDuration("Parsing Macros")) + using (Current.ProfilingLogger.DebugDuration("Parsing Macros")) { MacroTagParser.ParseMacros( diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/users/EditUser.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/users/EditUser.aspx.cs index 4c55278360..39bfd9c3f5 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/users/EditUser.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/users/EditUser.aspx.cs @@ -387,7 +387,7 @@ namespace umbraco.cms.presentation.user catch (Exception ex) { ClientTools.ShowSpeechBubble(SpeechBubbleIcon.Error, Services.TextService.Localize("speechBubbles/editUserError"), ""); - LogHelper.Error("Exception", ex); + Current.Logger.Error("Exception", ex); } } else diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/CacheRefresher.asmx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/CacheRefresher.asmx.cs index 1e4484f39c..25e8be8c61 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/CacheRefresher.asmx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/CacheRefresher.asmx.cs @@ -31,7 +31,7 @@ namespace umbraco.presentation.webservices if (string.IsNullOrEmpty(hash)) return false; // no hash = don't know = not self if (hash != WebServiceServerMessenger.GetCurrentServerHash()) return false; - LogHelper.Debug( + Current.Logger.Debug( "Ignoring self-message. (server: {0}, appId: {1}, hash: {2})", () => NetworkHelper.MachineName, () => HttpRuntime.AppDomainAppId, diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/nodeSorter.asmx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/nodeSorter.asmx.cs index 9dffb871f0..a192cac61c 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/nodeSorter.asmx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/nodeSorter.asmx.cs @@ -136,7 +136,7 @@ namespace umbraco.presentation.webservices } catch (Exception ex) { - LogHelper.Error("Could not update media sort order", ex); + Current.Logger.Error("Could not update media sort order", ex); } } @@ -188,7 +188,7 @@ namespace umbraco.presentation.webservices } catch (Exception ex) { - LogHelper.Error("Could not update content sort order", ex); + Current.Logger.Error("Could not update content sort order", ex); } } diff --git a/src/UmbracoExamine/LocalStorage/LocalTempStorageIndexer.cs b/src/UmbracoExamine/LocalStorage/LocalTempStorageIndexer.cs index 5d2870c4a8..e15144d5ad 100644 --- a/src/UmbracoExamine/LocalStorage/LocalTempStorageIndexer.cs +++ b/src/UmbracoExamine/LocalStorage/LocalTempStorageIndexer.cs @@ -10,6 +10,7 @@ using Lucene.Net.Analysis; using Lucene.Net.Index; using Lucene.Net.Store; using Umbraco.Core; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Directory = System.IO.Directory; @@ -59,7 +60,7 @@ namespace UmbracoExamine.LocalStorage } catch (Exception ex) { - LogHelper.Error( + Current.Logger.Error( string.Format("Could not create a temp storage location of type {0}, reverting to use the " + typeof (CodeGenLocalStorageDirectory).FullName, dirType), ex); } @@ -105,16 +106,16 @@ namespace UmbracoExamine.LocalStorage } catch (Exception ex) { - LogHelper.WarnWithException( - string.Format("Could not open an index reader, local temp storage index is empty or corrupt... retrying... {0}", configuredPath), - ex); + Current.Logger.Warn( + ex, + string.Format("Could not open an index reader, local temp storage index is empty or corrupt... retrying... {0}", configuredPath)); } return Attempt.Fail(false); }, 5, TimeSpan.FromSeconds(1)); if (result.Success == false) { - LogHelper.Warn( + Current.Logger.Warn( string.Format("Could not open an index reader, local temp storage index is empty or corrupt... attempting to clear index files in local temp storage, will operate from main storage only {0}", configuredPath)); ClearFilesInPath(TempPath); @@ -152,7 +153,7 @@ namespace UmbracoExamine.LocalStorage } catch (Exception exInner) { - LogHelper.Error("Could not delete local temp storage index file", exInner); + Current.Logger.Error("Could not delete local temp storage index file", exInner); } } } @@ -178,7 +179,7 @@ namespace UmbracoExamine.LocalStorage { if (file.InvariantEquals("write.lock")) { - LogHelper.Warn("The lock file could not be deleted but should be removed when the writer is disposed"); + Current.Logger.Warn("The lock file could not be deleted but should be removed when the writer is disposed"); } } @@ -189,7 +190,7 @@ namespace UmbracoExamine.LocalStorage } catch (Exception ex) { - LogHelper.Error("Could not clear corrupt index from main index folder, the index cannot be used", ex); + Current.Logger.Error("Could not clear corrupt index from main index folder, the index cannot be used", ex); return false; } } @@ -210,7 +211,7 @@ namespace UmbracoExamine.LocalStorage } catch (Exception ex) { - LogHelper.WarnWithException("Could not create index writer with snapshot policy for copying... retrying...", ex); + Current.Logger.Warn(ex, "Could not create index writer with snapshot policy for copying... retrying..."); return Attempt.Fail(ex); } } @@ -230,14 +231,14 @@ namespace UmbracoExamine.LocalStorage //last try... if (currentTry == maxTries) { - LogHelper.Info("Could not acquire index lock, attempting to force unlock it..."); + Current.Logger.Info("Could not acquire index lock, attempting to force unlock it..."); //unlock it! IndexWriter.Unlock(baseLuceneDirectory); } var writerAttempt = TryCreateWriter(baseLuceneDirectory, analyzer); if (writerAttempt) return writerAttempt; - LogHelper.Info("Could not create writer on {0}, retrying ....", baseLuceneDirectory.ToString); + Current.Logger.Info("Could not create writer on {0}, retrying ....", baseLuceneDirectory.ToString); return Attempt.Fail(); }, 5, TimeSpan.FromSeconds(1)); @@ -253,13 +254,13 @@ namespace UmbracoExamine.LocalStorage //last try... if (currentTry == maxTries) { - LogHelper.Info("Could not acquire directory lock, attempting to force unlock it..."); + Current.Logger.Info("Could not acquire directory lock, attempting to force unlock it..."); //unlock it! IndexWriter.Unlock(dir); } if (IndexWriter.IsLocked(dir) == false) return Attempt.Succeed(true); - LogHelper.Info("Could not acquire directory lock for {0} writer, retrying ....", dir.ToString); + Current.Logger.Info("Could not acquire directory lock for {0} writer, retrying ....", dir.ToString); return Attempt.Fail(); }, 5, TimeSpan.FromSeconds(1)); @@ -282,7 +283,7 @@ namespace UmbracoExamine.LocalStorage if (writerAttempt.Success == false) { - LogHelper.Error("Could not create index writer with snapshot policy for copying, the index cannot be used", writerAttempt.Exception); + Current.Logger.Error("Could not create index writer with snapshot policy for copying, the index cannot be used", writerAttempt.Exception); return InitializeDirectoryFlags.FailedLocked; } @@ -298,14 +299,14 @@ namespace UmbracoExamine.LocalStorage { writerAttempt.Result.Dispose(); - LogHelper.Error( + Current.Logger.Error( string.Format("Could not open an index reader, {0} is empty or corrupt... attempting to clear index files in master folder", configuredPath), ex); if (ClearLuceneDirFiles(baseLuceneDirectory) == false) { //hrm, not much we can do in this situation, but this shouldn't happen - LogHelper.Error("Could not open an index reader, index is corrupt.", ex); + Current.Logger.Error("Could not open an index reader, index is corrupt.", ex); return InitializeDirectoryFlags.FailedCorrupt; } @@ -314,7 +315,7 @@ namespace UmbracoExamine.LocalStorage if (writerAttempt.Success == false) { //ultra fail... - LogHelper.Error("Could not create index writer with snapshot policy for copying, the index cannot be used", writerAttempt.Exception); + Current.Logger.Error("Could not create index writer with snapshot policy for copying, the index cannot be used", writerAttempt.Exception); return InitializeDirectoryFlags.FailedLocked; } } @@ -358,10 +359,10 @@ namespace UmbracoExamine.LocalStorage if (file.InvariantEquals("write.lock")) { //This might happen if the writer is open - LogHelper.Warn("The lock file could not be deleted but should be removed when the writer is disposed"); + Current.Logger.Warn("The lock file could not be deleted but should be removed when the writer is disposed"); } - LogHelper.Debug("Could not delete non synced index file file, index sync will continue but old index files will remain - this shouldn't affect indexing/searching operations. {0}", () => ex.ToString()); + Current.Logger.Debug("Could not delete non synced index file file, index sync will continue but old index files will remain - this shouldn't affect indexing/searching operations. {0}", () => ex.ToString()); } } @@ -369,7 +370,7 @@ namespace UmbracoExamine.LocalStorage else { //quit here, this shouldn't happen with all the checks above. - LogHelper.Warn("Cannot sync index files from main storage, the temp file index is currently locked"); + Current.Logger.Warn("Cannot sync index files from main storage, the temp file index is currently locked"); return InitializeDirectoryFlags.FailedLocked; } @@ -389,7 +390,7 @@ namespace UmbracoExamine.LocalStorage } catch (IOException ex) { - LogHelper.Error("Could not copy index file, could not sync from main storage", ex); + Current.Logger.Error("Could not copy index file, could not sync from main storage", ex); //quit here return InitializeDirectoryFlags.FailedFileSync; @@ -403,7 +404,7 @@ namespace UmbracoExamine.LocalStorage } } - LogHelper.Info("Successfully sync'd main index to local temp storage for index: {0}", () => configuredPath); + Current.Logger.Info("Successfully sync'd main index to local temp storage for index: {0}", () => configuredPath); return InitializeDirectoryFlags.Success; } } diff --git a/src/UmbracoExamine/UmbracoExamineSearcher.cs b/src/UmbracoExamine/UmbracoExamineSearcher.cs index 2cadacae11..9a0f1df158 100644 --- a/src/UmbracoExamine/UmbracoExamineSearcher.cs +++ b/src/UmbracoExamine/UmbracoExamineSearcher.cs @@ -119,7 +119,7 @@ namespace UmbracoExamine } catch (Exception ex) { - LogHelper.Error( + Current.Logger.Error( string.Format("Could not create a temp storage location of type {0}, reverting to use the " + typeof(CodeGenLocalStorageDirectory).FullName, dirType), ex); } diff --git a/src/umbraco.cms/businesslogic/LegacySqlHelper.cs b/src/umbraco.cms/businesslogic/LegacySqlHelper.cs index b1d206cce4..614b1f04d9 100644 --- a/src/umbraco.cms/businesslogic/LegacySqlHelper.cs +++ b/src/umbraco.cms/businesslogic/LegacySqlHelper.cs @@ -2,6 +2,7 @@ using System; using System.Configuration; using umbraco.DataLayer; using Umbraco.Core; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.Logging; namespace umbraco.cms.businesslogic @@ -41,7 +42,7 @@ namespace umbraco.cms.businesslogic } catch(Exception ex) { - LogHelper.Error(string.Format("Can't instantiate SQLHelper with connectionstring \"{0}\"", connectionString), ex); + Current.Logger.Error(string.Format("Can't instantiate SQLHelper with connectionstring \"{0}\"", connectionString), ex); } } diff --git a/src/umbraco.cms/businesslogic/Packager/Installer.cs b/src/umbraco.cms/businesslogic/Packager/Installer.cs index 2f6b4175f4..69cd0674bb 100644 --- a/src/umbraco.cms/businesslogic/Packager/Installer.cs +++ b/src/umbraco.cms/businesslogic/Packager/Installer.cs @@ -177,9 +177,9 @@ namespace umbraco.cms.businesslogic.packager /// public string Import(string inputFile, bool deleteFile) { - using (DisposableTimer.DebugDuration( - () => "Importing package file " + inputFile, - () => "Package file " + inputFile + "imported")) + using (Current.ProfilingLogger.DebugDuration( + $"Importing package file {inputFile}.", + $"Package file {inputFile} imported.")) { var tempDir = ""; if (File.Exists(IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + inputFile))) @@ -258,9 +258,9 @@ namespace umbraco.cms.businesslogic.packager public void InstallFiles(int packageId, string tempDir) { - using (DisposableTimer.DebugDuration( - () => "Installing package files for package id " + packageId + " into temp folder " + tempDir, - () => "Package file installation complete for package id " + packageId)) + using (Current.ProfilingLogger.DebugDuration( + "Installing package files for package id " + packageId + " into temp folder " + tempDir, + "Package file installation complete for package id " + packageId)) { //retrieve the manifest to continue installation var insPack = InstalledPackage.GetById(packageId); @@ -308,9 +308,9 @@ namespace umbraco.cms.businesslogic.packager public void InstallBusinessLogic(int packageId, string tempDir) { - using (DisposableTimer.DebugDuration( - () => "Installing business logic for package id " + packageId + " into temp folder " + tempDir, - () => "Package business logic installation complete for package id " + packageId)) + using (Current.ProfilingLogger.DebugDuration( + "Installing business logic for package id " + packageId + " into temp folder " + tempDir, + "Package business logic installation complete for package id " + packageId)) { //retrieve the manifest to continue installation var insPack = InstalledPackage.GetById(packageId); diff --git a/src/umbraco.cms/businesslogic/Packager/PackageInstance/InstalledPackage.cs b/src/umbraco.cms/businesslogic/Packager/PackageInstance/InstalledPackage.cs index a8f90db5a0..8d3dc8abd4 100644 --- a/src/umbraco.cms/businesslogic/Packager/PackageInstance/InstalledPackage.cs +++ b/src/umbraco.cms/businesslogic/Packager/PackageInstance/InstalledPackage.cs @@ -35,7 +35,7 @@ namespace umbraco.cms.businesslogic.packager { { #if DEBUG _saveHitCount++; - LogHelper.Info("The InstalledPackage class save method has been hit " + _saveHitCount + " times."); + Current.Logger.Info("The InstalledPackage class save method has been hit " + _saveHitCount + " times."); #endif this.FireBeforeSave(EventArgs.Empty); data.Save(this.Data, IOHelper.MapPath(Settings.InstalledPackagesSettings)); @@ -84,7 +84,7 @@ namespace umbraco.cms.businesslogic.packager { } catch (Exception ex) { - LogHelper.Error("An error occured in isPackagedInstalled", ex); + Current.Logger.Error("An error occured in isPackagedInstalled", ex); return false; } } diff --git a/src/umbraco.cms/businesslogic/Packager/PackageInstance/PackageActions.cs b/src/umbraco.cms/businesslogic/Packager/PackageInstance/PackageActions.cs index b3f2af59f1..bfc902923d 100644 --- a/src/umbraco.cms/businesslogic/Packager/PackageInstance/PackageActions.cs +++ b/src/umbraco.cms/businesslogic/Packager/PackageInstance/PackageActions.cs @@ -36,7 +36,7 @@ namespace umbraco.cms.businesslogic.packager } catch (Exception ipaExp) { - LogHelper.Error(string.Format("Error loading package action '{0}' for package {1}", ipa.Alias(), packageName), ipaExp); + Current.Logger.Error(string.Format("Error loading package action '{0}' for package {1}", ipa.Alias(), packageName), ipaExp); } } } @@ -62,7 +62,7 @@ namespace umbraco.cms.businesslogic.packager } catch (Exception ipaExp) { - LogHelper.Error(string.Format("Error undoing package action '{0}' for package {1}", ipa.Alias(), packageName), ipaExp); + Current.Logger.Error(string.Format("Error undoing package action '{0}' for package {1}", ipa.Alias(), packageName), ipaExp); } } } diff --git a/src/umbraco.cms/businesslogic/Packager/Repositories/Repository.cs b/src/umbraco.cms/businesslogic/Packager/Repositories/Repository.cs index 8625446971..d5accf0fe4 100644 --- a/src/umbraco.cms/businesslogic/Packager/Repositories/Repository.cs +++ b/src/umbraco.cms/businesslogic/Packager/Repositories/Repository.cs @@ -61,7 +61,7 @@ namespace umbraco.cms.businesslogic.packager.repositories } catch (Exception ex) { - LogHelper.Error("An error occurred in SubmitPackage", ex); + Current.Logger.Error("An error occurred in SubmitPackage", ex); return SubmitStatus.Error; } diff --git a/src/umbraco.cms/businesslogic/Packager/data.cs b/src/umbraco.cms/businesslogic/Packager/data.cs index 2fef992bed..96e1df603c 100644 --- a/src/umbraco.cms/businesslogic/Packager/data.cs +++ b/src/umbraco.cms/businesslogic/Packager/data.cs @@ -6,6 +6,7 @@ using System.ComponentModel; using System.IO; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.DependencyInjection; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Xml; @@ -189,7 +190,7 @@ namespace umbraco.cms.businesslogic.packager } catch (Exception ex) { - LogHelper.Error("An error occurred in GetAllPackages", ex); + Current.Logger.Error("An error occurred in GetAllPackages", ex); } } diff --git a/src/umbraco.cms/businesslogic/language/Language.cs b/src/umbraco.cms/businesslogic/language/Language.cs index 840f88fcea..b0010b0469 100644 --- a/src/umbraco.cms/businesslogic/language/Language.cs +++ b/src/umbraco.cms/businesslogic/language/Language.cs @@ -144,7 +144,7 @@ namespace umbraco.cms.businesslogic.language } catch (Exception ex) { - LogHelper.Error("Could not find the culture " + cultureCode, ex); + Current.Logger.Error("Could not find the culture " + cultureCode, ex); return null; } } @@ -250,7 +250,7 @@ namespace umbraco.cms.businesslogic.language else { var e = new DataException("Cannot remove language " + LanguageEntity.CultureInfo.DisplayName + " because it's attached to a domain on a node"); - LogHelper.Error("Cannot remove language " + LanguageEntity.CultureInfo.DisplayName + " because it's attached to a domain on a node", e); + Current.Logger.Error("Cannot remove language " + LanguageEntity.CultureInfo.DisplayName + " because it's attached to a domain on a node", e); throw e; } } diff --git a/src/umbraco.cms/businesslogic/macro/Macro.cs b/src/umbraco.cms/businesslogic/macro/Macro.cs index 274fd48473..0a3f49887a 100644 --- a/src/umbraco.cms/businesslogic/macro/Macro.cs +++ b/src/umbraco.cms/businesslogic/macro/Macro.cs @@ -262,7 +262,7 @@ namespace umbraco.cms.businesslogic.macro } catch (Exception macroExp) { - LogHelper.Error("Error creating macro property", macroExp); + Current.Logger.Error("Error creating macro property", macroExp); } // macro properties @@ -291,7 +291,7 @@ namespace umbraco.cms.businesslogic.macro } catch (Exception macroPropertyExp) { - LogHelper.Error("Error creating macro property", macroPropertyExp); + Current.Logger.Error("Error creating macro property", macroPropertyExp); } } @@ -299,7 +299,7 @@ namespace umbraco.cms.businesslogic.macro } catch (Exception ex) { - LogHelper.Error("An error occurred importing a macro", ex); + Current.Logger.Error("An error occurred importing a macro", ex); return null; } diff --git a/src/umbraco.cms/businesslogic/member/Member.cs b/src/umbraco.cms/businesslogic/member/Member.cs index 47cefbcdf2..0be1ed690e 100644 --- a/src/umbraco.cms/businesslogic/member/Member.cs +++ b/src/umbraco.cms/businesslogic/member/Member.cs @@ -319,13 +319,13 @@ namespace umbraco.cms.businesslogic.member } else { - LogHelper.Debug("Incorrect login/password attempt or member is locked out or not approved (" + loginName + ")", true); + Current.Logger.Debug("Incorrect login/password attempt or member is locked out or not approved (" + loginName + ")"); return null; } } else { - LogHelper.Debug("No member with loginname: " + loginName + " Exists", true); + Current.Logger.Debug("No member with loginname: " + loginName + " Exists"); return null; } } @@ -899,7 +899,7 @@ namespace umbraco.cms.businesslogic.member } catch (Exception ex) { - LogHelper.Error("An error occurred in GetCurrentMember", ex); + Current.Logger.Error("An error occurred in GetCurrentMember", ex); } return null; } diff --git a/src/umbraco.cms/businesslogic/template/Template.cs b/src/umbraco.cms/businesslogic/template/Template.cs index 82aef5fbbb..a6a9095c70 100644 --- a/src/umbraco.cms/businesslogic/template/Template.cs +++ b/src/umbraco.cms/businesslogic/template/Template.cs @@ -308,7 +308,7 @@ namespace umbraco.cms.businesslogic.template if (this.HasChildren) { var ex = new InvalidOperationException("Can't delete a master template. Remove any bindings from child templates first."); - LogHelper.Error