Merge pull request #8892 from umbraco/netcore/feature/migrate-logging

Netcore: Migrate to use MS ILogger<T>
This commit is contained in:
Bjarke Berg
2020-10-07 06:44:55 +02:00
committed by GitHub
489 changed files with 3184 additions and 3593 deletions

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Logging;
namespace Umbraco.Core.Composing
@@ -12,22 +13,24 @@ namespace Umbraco.Core.Composing
{
private const int LogThresholdMilliseconds = 100;
private readonly IProfilingLogger _logger;
private readonly IProfilingLogger _profilingLogger;
private readonly ILogger<ComponentCollection> _logger;
public ComponentCollection(IEnumerable<IComponent> items, IProfilingLogger logger)
public ComponentCollection(IEnumerable<IComponent> items, IProfilingLogger profilingLogger, ILogger<ComponentCollection> logger)
: base(items)
{
_profilingLogger = profilingLogger;
_logger = logger;
}
public void Initialize()
{
using (_logger.DebugDuration<ComponentCollection>($"Initializing. (log components when >{LogThresholdMilliseconds}ms)", "Initialized."))
using (_profilingLogger.DebugDuration<ComponentCollection>($"Initializing. (log components when >{LogThresholdMilliseconds}ms)", "Initialized."))
{
foreach (var component in this)
{
var componentType = component.GetType();
using (_logger.DebugDuration<ComponentCollection>($"Initializing {componentType.FullName}.", $"Initialized {componentType.FullName}.", thresholdMilliseconds: LogThresholdMilliseconds))
using (_profilingLogger.DebugDuration<ComponentCollection>($"Initializing {componentType.FullName}.", $"Initialized {componentType.FullName}.", thresholdMilliseconds: LogThresholdMilliseconds))
{
component.Initialize();
}
@@ -37,12 +40,12 @@ namespace Umbraco.Core.Composing
public void Terminate()
{
using (_logger.DebugDuration<ComponentCollection>($"Terminating. (log components when >{LogThresholdMilliseconds}ms)", "Terminated."))
using (_profilingLogger.DebugDuration<ComponentCollection>($"Terminating. (log components when >{LogThresholdMilliseconds}ms)", "Terminated."))
{
foreach (var component in this.Reverse()) // terminate components in reverse order
{
var componentType = component.GetType();
using (_logger.DebugDuration<ComponentCollection>($"Terminating {componentType.FullName}.", $"Terminated {componentType.FullName}.", thresholdMilliseconds: LogThresholdMilliseconds))
using (_profilingLogger.DebugDuration<ComponentCollection>($"Terminating {componentType.FullName}.", $"Terminated {componentType.FullName}.", thresholdMilliseconds: LogThresholdMilliseconds))
{
try
{
@@ -51,7 +54,7 @@ namespace Umbraco.Core.Composing
}
catch (Exception ex)
{
_logger.Error<ComponentCollection>(ex, "Error while terminating component {ComponentType}.", componentType.FullName);
_logger.LogError(ex, "Error while terminating component {ComponentType}.", componentType.FullName);
}
}
}

View File

@@ -5,6 +5,7 @@ using System.Reflection;
using System.Text;
using Umbraco.Core.Collections;
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging;
namespace Umbraco.Core.Composing
{
@@ -16,7 +17,8 @@ namespace Umbraco.Core.Composing
public class Composers
{
private readonly Composition _composition;
private readonly IProfilingLogger _logger;
private readonly ILogger<Composers> _logger;
private readonly IProfilingLogger _profileLogger;
private readonly IEnumerable<Type> _composerTypes;
private readonly IEnumerable<Attribute> _enableDisableAttributes;
@@ -28,7 +30,8 @@ namespace Umbraco.Core.Composing
/// <param name="composition">The composition.</param>
/// <param name="composerTypes">The <see cref="IComposer" /> types.</param>
/// <param name="enableDisableAttributes">The <see cref="EnableComposerAttribute" /> and/or <see cref="DisableComposerAttribute" /> attributes.</param>
/// <param name="logger">The profiling logger.</param>
/// <param name="logger">The logger.</param>
/// <param name="profileLogger">The profiling logger.</param>
/// <exception cref="ArgumentNullException">composition
/// or
/// composerTypes
@@ -36,13 +39,13 @@ namespace Umbraco.Core.Composing
/// enableDisableAttributes
/// or
/// logger</exception>
public Composers(Composition composition, IEnumerable<Type> composerTypes, IEnumerable<Attribute> enableDisableAttributes, IProfilingLogger logger)
public Composers(Composition composition, IEnumerable<Type> composerTypes, IEnumerable<Attribute> enableDisableAttributes, ILogger<Composers> logger, IProfilingLogger profileLogger)
{
_composition = composition ?? throw new ArgumentNullException(nameof(composition));
_composerTypes = composerTypes ?? throw new ArgumentNullException(nameof(composerTypes));
_enableDisableAttributes = enableDisableAttributes ?? throw new ArgumentNullException(nameof(enableDisableAttributes));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_profileLogger = profileLogger;
}
private class EnableInfo
@@ -61,19 +64,19 @@ namespace Umbraco.Core.Composing
IEnumerable<Type> orderedComposerTypes;
using (_logger.DebugDuration<Composers>("Preparing composer types.", "Prepared composer types."))
using (_profileLogger.DebugDuration<Composers>("Preparing composer types.", "Prepared composer types."))
{
orderedComposerTypes = PrepareComposerTypes();
}
var composers = InstantiateComposers(orderedComposerTypes);
using (_logger.DebugDuration<Composers>($"Composing composers. (log when >{LogThresholdMilliseconds}ms)", "Composed composers."))
using (_profileLogger.DebugDuration<Composers>($"Composing composers. (log when >{LogThresholdMilliseconds}ms)", "Composed composers."))
{
foreach (var composer in composers)
{
var componentType = composer.GetType();
using (_logger.DebugDuration<Composers>($"Composing {componentType.FullName}.", $"Composed {componentType.FullName}.", thresholdMilliseconds: LogThresholdMilliseconds))
using (_profileLogger.DebugDuration<Composers>($"Composing {componentType.FullName}.", $"Composed {componentType.FullName}.", thresholdMilliseconds: LogThresholdMilliseconds))
{
composer.Compose(_composition);
}
@@ -92,7 +95,7 @@ namespace Umbraco.Core.Composing
// bit verbose but should help for troubleshooting
//var text = "Ordered Composers: " + Environment.NewLine + string.Join(Environment.NewLine, sortedComposerTypes) + Environment.NewLine;
_logger.Debug<Composers>("Ordered Composers: {SortedComposerTypes}", sortedComposerTypes);
_logger.LogDebug("Ordered Composers: {SortedComposerTypes}", sortedComposerTypes);
return sortedComposerTypes;
}
@@ -183,8 +186,8 @@ namespace Umbraco.Core.Composing
catch (Exception e)
{
// in case of an error, force-dump everything to log
_logger.Info<Composers>("Composer Report:\r\n{ComposerReport}", GetComposersReport(requirements));
_logger.Error<Composers>(e, "Failed to sort composers.");
_logger.LogInformation("Composer Report:\r\n{ComposerReport}", GetComposersReport(requirements));
_logger.LogError(e, "Failed to sort composers.");
throw;
}
@@ -370,7 +373,7 @@ namespace Umbraco.Core.Composing
return (IComposer) ctor.Invoke(Array.Empty<object>());
}
using (_logger.DebugDuration<Composers>("Instantiating composers.", "Instantiated composers."))
using (_profileLogger.DebugDuration<Composers>("Instantiating composers.", "Instantiated composers."))
{
return types.Select(InstantiateComposer).ToArray();
}

View File

@@ -1,18 +1,20 @@
using System;
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Umbraco.Composing
{
public static class Current
{
private static ILogger _logger = new NullLogger();
private static ILogger<object> _logger = new NullLogger<object>();
private static IIOHelper _ioHelper;
private static IHostingEnvironment _hostingEnvironment;
private static IBackOfficeInfo _backOfficeInfo;
@@ -20,8 +22,7 @@ namespace Umbraco.Composing
private static SecuritySettings _securitySettings;
private static GlobalSettings _globalSettings;
public static ILogger Logger => EnsureInitialized(_logger);
public static ILogger<object> Logger => EnsureInitialized(_logger);
public static IIOHelper IOHelper => EnsureInitialized(_ioHelper);
public static IHostingEnvironment HostingEnvironment => EnsureInitialized(_hostingEnvironment);
public static IBackOfficeInfo BackOfficeInfo => EnsureInitialized(_backOfficeInfo);
@@ -41,7 +42,7 @@ namespace Umbraco.Composing
}
public static void Initialize(
ILogger logger,
ILogger<object> logger,
SecuritySettings securitySettings,
GlobalSettings globalSettings,
IIOHelper ioHelper,

View File

@@ -6,7 +6,7 @@ using System.Reflection;
using System.Security;
using System.Text;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging;
namespace Umbraco.Core.Composing
{
@@ -14,7 +14,7 @@ namespace Umbraco.Core.Composing
/// <inheritdoc cref="ITypeFinder"/>
public class TypeFinder : ITypeFinder
{
private readonly ILogger _logger;
private readonly ILogger<TypeFinder> _logger;
private readonly IAssemblyProvider _assemblyProvider;
private readonly IRuntimeHash _runtimeHash;
private volatile HashSet<Assembly> _localFilteredAssemblyCache;
@@ -26,7 +26,7 @@ namespace Umbraco.Core.Composing
// used for benchmark tests
internal bool QueryWithReferencingAssemblies = true;
public TypeFinder(ILogger logger, IAssemblyProvider assemblyProvider, IRuntimeHash runtimeHash, ITypeFinderConfig typeFinderConfig = null)
public TypeFinder(ILogger<TypeFinder> logger, IAssemblyProvider assemblyProvider, IRuntimeHash runtimeHash, ITypeFinderConfig typeFinderConfig = null)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_assemblyProvider = assemblyProvider;
@@ -297,7 +297,7 @@ namespace Umbraco.Core.Composing
}
catch (TypeLoadException ex)
{
_logger.Error(typeof(TypeFinder), ex, "Could not query types on {Assembly} assembly, this is most likely due to this assembly not being compatible with the current Umbraco version", assembly);
_logger.LogError(ex, "Could not query types on {Assembly} assembly, this is most likely due to this assembly not being compatible with the current Umbraco version", assembly);
continue;
}
@@ -372,7 +372,7 @@ namespace Umbraco.Core.Composing
}
catch (TypeLoadException ex)
{
_logger.Error(typeof(TypeFinder), ex, "Could not query types on {Assembly} assembly, this is most likely due to this assembly not being compatible with the current Umbraco version", assembly);
_logger.LogError(ex, "Could not query types on {Assembly} assembly, this is most likely due to this assembly not being compatible with the current Umbraco version", assembly);
continue;
}
@@ -442,7 +442,7 @@ namespace Umbraco.Core.Composing
if (_notifiedLoadExceptionAssemblies.Contains(a.FullName) == false)
{
_notifiedLoadExceptionAssemblies.Add(a.FullName);
_logger.Warn(typeof (TypeFinder), ex, "Could not load all types from {TypeName}.", a.GetName().Name);
_logger.LogWarning(ex, "Could not load all types from {TypeName}.", a.GetName().Name);
}
}
return rex.Types.WhereNotNull().ToArray();

View File

@@ -11,6 +11,7 @@ using Umbraco.Core.Collections;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using File = System.IO.File;
using Microsoft.Extensions.Logging;
namespace Umbraco.Core.Composing
{
@@ -28,7 +29,8 @@ namespace Umbraco.Core.Composing
private const string CacheKey = "umbraco-types.list";
private readonly IAppPolicyCache _runtimeCache;
private readonly IProfilingLogger _logger;
private readonly ILogger<TypeLoader> _logger;
private readonly IProfilingLogger _profilingLogger;
private readonly Dictionary<CompositeTypeTypeKey, TypeList> _types = new Dictionary<CompositeTypeTypeKey, TypeList>();
private readonly object _locko = new object();
@@ -51,8 +53,8 @@ namespace Umbraco.Core.Composing
/// <param name="localTempPath">Files storage location.</param>
/// <param name="logger">A profiling logger.</param>
/// <param name="assembliesToScan"></param>
public TypeLoader(ITypeFinder typeFinder, IAppPolicyCache runtimeCache, DirectoryInfo localTempPath, IProfilingLogger logger, IEnumerable<Assembly> assembliesToScan = null)
: this(typeFinder, runtimeCache, localTempPath, logger, true, assembliesToScan)
public TypeLoader(ITypeFinder typeFinder, IAppPolicyCache runtimeCache, DirectoryInfo localTempPath, ILogger<TypeLoader> logger, IProfilingLogger profilingLogger, IEnumerable<Assembly> assembliesToScan = null)
: this(typeFinder, runtimeCache, localTempPath, logger, profilingLogger, true, assembliesToScan)
{ }
/// <summary>
@@ -64,12 +66,13 @@ namespace Umbraco.Core.Composing
/// <param name="logger">A profiling logger.</param>
/// <param name="detectChanges">Whether to detect changes using hashes.</param>
/// <param name="assembliesToScan"></param>
public TypeLoader(ITypeFinder typeFinder, IAppPolicyCache runtimeCache, DirectoryInfo localTempPath, IProfilingLogger logger, bool detectChanges, IEnumerable<Assembly> assembliesToScan = null)
public TypeLoader(ITypeFinder typeFinder, IAppPolicyCache runtimeCache, DirectoryInfo localTempPath, ILogger<TypeLoader> logger, IProfilingLogger profilingLogger, bool detectChanges, IEnumerable<Assembly> assembliesToScan = null)
{
TypeFinder = typeFinder ?? throw new ArgumentNullException(nameof(typeFinder));
_runtimeCache = runtimeCache ?? throw new ArgumentNullException(nameof(runtimeCache));
_localTempPath = localTempPath;
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_profilingLogger = profilingLogger ?? throw new ArgumentNullException(nameof(profilingLogger));
_assemblies = assembliesToScan;
if (detectChanges)
@@ -309,7 +312,7 @@ namespace Umbraco.Core.Composing
// internal for tests
public void WriteCache()
{
_logger.Debug<TypeLoader>("Writing cache file.");
_logger.LogDebug("Writing cache file.");
var typesListFilePath = GetTypesListFilePath();
using (var stream = GetFileStream(typesListFilePath, FileMode.Create, FileAccess.Write, FileShare.None, ListFileOpenWriteTimeout))
using (var writer = new StreamWriter(stream))
@@ -381,7 +384,7 @@ namespace Umbraco.Core.Composing
if (--attempts == 0)
throw;
_logger.Debug<TypeLoader>("Attempted to get filestream for file {Path} failed, {NumberOfAttempts} attempts left, pausing for {PauseMilliseconds} milliseconds", path, attempts, pauseMilliseconds);
_logger.LogDebug("Attempted to get filestream for file {Path} failed, {NumberOfAttempts} attempts left, pausing for {PauseMilliseconds} milliseconds", path, attempts, pauseMilliseconds);
Thread.Sleep(pauseMilliseconds);
}
}
@@ -402,7 +405,7 @@ namespace Umbraco.Core.Composing
if (--attempts == 0)
throw;
_logger.Debug<TypeLoader>("Attempted to delete file {Path} failed, {NumberOfAttempts} attempts left, pausing for {PauseMilliseconds} milliseconds", path, attempts, pauseMilliseconds);
_logger.LogDebug("Attempted to delete file {Path} failed, {NumberOfAttempts} attempts left, pausing for {PauseMilliseconds} milliseconds", path, attempts, pauseMilliseconds);
Thread.Sleep(pauseMilliseconds);
}
}
@@ -475,7 +478,7 @@ namespace Umbraco.Core.Composing
if (!typeof(IDiscoverable).IsAssignableFrom(typeof(T)))
{
// warn
_logger.Debug<TypeLoader>("Running a full, " + (cache ? "" : "non-") + "cached, scan for non-discoverable type {TypeName} (slow).", typeof(T).FullName);
_logger.LogDebug("Running a full, " + (cache ? "" : "non-") + "cached, scan for non-discoverable type {TypeName} (slow).", typeof(T).FullName);
return GetTypesInternal(
typeof(T), null,
@@ -493,7 +496,7 @@ namespace Umbraco.Core.Composing
// warn
if (!cache)
_logger.Debug<TypeLoader>("Running a non-cached, filter for discoverable type {TypeName} (slowish).", typeof(T).FullName);
_logger.LogDebug("Running a non-cached, filter for discoverable type {TypeName} (slowish).", typeof(T).FullName);
// filter the cached discovered types (and maybe cache the result)
return GetTypesInternal(
@@ -525,7 +528,7 @@ namespace Umbraco.Core.Composing
// if not IDiscoverable, directly get types
if (!typeof(IDiscoverable).IsAssignableFrom(typeof(T)))
{
_logger.Debug<TypeLoader>("Running a full, " + (cache ? "" : "non-") + "cached, scan for non-discoverable type {TypeName} / attribute {AttributeName} (slow).", typeof(T).FullName, typeof(TAttribute).FullName);
_logger.LogDebug("Running a full, " + (cache ? "" : "non-") + "cached, scan for non-discoverable type {TypeName} / attribute {AttributeName} (slow).", typeof(T).FullName, typeof(TAttribute).FullName);
return GetTypesInternal(
typeof(T), typeof(TAttribute),
@@ -543,7 +546,7 @@ namespace Umbraco.Core.Composing
// warn
if (!cache)
_logger.Debug<TypeLoader>("Running a non-cached, filter for discoverable type {TypeName} / attribute {AttributeName} (slowish).", typeof(T).FullName, typeof(TAttribute).FullName);
_logger.LogDebug("Running a non-cached, filter for discoverable type {TypeName} / attribute {AttributeName} (slowish).", typeof(T).FullName, typeof(TAttribute).FullName);
// filter the cached discovered types (and maybe cache the result)
return GetTypesInternal(
@@ -573,7 +576,7 @@ namespace Umbraco.Core.Composing
cache &= specificAssemblies == null;
if (!cache)
_logger.Debug<TypeLoader>("Running a full, non-cached, scan for types / attribute {AttributeName} (slow).", typeof(TAttribute).FullName);
_logger.LogDebug("Running a full, non-cached, scan for types / attribute {AttributeName} (slow).", typeof(TAttribute).FullName);
return GetTypesInternal(
typeof (object), typeof (TAttribute),
@@ -596,7 +599,7 @@ namespace Umbraco.Core.Composing
var name = GetName(baseType, attributeType);
lock (_locko)
using (_logger.DebugDuration<TypeLoader>(
using (_profilingLogger.DebugDuration<TypeLoader>(
"Getting " + name,
"Got " + name)) // cannot contain typesFound.Count as it's evaluated before the find
{
@@ -629,7 +632,7 @@ namespace Umbraco.Core.Composing
if (typeList != null)
{
// need to put some logging here to try to figure out why this is happening: http://issues.umbraco.org/issue/U4-3505
_logger.Debug<TypeLoader>("Getting {TypeName}: found a cached type list.", GetName(baseType, attributeType));
_logger.LogDebug("Getting {TypeName}: found a cached type list.", GetName(baseType, attributeType));
return typeList.Types;
}
@@ -645,7 +648,7 @@ namespace Umbraco.Core.Composing
// report (only once) and scan and update the cache file
if (_reportedChange == false)
{
_logger.Debug<TypeLoader>("Assemblies changes detected, need to rescan everything.");
_logger.LogDebug("Assemblies changes detected, need to rescan everything.");
_reportedChange = true;
}
}
@@ -660,7 +663,7 @@ namespace Umbraco.Core.Composing
// so in this instance there will never be a result.
if (cacheResult.Exception is CachedTypeNotFoundInFileException || cacheResult.Success == false)
{
_logger.Debug<TypeLoader>("Getting {TypeName}: failed to load from cache file, must scan assemblies.", GetName(baseType, attributeType));
_logger.LogDebug("Getting {TypeName}: failed to load from cache file, must scan assemblies.", GetName(baseType, attributeType));
scan = true;
}
else
@@ -674,7 +677,7 @@ namespace Umbraco.Core.Composing
else
{
// in case of any exception, we have to exit, and revert to scanning
_logger.Warn<TypeLoader>("Getting {TypeName}: failed to load cache file type {CacheType}, reverting to scanning assemblies.", GetName(baseType, attributeType), type);
_logger.LogWarning("Getting {TypeName}: failed to load cache file type {CacheType}, reverting to scanning assemblies.", GetName(baseType, attributeType), type);
scan = true;
break;
}
@@ -682,7 +685,7 @@ namespace Umbraco.Core.Composing
if (scan == false)
{
_logger.Debug<TypeLoader>("Getting {TypeName}: loaded types from cache file.", GetName(baseType, attributeType));
_logger.LogDebug("Getting {TypeName}: loaded types from cache file.", GetName(baseType, attributeType));
}
}
}
@@ -690,7 +693,7 @@ namespace Umbraco.Core.Composing
if (scan)
{
// either we had to scan, or we could not get the types from the cache file - scan now
_logger.Debug<TypeLoader>("Getting {TypeName}: " + action + ".", GetName(baseType, attributeType));
_logger.LogDebug("Getting {TypeName}: " + action + ".", GetName(baseType, attributeType));
foreach (var t in finder())
typeList.Add(t);
@@ -708,11 +711,11 @@ namespace Umbraco.Core.Composing
UpdateCache();
}
_logger.Debug<TypeLoader>("Got {TypeName}, caching ({CacheType}).", GetName(baseType, attributeType), added.ToString().ToLowerInvariant());
_logger.LogDebug("Got {TypeName}, caching ({CacheType}).", GetName(baseType, attributeType), added.ToString().ToLowerInvariant());
}
else
{
_logger.Debug<TypeLoader>("Got {TypeName}.", GetName(baseType, attributeType));
_logger.LogDebug("Got {TypeName}.", GetName(baseType, attributeType));
}
return typeList.Types;

View File

@@ -29,7 +29,9 @@ namespace Umbraco.Core.Configuration
ConnectionString = connectionString
};
if (builder.TryGetValue("Data Source", out var ds) && ds is string dataSource)
if (
(builder.TryGetValue("Data Source", out var ds)
|| builder.TryGetValue("DataSource", out ds)) && ds is string dataSource)
{
if (dataSource.EndsWith(".sdf"))
{
@@ -37,6 +39,7 @@ namespace Umbraco.Core.Configuration
}
}
if (builder.TryGetValue("Server", out var s) && s is string server && !string.IsNullOrEmpty(server))
{
if (builder.TryGetValue("Database", out var db) && db is string database && !string.IsNullOrEmpty(database))

View File

@@ -1,6 +1,6 @@
using Umbraco.Core.Cache;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Cache;
using Umbraco.Core.Hosting;
using Umbraco.Core.Logging;
using Umbraco.Core.Manifest;
using Umbraco.Core.Serialization;
@@ -8,9 +8,9 @@ namespace Umbraco.Core.Configuration.Grid
{
public class GridConfig : IGridConfig
{
public GridConfig(AppCaches appCaches, IManifestParser manifestParser, IJsonSerializer jsonSerializer, IHostingEnvironment hostingEnvironment, ILogger logger)
public GridConfig(AppCaches appCaches, IManifestParser manifestParser, IJsonSerializer jsonSerializer, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory)
{
EditorsConfig = new GridEditorsConfig(appCaches, hostingEnvironment, manifestParser, jsonSerializer, logger);
EditorsConfig = new GridEditorsConfig(appCaches, hostingEnvironment, manifestParser, jsonSerializer, loggerFactory.CreateLogger<GridEditorsConfig>());
}
public IGridEditorsConfig EditorsConfig { get; }

View File

@@ -1,9 +1,9 @@
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Cache;
using Umbraco.Core.Hosting;
using Umbraco.Core.Logging;
using Umbraco.Core.Manifest;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Serialization;
@@ -17,9 +17,9 @@ namespace Umbraco.Core.Configuration.Grid
private readonly IManifestParser _manifestParser;
private readonly IJsonSerializer _jsonSerializer;
private readonly ILogger _logger;
private readonly ILogger<GridEditorsConfig> _logger;
public GridEditorsConfig(AppCaches appCaches, IHostingEnvironment hostingEnvironment, IManifestParser manifestParser,IJsonSerializer jsonSerializer, ILogger logger)
public GridEditorsConfig(AppCaches appCaches, IHostingEnvironment hostingEnvironment, IManifestParser manifestParser,IJsonSerializer jsonSerializer, ILogger<GridEditorsConfig> logger)
{
_appCaches = appCaches;
_hostingEnvironment = hostingEnvironment;
@@ -47,7 +47,7 @@ namespace Umbraco.Core.Configuration.Grid
}
catch (Exception ex)
{
_logger.Error<GridEditorsConfig>(ex, "Could not parse the contents of grid.editors.config.js into a JSON array '{Json}", sourceString);
_logger.LogError(ex, "Could not parse the contents of grid.editors.config.js into a JSON array '{Json}", sourceString);
}
}

View File

@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
@@ -15,7 +16,7 @@ namespace Umbraco.Web.HealthCheck.Checks.Config
private readonly ConfigurationService _configurationService;
protected ILocalizedTextService TextService { get; }
protected ILogger Logger { get; }
protected ILoggerFactory LoggerFactory { get; }
/// <summary>
/// Gets the config file path.
@@ -55,12 +56,12 @@ namespace Umbraco.Web.HealthCheck.Checks.Config
get { return false; }
}
protected AbstractConfigCheck(ILocalizedTextService textService, IHostingEnvironment hostingEnvironment, ILogger logger)
protected AbstractConfigCheck(ILocalizedTextService textService, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory)
{
_hostingEnvironment = hostingEnvironment;
TextService = textService;
Logger = logger;
_configurationService = new ConfigurationService(AbsoluteFilePath, XPath, textService, logger);
LoggerFactory = loggerFactory;
_configurationService = new ConfigurationService(AbsoluteFilePath, XPath, textService, loggerFactory.CreateLogger<ConfigurationService>());
}
/// <summary>

View File

@@ -1,7 +1,7 @@
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Services;
namespace Umbraco.Web.HealthCheck.Checks.Config
@@ -11,8 +11,8 @@ namespace Umbraco.Web.HealthCheck.Checks.Config
Group = "Live Environment")]
public class CompilationDebugCheck : AbstractConfigCheck
{
public CompilationDebugCheck(ILocalizedTextService textService, IHostingEnvironment hostingEnvironment, ILogger logger)
: base(textService, hostingEnvironment, logger)
public CompilationDebugCheck(ILocalizedTextService textService, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory)
: base(textService, hostingEnvironment, loggerFactory)
{ }
public override string FilePath => "~/Web.config";

View File

@@ -1,7 +1,7 @@
using System;
using System.IO;
using System.Xml;
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Services;
namespace Umbraco.Web.HealthCheck.Checks.Config
@@ -13,14 +13,14 @@ namespace Umbraco.Web.HealthCheck.Checks.Config
private readonly string _configFilePath;
private readonly string _xPath;
private readonly ILocalizedTextService _textService;
private readonly ILogger _logger;
private readonly ILogger<ConfigurationService> _logger;
/// <param name="configFilePath">The absolute file location of the configuration file</param>
/// <param name="xPath">The XPath to select the value</param>
/// <param name="textService"></param>
/// <param name="logger"></param>
/// <returns></returns>
public ConfigurationService(string configFilePath, string xPath, ILocalizedTextService textService, ILogger logger)
public ConfigurationService(string configFilePath, string xPath, ILocalizedTextService textService, ILogger<ConfigurationService> logger)
{
_configFilePath = configFilePath;
_xPath = xPath;
@@ -61,7 +61,7 @@ namespace Umbraco.Web.HealthCheck.Checks.Config
}
catch (Exception ex)
{
_logger.Error<ConfigurationService>(ex, "Error trying to get configuration value");
_logger.LogError(ex, "Error trying to get configuration value");
return new ConfigurationServiceResult
{
Success = false,
@@ -107,7 +107,7 @@ namespace Umbraco.Web.HealthCheck.Checks.Config
}
catch (Exception ex)
{
_logger.Error<ConfigurationService>(ex, "Error trying to update configuration");
_logger.LogError(ex, "Error trying to update configuration");
return new ConfigurationServiceResult
{
Success = false,

View File

@@ -1,8 +1,8 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Services;
namespace Umbraco.Web.HealthCheck.Checks.Config
@@ -12,8 +12,8 @@ namespace Umbraco.Web.HealthCheck.Checks.Config
Group = "Live Environment")]
public class CustomErrorsCheck : AbstractConfigCheck
{
public CustomErrorsCheck(ILocalizedTextService textService, IHostingEnvironment hostingEnvironment, ILogger logger)
: base(textService, hostingEnvironment, logger)
public CustomErrorsCheck(ILocalizedTextService textService, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory)
: base(textService, hostingEnvironment, loggerFactory)
{ }
public override string FilePath => "~/Web.config";

View File

@@ -1,8 +1,8 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Services;
namespace Umbraco.Web.HealthCheck.Checks.Config
@@ -12,8 +12,8 @@ namespace Umbraco.Web.HealthCheck.Checks.Config
Group = "Configuration")]
public class MacroErrorsCheck : AbstractConfigCheck
{
public MacroErrorsCheck(ILocalizedTextService textService, IHostingEnvironment hostingEnvironment, ILogger logger)
: base(textService, hostingEnvironment, logger)
public MacroErrorsCheck(ILocalizedTextService textService, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory)
: base(textService, hostingEnvironment, loggerFactory)
{ }
public override string FilePath => "~/Config/umbracoSettings.config";

View File

@@ -1,7 +1,7 @@
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Services;
namespace Umbraco.Web.HealthCheck.Checks.Config
@@ -13,8 +13,8 @@ namespace Umbraco.Web.HealthCheck.Checks.Config
{
private const string DefaultFromEmail = "your@email.here";
public NotificationEmailCheck(ILocalizedTextService textService, IHostingEnvironment hostingEnvironment, ILogger logger)
: base(textService, hostingEnvironment, logger)
public NotificationEmailCheck(ILocalizedTextService textService, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory)
: base(textService, hostingEnvironment, loggerFactory)
{ }
public override string FilePath => "~/Config/umbracoSettings.config";

View File

@@ -1,7 +1,7 @@
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Services;
namespace Umbraco.Web.HealthCheck.Checks.Config
@@ -12,8 +12,8 @@ namespace Umbraco.Web.HealthCheck.Checks.Config
public class TraceCheck : AbstractConfigCheck
{
public TraceCheck(ILocalizedTextService textService, IHostingEnvironment hostingEnvironment, ILogger logger)
: base(textService, hostingEnvironment, logger)
public TraceCheck(ILocalizedTextService textService, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory)
: base(textService, hostingEnvironment, loggerFactory)
{ }
public override string FilePath => "~/Web.config";

View File

@@ -1,9 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Services;
namespace Umbraco.Web.HealthCheck.Checks.Config
@@ -15,9 +15,9 @@ namespace Umbraco.Web.HealthCheck.Checks.Config
{
private readonly Version _iisVersion;
public TrySkipIisCustomErrorsCheck(ILocalizedTextService textService, ILogger logger,
public TrySkipIisCustomErrorsCheck(ILocalizedTextService textService, ILoggerFactory loggerFactory,
IHostingEnvironment hostingEnvironment)
: base(textService, hostingEnvironment, logger)
: base(textService, hostingEnvironment, loggerFactory)
{
_iisVersion = hostingEnvironment.IISVersion;
}

View File

@@ -4,17 +4,17 @@ using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
namespace Umbraco.Core.Configuration
{
public class XmlConfigManipulator : IConfigManipulator
{
private readonly IIOHelper _ioHelper;
private readonly ILogger _logger;
private readonly ILogger<XmlConfigManipulator> _logger;
public XmlConfigManipulator(IIOHelper ioHelper, ILogger logger)
public XmlConfigManipulator(IIOHelper ioHelper, ILogger<XmlConfigManipulator> logger)
{
_ioHelper = ioHelper;
_logger = logger;
@@ -101,9 +101,9 @@ namespace Umbraco.Core.Configuration
}
// save
_logger.Info<XmlConfigManipulator>("Saving connection string to {ConfigFile}.", fileSource);
_logger.LogInformation("Saving connection string to {ConfigFile}.", fileSource);
xml.Save(fileName, SaveOptions.DisableFormatting);
_logger.Info<XmlConfigManipulator>("Saved connection string to {ConfigFile}.", fileSource);
_logger.LogInformation("Saved connection string to {ConfigFile}.", fileSource);
}
public void SaveConfigValue(string itemPath, object value)

View File

@@ -1,19 +1,19 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Models.ContentEditing;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Membership;
namespace Umbraco.Web.ContentApps
{
public class ContentAppFactoryCollection : BuilderCollectionBase<IContentAppFactory>
{
private readonly ILogger _logger;
private readonly ILogger<ContentAppFactoryCollection> _logger;
private readonly IUmbracoContextAccessor _umbracoContextAccessor;
public ContentAppFactoryCollection(IEnumerable<IContentAppFactory> items, ILogger logger, IUmbracoContextAccessor umbracoContextAccessor)
public ContentAppFactoryCollection(IEnumerable<IContentAppFactory> items, ILogger<ContentAppFactoryCollection> logger, IUmbracoContextAccessor umbracoContextAccessor)
: base(items)
{
_logger = logger;
@@ -51,7 +51,7 @@ namespace Umbraco.Web.ContentApps
// dying is not user-friendly, so let's write to log instead, and wish people read logs...
//throw new InvalidOperationException($"Duplicate content app aliases found: {string.Join(",", dups)}");
_logger.Warn<ContentAppFactoryCollection>("Duplicate content app aliases found: {DuplicateAliases}", string.Join(",", dups));
_logger.LogWarning("Duplicate content app aliases found: {DuplicateAliases}", string.Join(",", dups));
}
return apps;

View File

@@ -1,9 +1,9 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Manifest;
using Umbraco.Core.Models.ContentEditing;
using Umbraco.Core.Models.Identity;
@@ -17,10 +17,10 @@ namespace Umbraco.Web.ContentApps
// need to inject dependencies in the collection, so override creation
public override ContentAppFactoryCollection CreateCollection(IFactory factory)
{
// get the logger just-in-time - see note below for manifest parser
var logger = factory.GetInstance<ILogger>();
// get the logger factory just-in-time - see note below for manifest parser
var loggerFactory = factory.GetInstance<ILoggerFactory>();
var umbracoContextAccessor = factory.GetInstance<IUmbracoContextAccessor>();
return new ContentAppFactoryCollection(CreateItems(factory), logger, umbracoContextAccessor);
return new ContentAppFactoryCollection(CreateItems(factory), loggerFactory.CreateLogger<ContentAppFactoryCollection>(), umbracoContextAccessor);
}
protected override IEnumerable<IContentAppFactory> CreateItems(IFactory factory)

View File

@@ -2,11 +2,11 @@
using System.Collections.Generic;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
using Umbraco.Core.Services;
using Umbraco.Core.Logging;
using Umbraco.Web.HealthCheck.Checks.Config;
using Umbraco.Core.Configuration.Models;
using Microsoft.Extensions.Options;
@@ -23,18 +23,22 @@ namespace Umbraco.Web.HealthCheck.Checks.Security
private readonly ILocalizedTextService _textService;
private readonly GlobalSettings _globalSettings;
private readonly IIOHelper _ioHelper;
private readonly ILogger _logger;
private readonly IRequestAccessor _requestAccessor;
private readonly ILogger<ConfigurationService> _logger;
private const string FixHttpsSettingAction = "fixHttpsSetting";
public HttpsCheck(ILocalizedTextService textService, IOptions<GlobalSettings> globalSettings, IIOHelper ioHelper, ILogger logger, IRequestAccessor requestAccessor)
public HttpsCheck(ILocalizedTextService textService,
IOptions<GlobalSettings> globalSettings,
IIOHelper ioHelper,
IRequestAccessor requestAccessor,
ILogger<ConfigurationService> logger)
{
_textService = textService;
_globalSettings = globalSettings.Value;
_ioHelper = ioHelper;
_logger = logger;
_requestAccessor = requestAccessor;
_logger = logger;
}
/// <summary>

View File

@@ -2,7 +2,7 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration;
using Umbraco.Core.Hosting;
@@ -14,7 +14,8 @@ namespace Umbraco.Core.IO
public class FileSystems : IFileSystems
{
private readonly IFactory _container;
private readonly ILogger _logger;
private readonly ILogger<FileSystems> _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly IIOHelper _ioHelper;
private readonly ConcurrentDictionary<Type, Lazy<IFileSystem>> _filesystems = new ConcurrentDictionary<Type, Lazy<IFileSystem>>();
@@ -38,10 +39,11 @@ namespace Umbraco.Core.IO
#region Constructor
// DI wants a public ctor
public FileSystems(IFactory container, ILogger logger, IIOHelper ioHelper, IOptions<GlobalSettings> globalSettings, IHostingEnvironment hostingEnvironment)
public FileSystems(IFactory container, ILogger<FileSystems> logger, ILoggerFactory loggerFactory, IIOHelper ioHelper, IOptions<GlobalSettings> globalSettings, IHostingEnvironment hostingEnvironment)
{
_container = container;
_logger = logger;
_loggerFactory = loggerFactory;
_ioHelper = ioHelper;
_globalSettings = globalSettings.Value;
_hostingEnvironment = hostingEnvironment;
@@ -128,17 +130,18 @@ namespace Umbraco.Core.IO
// but it does not really matter what we return - here, null
private object CreateWellKnownFileSystems()
{
var macroPartialFileSystem = new PhysicalFileSystem(_ioHelper, _hostingEnvironment, _logger, Constants.SystemDirectories.MacroPartials);
var partialViewsFileSystem = new PhysicalFileSystem(_ioHelper, _hostingEnvironment, _logger, Constants.SystemDirectories.PartialViews);
var stylesheetsFileSystem = new PhysicalFileSystem(_ioHelper, _hostingEnvironment, _logger, _globalSettings.UmbracoCssPath);
var scriptsFileSystem = new PhysicalFileSystem(_ioHelper, _hostingEnvironment, _logger, _globalSettings.UmbracoScriptsPath);
var mvcViewsFileSystem = new PhysicalFileSystem(_ioHelper, _hostingEnvironment, _logger, Constants.SystemDirectories.MvcViews);
var logger = _loggerFactory.CreateLogger<PhysicalFileSystem>();
var macroPartialFileSystem = new PhysicalFileSystem(_ioHelper, _hostingEnvironment, logger, Constants.SystemDirectories.MacroPartials);
var partialViewsFileSystem = new PhysicalFileSystem(_ioHelper, _hostingEnvironment, logger, Constants.SystemDirectories.PartialViews);
var stylesheetsFileSystem = new PhysicalFileSystem(_ioHelper, _hostingEnvironment, logger, _globalSettings.UmbracoCssPath);
var scriptsFileSystem = new PhysicalFileSystem(_ioHelper, _hostingEnvironment, logger, _globalSettings.UmbracoScriptsPath);
var mvcViewsFileSystem = new PhysicalFileSystem(_ioHelper, _hostingEnvironment, logger, Constants.SystemDirectories.MvcViews);
_macroPartialFileSystem = new ShadowWrapper(macroPartialFileSystem, _ioHelper, _hostingEnvironment, _logger,"macro-partials", IsScoped);
_partialViewsFileSystem = new ShadowWrapper(partialViewsFileSystem, _ioHelper, _hostingEnvironment, _logger,"partials", IsScoped);
_stylesheetsFileSystem = new ShadowWrapper(stylesheetsFileSystem, _ioHelper, _hostingEnvironment,_logger,"css", IsScoped);
_scriptsFileSystem = new ShadowWrapper(scriptsFileSystem, _ioHelper, _hostingEnvironment,_logger,"scripts", IsScoped);
_mvcViewsFileSystem = new ShadowWrapper(mvcViewsFileSystem, _ioHelper, _hostingEnvironment,_logger,"views", IsScoped);
_macroPartialFileSystem = new ShadowWrapper(macroPartialFileSystem, _ioHelper, _hostingEnvironment, _loggerFactory, "macro-partials", IsScoped);
_partialViewsFileSystem = new ShadowWrapper(partialViewsFileSystem, _ioHelper, _hostingEnvironment, _loggerFactory, "partials", IsScoped);
_stylesheetsFileSystem = new ShadowWrapper(stylesheetsFileSystem, _ioHelper, _hostingEnvironment, _loggerFactory, "css", IsScoped);
_scriptsFileSystem = new ShadowWrapper(scriptsFileSystem, _ioHelper, _hostingEnvironment, _loggerFactory, "scripts", IsScoped);
_mvcViewsFileSystem = new ShadowWrapper(mvcViewsFileSystem, _ioHelper, _hostingEnvironment, _loggerFactory, "views", IsScoped);
// TODO: do we need a lock here?
_shadowWrappers.Add(_macroPartialFileSystem);
@@ -235,7 +238,7 @@ namespace Umbraco.Core.IO
_shadowCurrentId = id;
_logger.Debug<ShadowFileSystems>("Shadow '{ShadowId}'", _shadowCurrentId);
_logger.LogDebug("Shadow '{ShadowId}'", _shadowCurrentId);
foreach (var wrapper in _shadowWrappers)
wrapper.Shadow(_shadowCurrentId);
@@ -252,7 +255,7 @@ namespace Umbraco.Core.IO
if (id != _shadowCurrentId)
throw new InvalidOperationException("Not the current shadow.");
_logger.Debug<ShadowFileSystems>("UnShadow '{ShadowId}' {Status}", id, completed ? "complete" : "abort");
_logger.LogDebug("UnShadow '{ShadowId}' {Status}", id, completed ? "complete" : "abort");
var exceptions = new List<Exception>();
foreach (var wrapper in _shadowWrappers)
@@ -279,7 +282,7 @@ namespace Umbraco.Core.IO
{
lock (_shadowLocker)
{
var wrapper = new ShadowWrapper(filesystem, _ioHelper, _hostingEnvironment, _logger, shadowPath, IsScoped);
var wrapper = new ShadowWrapper(filesystem, _ioHelper, _hostingEnvironment, _loggerFactory, shadowPath, IsScoped);
if (_shadowCurrentId != null)
wrapper.Shadow(_shadowCurrentId);
_shadowWrappers.Add(wrapper);

View File

@@ -3,7 +3,7 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Strings;
@@ -15,13 +15,13 @@ namespace Umbraco.Core.IO
public class MediaFileSystem : FileSystemWrapper, IMediaFileSystem
{
private readonly IMediaPathScheme _mediaPathScheme;
private readonly ILogger _logger;
private readonly ILogger<MediaFileSystem> _logger;
private readonly IShortStringHelper _shortStringHelper;
/// <summary>
/// Initializes a new instance of the <see cref="MediaFileSystem"/> class.
/// </summary>
public MediaFileSystem(IFileSystem innerFileSystem, IMediaPathScheme mediaPathScheme, ILogger logger, IShortStringHelper shortStringHelper)
public MediaFileSystem(IFileSystem innerFileSystem, IMediaPathScheme mediaPathScheme, ILogger<MediaFileSystem> logger, IShortStringHelper shortStringHelper)
: base(innerFileSystem)
{
_mediaPathScheme = mediaPathScheme;
@@ -51,7 +51,7 @@ namespace Umbraco.Core.IO
}
catch (Exception e)
{
_logger.Error<MediaFileSystem>(e, "Failed to delete media file '{File}'.", file);
_logger.LogError(e, "Failed to delete media file '{File}'.", file);
}
});
}

View File

@@ -2,18 +2,18 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Exceptions;
using Umbraco.Core.Composing;
using System.Threading;
using Umbraco.Core.Hosting;
using Umbraco.Core.Logging;
namespace Umbraco.Core.IO
{
public class PhysicalFileSystem : IFileSystem
{
private readonly IIOHelper _ioHelper;
private readonly ILogger _logger;
private readonly ILogger<PhysicalFileSystem> _logger;
// the rooted, filesystem path, using directory separator chars, NOT ending with a separator
// eg "c:" or "c:\path\to\site" or "\\server\path"
@@ -30,7 +30,7 @@ namespace Umbraco.Core.IO
// virtualRoot should be "~/path/to/root" eg "~/Views"
// the "~/" is mandatory.
public PhysicalFileSystem(IIOHelper ioHelper, IHostingEnvironment hostingEnvironment, ILogger logger, string virtualRoot)
public PhysicalFileSystem(IIOHelper ioHelper, IHostingEnvironment hostingEnvironment, ILogger<PhysicalFileSystem> logger, string virtualRoot)
{
_ioHelper = ioHelper ?? throw new ArgumentNullException(nameof(ioHelper));
if (hostingEnvironment == null) throw new ArgumentNullException(nameof(hostingEnvironment));
@@ -45,7 +45,7 @@ namespace Umbraco.Core.IO
_rootUrl = EnsureUrlSeparatorChar(hostingEnvironment.ToAbsolute(virtualRoot)).TrimEnd('/');
}
public PhysicalFileSystem(IIOHelper ioHelper,IHostingEnvironment hostingEnvironment, ILogger logger, string rootPath, string rootUrl)
public PhysicalFileSystem(IIOHelper ioHelper,IHostingEnvironment hostingEnvironment, ILogger<PhysicalFileSystem> logger, string rootPath, string rootUrl)
{
_ioHelper = ioHelper ?? throw new ArgumentNullException(nameof(ioHelper));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
@@ -87,11 +87,11 @@ namespace Umbraco.Core.IO
}
catch (UnauthorizedAccessException ex)
{
_logger.Error<PhysicalFileSystem>(ex, "Not authorized to get directories for '{Path}'", fullPath);
_logger.LogError(ex, "Not authorized to get directories for '{Path}'", fullPath);
}
catch (DirectoryNotFoundException ex)
{
_logger.Error<PhysicalFileSystem>(ex, "Directory not found for '{Path}'", fullPath);
_logger.LogError(ex, "Directory not found for '{Path}'", fullPath);
}
return Enumerable.Empty<string>();
@@ -123,7 +123,7 @@ namespace Umbraco.Core.IO
}
catch (DirectoryNotFoundException ex)
{
_logger.Error<PhysicalFileSystem>(ex, "Directory not found for '{Path}'", fullPath);
_logger.LogError(ex, "Directory not found for '{Path}'", fullPath);
}
}
@@ -203,11 +203,11 @@ namespace Umbraco.Core.IO
}
catch (UnauthorizedAccessException ex)
{
_logger.Error<PhysicalFileSystem>(ex, "Not authorized to get directories for '{Path}'", fullPath);
_logger.LogError(ex, "Not authorized to get directories for '{Path}'", fullPath);
}
catch (DirectoryNotFoundException ex)
{
_logger.Error<PhysicalFileSystem>(ex, "Directory not found for '{FullPath}'", fullPath);
_logger.LogError(ex, "Directory not found for '{FullPath}'", fullPath);
}
return Enumerable.Empty<string>();
@@ -240,7 +240,7 @@ namespace Umbraco.Core.IO
}
catch (FileNotFoundException ex)
{
_logger.Error<PhysicalFileSystem>(ex.InnerException, "DeleteFile failed with FileNotFoundException for '{Path}'", fullPath);
_logger.LogError(ex.InnerException, "DeleteFile failed with FileNotFoundException for '{Path}'", fullPath);
}
}

View File

@@ -2,9 +2,9 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Composing;
using Umbraco.Core.Hosting;
using Umbraco.Core.Logging;
namespace Umbraco.Core.IO
{
@@ -19,14 +19,14 @@ namespace Umbraco.Core.IO
private string _shadowDir;
private readonly IIOHelper _ioHelper;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly ILogger _logger;
private readonly ILoggerFactory _loggerFactory;
public ShadowWrapper(IFileSystem innerFileSystem, IIOHelper ioHelper, IHostingEnvironment hostingEnvironment, ILogger logger, string shadowPath, Func<bool> isScoped = null)
public ShadowWrapper(IFileSystem innerFileSystem, IIOHelper ioHelper, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory, string shadowPath, Func<bool> isScoped = null)
{
_innerFileSystem = innerFileSystem;
_ioHelper = ioHelper ?? throw new ArgumentNullException(nameof(ioHelper));
_hostingEnvironment = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_loggerFactory = loggerFactory;
_shadowPath = shadowPath;
_isScoped = isScoped;
}
@@ -66,7 +66,7 @@ namespace Umbraco.Core.IO
var virt = ShadowFsPath + "/" + id + "/" + _shadowPath;
_shadowDir = _ioHelper.MapPath(virt);
Directory.CreateDirectory(_shadowDir);
var tempfs = new PhysicalFileSystem(_ioHelper, _hostingEnvironment, _logger, virt);
var tempfs = new PhysicalFileSystem(_ioHelper, _hostingEnvironment, _loggerFactory.CreateLogger<PhysicalFileSystem>(), virt);
_shadowFileSystem = new ShadowFileSystem(_innerFileSystem, tempfs);
}

View File

@@ -1,125 +0,0 @@
using System;
namespace Umbraco.Core.Logging
{
public class ConsoleLogger : ILogger
{
private readonly IMessageTemplates _messageTemplates;
public ConsoleLogger(IMessageTemplates messageTemplates)
{
_messageTemplates = messageTemplates;
}
public bool IsEnabled(Type reporting, LogLevel level)
=> true;
public void Fatal(Type reporting, Exception exception, string message)
{
Console.WriteLine("FATAL {0} - {1}", reporting.Name, message);
Console.WriteLine(exception);
}
public void Fatal(Type reporting, Exception exception)
{
Console.WriteLine("FATAL {0}", reporting.Name);
Console.WriteLine(exception);
}
public void Fatal(Type reporting, string message)
{
Console.WriteLine("FATAL {0} - {1}", reporting.Name, message);
}
public void Fatal(Type reporting, Exception exception, string messageTemplate, params object[] propertyValues)
{
Console.WriteLine("FATAL {0} - {1}", reporting.Name, _messageTemplates.Render(messageTemplate, propertyValues));
Console.WriteLine(exception);
}
public void Fatal(Type reporting, string messageTemplate, params object[] propertyValues)
{
Console.WriteLine("FATAL {0} - {1}", reporting.Name, _messageTemplates.Render(messageTemplate, propertyValues));
}
public void Error(Type reporting, Exception exception, string message)
{
Console.WriteLine("ERROR {0} - {1}", reporting.Name, message);
Console.WriteLine(exception);
}
public void Error(Type reporting, Exception exception)
{
Console.WriteLine("ERROR {0}", reporting.Name);
Console.WriteLine(exception);
}
public void Error(Type reporting, string message)
{
Console.WriteLine("ERROR {0} - {1}", reporting.Name, message);
}
public void Error(Type reporting, Exception exception, string messageTemplate, params object[] propertyValues)
{
Console.WriteLine("ERROR {0} - {1}", reporting.Name, _messageTemplates.Render(messageTemplate, propertyValues));
Console.WriteLine(exception);
}
public void Error(Type reporting, string messageTemplate, params object[] propertyValues)
{
Console.WriteLine("ERROR {0} - {1}", reporting.Name, _messageTemplates.Render(messageTemplate, propertyValues));
}
public void Warn(Type reporting, string message)
{
Console.WriteLine("WARN {0} - {1}", reporting.Name, message);
}
public void Warn(Type reporting, string message, params object[] propertyValues)
{
Console.WriteLine("WARN {0} - {1}", reporting.Name, _messageTemplates.Render(message, propertyValues));
}
public void Warn(Type reporting, Exception exception, string message)
{
Console.WriteLine("WARN {0} - {1}", reporting.Name, message);
Console.WriteLine(exception);
}
public void Warn(Type reporting, Exception exception, string message, params object[] propertyValues)
{
Console.WriteLine("WARN {0} - {1}", reporting.Name, _messageTemplates.Render(message, propertyValues));
Console.WriteLine(exception);
}
public void Info(Type reporting, string messageTemplate, params object[] propertyValues)
{
Console.WriteLine("INFO {0} - {1}", reporting.Name, _messageTemplates.Render(messageTemplate, propertyValues));
}
public void Info(Type reporting, string message)
{
Console.WriteLine("INFO {0} - {1}", reporting.Name, message);
}
public void Debug(Type reporting, string message)
{
Console.WriteLine("DEBUG {0} - {1}", reporting.Name, message);
}
public void Debug(Type reporting, string messageTemplate, params object[] propertyValues)
{
Console.WriteLine("DEBUG {0} - {1}", reporting.Name, _messageTemplates.Render(messageTemplate, propertyValues));
}
public void Verbose(Type reporting, string message)
{
Console.WriteLine("VERBOSE {0} - {1}", reporting.Name, message);
}
public void Verbose(Type reporting, string messageTemplate, params object[] propertyValues)
{
Console.WriteLine("VERBOSE {0} - {1}", reporting.Name, _messageTemplates.Render(messageTemplate, propertyValues));
}
}
}

View File

@@ -1,140 +0,0 @@
using System;
namespace Umbraco.Core.Logging
{
/// <summary>
/// Implements <see cref="ILogger"/> on top of <see cref="System.Diagnostics"/>.
/// </summary>
public class DebugDiagnosticsLogger : ILogger
{
private readonly IMessageTemplates _messageTemplates;
public DebugDiagnosticsLogger(IMessageTemplates messageTemplates)
{
_messageTemplates = messageTemplates;
}
public bool IsEnabled(Type reporting, LogLevel level)
=> true;
/// <inheritdoc/>
public void Fatal(Type reporting, Exception exception, string message)
{
System.Diagnostics.Debug.WriteLine(message + Environment.NewLine + exception, reporting.FullName);
}
/// <inheritdoc/>
public void Fatal(Type reporting, Exception exception)
{
System.Diagnostics.Debug.WriteLine(Environment.NewLine + exception, reporting.FullName);
}
/// <inheritdoc/>
public void Fatal(Type reporting, string message)
{
System.Diagnostics.Debug.WriteLine(message);
}
/// <inheritdoc/>
public void Fatal(Type reporting, Exception exception, string messageTemplate, params object[] propertyValues)
{
System.Diagnostics.Debug.WriteLine(_messageTemplates.Render(messageTemplate, propertyValues) + Environment.NewLine + exception, reporting.FullName);
}
/// <inheritdoc/>
public void Fatal(Type reporting, string messageTemplate, params object[] propertyValues)
{
System.Diagnostics.Debug.WriteLine(messageTemplate, propertyValues);
}
/// <inheritdoc/>
public void Error(Type reporting, Exception exception, string message)
{
System.Diagnostics.Debug.WriteLine(message + Environment.NewLine + exception, reporting.FullName);
}
/// <inheritdoc/>
public void Error(Type reporting, Exception exception)
{
System.Diagnostics.Debug.WriteLine(Environment.NewLine + exception, reporting.FullName);
}
/// <inheritdoc/>
public void Error(Type reporting, string message)
{
System.Diagnostics.Debug.WriteLine(message);
}
/// <inheritdoc/>
public void Error(Type reporting, Exception exception, string messageTemplate, params object[] propertyValues)
{
System.Diagnostics.Debug.WriteLine(_messageTemplates.Render(messageTemplate, propertyValues) + Environment.NewLine + exception, reporting.FullName);
}
/// <inheritdoc/>
public void Error(Type reporting, string messageTemplate, params object[] propertyValues)
{
System.Diagnostics.Debug.WriteLine(messageTemplate, propertyValues);
}
/// <inheritdoc/>
public void Warn(Type reporting, string message)
{
System.Diagnostics.Debug.WriteLine(message, reporting.FullName);
}
/// <inheritdoc/>
public void Warn(Type reporting, string message, params object[] propertyValues)
{
System.Diagnostics.Debug.WriteLine(_messageTemplates.Render(message, propertyValues), reporting.FullName);
}
/// <inheritdoc/>
public void Warn(Type reporting, Exception exception, string message)
{
System.Diagnostics.Debug.WriteLine(message + Environment.NewLine + exception, reporting.FullName);
}
/// <inheritdoc/>
public void Warn(Type reporting, Exception exception, string message, params object[] propertyValues)
{
System.Diagnostics.Debug.WriteLine(_messageTemplates.Render(message + Environment.NewLine + exception, propertyValues), reporting.FullName);
}
/// <inheritdoc/>
public void Info(Type reporting, string message)
{
System.Diagnostics.Debug.WriteLine(message, reporting.FullName);
}
/// <inheritdoc/>
public void Info(Type reporting, string messageTemplate, params object[] propertyValues)
{
System.Diagnostics.Debug.WriteLine(_messageTemplates.Render(messageTemplate, propertyValues), reporting.FullName);
}
/// <inheritdoc/>
public void Debug(Type reporting, string message)
{
System.Diagnostics.Debug.WriteLine(message, reporting.FullName);
}
/// <inheritdoc/>
public void Debug(Type reporting, string messageTemplate, params object[] propertyValues)
{
System.Diagnostics.Debug.WriteLine(_messageTemplates.Render(messageTemplate, propertyValues), reporting.FullName);
}
/// <inheritdoc/>
public void Verbose(Type reporting, string message)
{
System.Diagnostics.Debug.WriteLine(message, reporting.FullName);
}
/// <inheritdoc/>
public void Verbose(Type reporting, string messageTemplate, params object[] propertyValues)
{
System.Diagnostics.Debug.WriteLine(_messageTemplates.Render(messageTemplate, propertyValues), reporting.FullName);
}
}
}

View File

@@ -1,5 +1,6 @@
using System;
using System.Diagnostics;
using Microsoft.Extensions.Logging;
namespace Umbraco.Core.Logging
{
@@ -37,10 +38,10 @@ namespace Umbraco.Core.Logging
switch (_level)
{
case LogLevel.Debug:
logger.Debug(loggerType, "{StartMessage} [Timing {TimingId}]", startMessage, _timingId);
logger.LogDebug("{StartMessage} [Timing {TimingId}]", startMessage, _timingId);
break;
case LogLevel.Information:
logger.Info(loggerType, "{StartMessage} [Timing {TimingId}]", startMessage, _timingId);
logger.LogInformation("{StartMessage} [Timing {TimingId}]", startMessage, _timingId);
break;
default:
throw new ArgumentOutOfRangeException(nameof(level));
@@ -84,15 +85,15 @@ namespace Umbraco.Core.Logging
{
if (_failed)
{
_logger.Error(_loggerType, _failException, "{FailMessage} ({Duration}ms) [Timing {TimingId}]", _failMessage, Stopwatch.ElapsedMilliseconds, _timingId);
_logger.LogError(_failException, "{FailMessage} ({Duration}ms) [Timing {TimingId}]", _failMessage, Stopwatch.ElapsedMilliseconds, _timingId);
}
else switch (_level)
{
case LogLevel.Debug:
_logger.Debug(_loggerType, "{EndMessage} ({Duration}ms) [Timing {TimingId}]", _endMessage, Stopwatch.ElapsedMilliseconds, _timingId);
_logger.LogDebug("{EndMessage} ({Duration}ms) [Timing {TimingId}]", _endMessage, Stopwatch.ElapsedMilliseconds, _timingId);
break;
case LogLevel.Information:
_logger.Info(_loggerType, "{EndMessage} ({Duration}ms) [Timing {TimingId}]", _endMessage, Stopwatch.ElapsedMilliseconds, _timingId);
_logger.LogInformation("{EndMessage} ({Duration}ms) [Timing {TimingId}]", _endMessage, Stopwatch.ElapsedMilliseconds, _timingId);
break;
// filtered in the ctor
//default:

View File

@@ -1,182 +0,0 @@
using System;
namespace Umbraco.Core.Logging
{
/// <summary>
/// Defines the logging service.
/// </summary>
/// <remarks>
/// <para>Message templates in logging methods follow the Message Templates specification
/// available at https://messagetemplates.org/ in order to support structured logging.</para>
/// <para>Implementations must ensure that they support these templates. Note that the
/// specification includes support for traditional C# numeric placeholders.</para>
/// <para>For instance, "Processed {Input} in {Time}ms."</para>
/// </remarks>
public interface ILogger
{
/// <summary>
/// Determines if logging is enabled at a specified level, for a reporting type.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="level">The level.</param>
bool IsEnabled(Type reporting, LogLevel level);
/// <summary>
/// Logs a fatal message with an exception.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="exception">An exception.</param>
/// <param name="message">A message.</param>
void Fatal(Type reporting, Exception exception, string message);
/// <summary>
/// Logs a fatal exception.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="exception">An exception.</param>
/// <remarks>The message string is unspecified and is implementation-specific.</remarks>
void Fatal(Type reporting, Exception exception);
/// <summary>
/// Logs a fatal message.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="message">A message.</param>
void Fatal(Type reporting, string message);
/// <summary>
/// Logs a fatal message with an exception.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="exception">An exception.</param>
/// <param name="messageTemplate">A message template.</param>
/// <param name="propertyValues">Property values.</param>
void Fatal(Type reporting, Exception exception, string messageTemplate, params object[] propertyValues);
/// <summary>
/// Logs a fatal message.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="messageTemplate">A message template.</param>
/// <param name="propertyValues">Property values.</param>
void Fatal(Type reporting, string messageTemplate, params object[] propertyValues);
/// <summary>
/// Logs an error message with an exception.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="exception">An exception.</param>
/// <param name="message">A message.</param>
void Error(Type reporting, Exception exception, string message);
/// <summary>
/// Logs an error exception.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="exception">An exception.</param>
/// <remarks>The message string is unspecified and is implementation-specific.</remarks>
void Error(Type reporting, Exception exception);
/// <summary>
/// Logs an error message.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="message">A message.</param>
void Error(Type reporting, string message);
/// <summary>
/// Logs an error message with an exception.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="exception">An exception.</param>
/// <param name="messageTemplate">A message template.</param>
/// <param name="propertyValues">Property values.</param>
void Error(Type reporting, Exception exception, string messageTemplate, params object[] propertyValues);
/// <summary>
/// Logs an error message.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="messageTemplate">A message template.</param>
/// <param name="propertyValues">Property values.</param>
void Error(Type reporting, string messageTemplate, params object[] propertyValues);
/// <summary>
/// Logs a warning message.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="message">A message.</param>
void Warn(Type reporting, string message);
/// <summary>
/// Logs a warning message.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="messageTemplate">A message template.</param>
/// <param name="propertyValues">Property values.</param>
void Warn(Type reporting, string messageTemplate, params object[] propertyValues);
/// <summary>
/// Logs a warning message with an exception.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="exception">An exception.</param>
/// <param name="message">A message.</param>
void Warn(Type reporting, Exception exception, string message);
/// <summary>
/// Logs a warning message with an exception.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="exception">An exception.</param>
/// <param name="messageTemplate">A message template.</param>
/// <param name="propertyValues">Property values.</param>
void Warn(Type reporting, Exception exception, string messageTemplate, params object[] propertyValues);
/// <summary>
/// Logs an information message.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="message">A message.</param>
void Info(Type reporting, string message);
/// <summary>
/// Logs a info message.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="messageTemplate">A message template.</param>
/// <param name="propertyValues">Property values.</param>
void Info(Type reporting, string messageTemplate, params object[] propertyValues);
/// <summary>
/// Logs a debugging message.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="message">A message.</param>
void Debug(Type reporting, string message);
/// <summary>
/// Logs a debug message.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="messageTemplate">A message template.</param>
/// <param name="propertyValues">Property values.</param>
void Debug(Type reporting, string messageTemplate, params object[] propertyValues);
/// <summary>
/// Logs a verbose message.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="message">A message.</param>
void Verbose(Type reporting, string message);
/// <summary>
/// Logs a verbose message.
/// </summary>
/// <param name="reporting">The reporting type.</param>
/// <param name="messageTemplate">A message template.</param>
/// <param name="propertyValues">Property values.</param>
void Verbose(Type reporting, string messageTemplate, params object[] propertyValues);
}
}

View File

@@ -5,7 +5,7 @@ namespace Umbraco.Core.Logging
/// <summary>
/// Defines the profiling logging service.
/// </summary>
public interface IProfilingLogger : ILogger
public interface IProfilingLogger
{
/// <summary>
/// Profiles an action and log as information messages.

View File

@@ -1,5 +1,6 @@
using System;
using System.Diagnostics;
using Microsoft.Extensions.Logging;
namespace Umbraco.Core.Logging
{
@@ -8,9 +9,9 @@ namespace Umbraco.Core.Logging
/// </summary>
public class LogProfiler : IProfiler
{
private readonly ILogger _logger;
private readonly ILogger<LogProfiler> _logger;
public LogProfiler(ILogger logger)
public LogProfiler(ILogger<LogProfiler> logger)
{
_logger = logger;
}
@@ -18,8 +19,8 @@ namespace Umbraco.Core.Logging
/// <inheritdoc/>
public IDisposable Step(string name)
{
_logger.Debug<LogProfiler>("Begin: {ProfileName}", name);
return new LightDisposableTimer(duration => _logger.Info<LogProfiler>("End {ProfileName} ({ProfileDuration}ms)", name, duration));
_logger.LogDebug("Begin: {ProfileName}", name);
return new LightDisposableTimer(duration => _logger.LogInformation("End {ProfileName} ({ProfileDuration}ms)", name, duration));
}
/// <inheritdoc/>

View File

@@ -1,186 +0,0 @@
using System;
namespace Umbraco.Core.Logging
{
/// <summary>
/// Provides extension methods for the <see cref="ILogger"/> interface.
/// </summary>
public static class LoggerExtensions
{
/// <summary>
/// Determines if logging is enabled at a specified level, for a reporting type.
/// </summary>
/// <typeparam name="T">The reporting type.</typeparam>
/// <param name="logger">The logger.</param>
/// <param name="level">The level.</param>
public static bool IsEnabled<T>(this ILogger logger, LogLevel level)
=> logger.IsEnabled(typeof(T), level);
/// <summary>
/// Logs an error message with an exception.
/// </summary>
/// <typeparam name="T">The reporting type.</typeparam>
/// <param name="logger">The logger.</param>
/// <param name="message">A message.</param>
/// <param name="exception">An exception.</param>
public static void Error<T>(this ILogger logger, Exception exception, string message)
=> logger.Error(typeof(T), exception, message);
/// <summary>
/// Logs an error message with an exception.
/// </summary>
/// <typeparam name="T">The reporting type.</typeparam>
/// <param name="logger">The logger.</param>
/// <param name="exception">An exception.</param>
/// <param name="messageTemplate">A message template.</param>
/// <param name="propertyValues">Property values.</param>
public static void Error<T>(this ILogger logger, Exception exception, string messageTemplate, params object[] propertyValues)
=> logger.Error(typeof(T), exception, messageTemplate, propertyValues);
/// <summary>
/// Logs an error exception.
/// </summary>
/// <typeparam name="T">The reporting type.</typeparam>
/// <param name="logger">The logger.</param>
/// <param name="exception">An exception.</param>
public static void Error<T>(this ILogger logger, Exception exception)
=> logger.Error(typeof(T), exception);
/// <summary>
/// Logs an error message.
/// </summary>
/// <typeparam name="T">The reporting type.</typeparam>
/// <param name="logger">The logger.</param>
/// <param name="message">A message.</param>
public static void Error<T>(this ILogger logger, string message)
=> logger.Error(typeof(T), message);
/// <summary>
/// Logs an error message.
/// </summary>
/// <typeparam name="T">The reporting type.</typeparam>
/// <param name="logger">The logger.</param>
/// <param name="messageTemplate">A message template.</param>
/// <param name="propertyValues">Property values.</param>
public static void Error<T>(this ILogger logger, string messageTemplate, params object[] propertyValues)
=> logger.Error(typeof(T), messageTemplate, propertyValues);
/// <summary>
/// Logs a warning message.
/// </summary>
/// <typeparam name="T">The reporting type.</typeparam>
/// <param name="logger">The logger.</param>
/// <param name="message">A message.</param>
public static void Warn<T>(this ILogger logger, string message)
=> logger.Warn(typeof(T), message);
/// <summary>
/// Logs a warning message.
/// </summary>
/// <typeparam name="T">The reporting type.</typeparam>
/// <param name="logger">The logger.</param>
/// <param name="messageTemplate">A message template.</param>
/// <param name="propertyValues">Property values.</param>
public static void Warn<T>(this ILogger logger, string messageTemplate, params object[] propertyValues)
=> logger.Warn(typeof(T), messageTemplate, propertyValues);
/// <summary>
/// Logs a warning message with an exception.
/// </summary>
/// <typeparam name="T">The reporting type.</typeparam>
/// <param name="logger">The logger.</param>
/// <param name="exception">An exception.</param>
/// <param name="message">A message.</param>
public static void Warn<T>(this ILogger logger, Exception exception, string message)
=> logger.Warn(typeof(T), exception, message);
/// <summary>
/// Logs a warning message with an exception.
/// </summary>
/// <typeparam name="T">The reporting type.</typeparam>
/// <param name="logger">The logger.</param>
/// <param name="exception">An exception.</param>
/// <param name="messageTemplate">A message template.</param>
/// <param name="propertyValues">Property values.</param>
public static void Warn<T>(this ILogger logger, Exception exception, string messageTemplate, params object[] propertyValues)
=> logger.Warn(typeof(T), exception, messageTemplate, propertyValues);
/// <summary>
/// Logs an information message.
/// </summary>
/// <typeparam name="T">The reporting type.</typeparam>
/// <param name="logger">The logger.</param>
/// <param name="message">A message.</param>
public static void Info<T>(this ILogger logger, string message)
=> logger.Info(typeof(T), message);
/// <summary>
/// Logs a information message.
/// </summary>
/// <typeparam name="T">The reporting type</typeparam>
/// <param name="logger">The logger.</param>
/// <param name="messageTemplate">A message template.</param>
/// <param name="propertyValues">Property values.</param>
public static void Info<T>(this ILogger logger, string messageTemplate, params object[] propertyValues)
=> logger.Info(typeof(T), messageTemplate, propertyValues);
/// <summary>
/// Logs a debugging message.
/// </summary>
/// <typeparam name="T">The reporting type.</typeparam>
/// <param name="logger">The logger.</param>
/// <param name="message">A message.</param>
public static void Debug<T>(this ILogger logger, string message)
=> logger.Debug(typeof(T), message);
/// <summary>
/// Logs a debugging message.
/// </summary>
/// <typeparam name="T">The reporting type</typeparam>
/// <param name="logger">The logger.</param>
/// <param name="messageTemplate">A message template.</param>
/// <param name="propertyValues">Property values.</param>
public static void Debug<T>(this ILogger logger, string messageTemplate, params object[] propertyValues)
=> logger.Debug(typeof(T), messageTemplate, propertyValues);
/// <summary>
/// Logs a verbose message.
/// </summary>
/// <typeparam name="T">The reporting type.</typeparam>
/// <param name="logger">The logger.</param>
/// <param name="message">A message.</param>
public static void Verbose<T>(this ILogger logger, string message)
=> logger.Verbose(typeof(T), message);
/// <summary>
/// Logs a verbose message.
/// </summary>
/// <typeparam name="T">The reporting type.</typeparam>
/// <param name="logger">The logger.</param>
/// <param name="messageTemplate">A message template.</param>
/// <param name="propertyValues">Property values.</param>
public static void Verbose<T>(this ILogger logger, string messageTemplate, params object[] propertyValues)
=> logger.Verbose(typeof(T), messageTemplate, propertyValues);
/// <summary>
/// Logs a fatal message.
/// </summary>
/// <typeparam name="T">The reporting type.</typeparam>
/// <param name="logger">The logger.</param>
/// <param name="exception">An exception.</param>
/// <param name="message">A message.</param>
public static void Fatal<T>(this ILogger logger, Exception exception, string message)
=> logger.Fatal(typeof(T), exception, message);
/// <summary>
/// Logs a fatal message.
/// </summary>
/// <typeparam name="T">The reporting type.</typeparam>
/// <param name="logger">The logger.</param>
/// <param name="exception">An exception.</param>
/// <param name="messageTemplate">A message template.</param>
/// <param name="propertyValues">Property values.</param>
public static void Fatal<T>(this ILogger logger, Exception exception, string messageTemplate, params object[] propertyValues)
=> logger.Fatal(typeof(T), exception, messageTemplate, propertyValues);
}
}

View File

@@ -1,109 +0,0 @@
using System;
namespace Umbraco.Core.Logging
{
public class NullLogger : ILogger
{
public bool IsEnabled(Type reporting, LogLevel level) => false;
public void Fatal(Type reporting, Exception exception, string message)
{
}
public void Fatal(Type reporting, Exception exception)
{
}
public void Fatal(Type reporting, string message)
{
}
public void Fatal(Type reporting, Exception exception, string messageTemplate, params object[] propertyValues)
{
}
public void Fatal(Type reporting, string messageTemplate, params object[] propertyValues)
{
}
public void Error(Type reporting, Exception exception, string message)
{
}
public void Error(Type reporting, Exception exception)
{
}
public void Error(Type reporting, string message)
{
}
public void Error(Type reporting, Exception exception, string messageTemplate, params object[] propertyValues)
{
}
public void Error(Type reporting, string messageTemplate, params object[] propertyValues)
{
}
public void Warn(Type reporting, string message)
{
}
public void Warn(Type reporting, string messageTemplate, params object[] propertyValues)
{
}
public void Warn(Type reporting, Exception exception, string message)
{
}
public void Warn(Type reporting, Exception exception, string messageTemplate, params object[] propertyValues)
{
}
public void Info(Type reporting, string message)
{
}
public void Info(Type reporting, string messageTemplate, params object[] propertyValues)
{
}
public void Debug(Type reporting, string message)
{
}
public void Debug(Type reporting, string messageTemplate, params object[] propertyValues)
{
}
public void Verbose(Type reporting, string message)
{
}
public void Verbose(Type reporting, string messageTemplate, params object[] propertyValues)
{
}
}
}

View File

@@ -1,4 +1,7 @@
using System;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Models;
namespace Umbraco.Core.Logging
{
@@ -43,89 +46,56 @@ namespace Umbraco.Core.Logging
public DisposableTimer DebugDuration<T>(string startMessage)
{
return Logger.IsEnabled<T>(LogLevel.Debug)
return Logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)
? DebugDuration<T>(startMessage, "Completed.")
: null;
}
public DisposableTimer DebugDuration<T>(string startMessage, string completeMessage, string failMessage = null, int thresholdMilliseconds = 0)
{
return Logger.IsEnabled<T>(LogLevel.Debug)
return Logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)
? new DisposableTimer(Logger, LogLevel.Debug, Profiler, typeof(T), startMessage, completeMessage, failMessage, thresholdMilliseconds)
: null;
}
public DisposableTimer DebugDuration(Type loggerType, string startMessage, string completeMessage, string failMessage = null, int thresholdMilliseconds = 0)
{
return Logger.IsEnabled(loggerType, LogLevel.Debug)
return Logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)
? new DisposableTimer(Logger, LogLevel.Debug, Profiler, loggerType, startMessage, completeMessage, failMessage, thresholdMilliseconds)
: null;
}
#region ILogger
public bool IsEnabled(Type reporting, LogLevel level)
=> Logger.IsEnabled(reporting, level);
public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel level)
=> Logger.IsEnabled(level);
public void Fatal(Type reporting, Exception exception, string message)
=> Logger.Fatal(reporting, exception, message);
public void LogCritical(Exception exception, string messageTemplate, params object[] propertyValues)
=> Logger.LogCritical(exception, messageTemplate, propertyValues);
public void Fatal(Type reporting, Exception exception)
=> Logger.Fatal(reporting, exception);
public void LogCritical(string messageTemplate, params object[] propertyValues)
=> Logger.LogCritical(messageTemplate, propertyValues);
public void Fatal(Type reporting, string message)
=> Logger.Fatal(reporting, message);
public void LogError(Exception exception, string messageTemplate, params object[] propertyValues)
=> Logger.LogError(exception, messageTemplate, propertyValues);
public void Fatal(Type reporting, Exception exception, string messageTemplate, params object[] propertyValues)
=> Logger.Fatal(reporting, exception, messageTemplate, propertyValues);
public void LogError(string messageTemplate, params object[] propertyValues)
=> Logger.LogError(messageTemplate, propertyValues);
public void Fatal(Type reporting, string messageTemplate, params object[] propertyValues)
=> Logger.Fatal(reporting, messageTemplate, propertyValues);
public void LogWarning(string messageTemplate, params object[] propertyValues)
=> Logger.LogWarning(messageTemplate, propertyValues);
public void Error(Type reporting, Exception exception, string message)
=> Logger.Error(reporting, exception, message);
public void LogWarning(Exception exception, string messageTemplate, params object[] propertyValues)
=> Logger.LogWarning(exception, messageTemplate, propertyValues);
public void Error(Type reporting, Exception exception)
=> Logger.Error(reporting, exception);
public void LogInformation(string messageTemplate, params object[] propertyValues)
=> Logger.LogInformation(messageTemplate, propertyValues);
public void Error(Type reporting, string message)
=> Logger.Error(reporting, message);
public void LogDebug(string messageTemplate, params object[] propertyValues)
=> Logger.LogDebug(messageTemplate, propertyValues);
public void Error(Type reporting, Exception exception, string messageTemplate, params object[] propertyValues)
=> Logger.Error(reporting, exception, messageTemplate, propertyValues);
public void Error(Type reporting, string messageTemplate, params object[] propertyValues)
=> Logger.Error(reporting, messageTemplate, propertyValues);
public void Warn(Type reporting, string message)
=> Logger.Warn(reporting, message);
public void Warn(Type reporting, string messageTemplate, params object[] propertyValues)
=> Logger.Warn(reporting, messageTemplate, propertyValues);
public void Warn(Type reporting, Exception exception, string message)
=> Logger.Warn(reporting, exception, message);
public void Warn(Type reporting, Exception exception, string messageTemplate, params object[] propertyValues)
=> Logger.Warn(reporting, exception, messageTemplate, propertyValues);
public void Info(Type reporting, string message)
=> Logger.Info(reporting, message);
public void Info(Type reporting, string messageTemplate, params object[] propertyValues)
=> Logger.Info(reporting, messageTemplate, propertyValues);
public void Debug(Type reporting, string message)
=> Logger.Debug(reporting, message);
public void Debug(Type reporting, string messageTemplate, params object[] propertyValues)
=> Logger.Debug(reporting, messageTemplate, propertyValues);
public void Verbose(Type reporting, string message)
=> Logger.Verbose(reporting, message);
public void Verbose(Type reporting, string messageTemplate, params object[] propertyValues)
=> Logger.Verbose(reporting, messageTemplate, propertyValues);
public void LogTrace(string messageTemplate, params object[] propertyValues)
=> Logger.LogTrace(messageTemplate, propertyValues);
#endregion
}

View File

@@ -2,8 +2,8 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Hosting;
using Umbraco.Core.Logging;
using Umbraco.Net;
namespace Umbraco.Core.Manifest
@@ -13,11 +13,11 @@ namespace Umbraco.Core.Manifest
private static readonly object Locker = new object();
private static volatile bool _isRestarting;
private readonly ILogger _logger;
private readonly ILogger<ManifestWatcher> _logger;
private readonly IUmbracoApplicationLifetime _umbracoApplicationLifetime;
private readonly List<FileSystemWatcher> _fws = new List<FileSystemWatcher>();
public ManifestWatcher(ILogger logger, IUmbracoApplicationLifetime umbracoApplicationLifetime)
public ManifestWatcher(ILogger<ManifestWatcher> logger, IUmbracoApplicationLifetime umbracoApplicationLifetime)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_umbracoApplicationLifetime = umbracoApplicationLifetime;
@@ -57,7 +57,7 @@ namespace Umbraco.Core.Manifest
if (_isRestarting) return;
_isRestarting = true;
_logger.Info<ManifestWatcher>("Manifest has changed, app pool is restarting ({Path})", e.FullPath);
_logger.LogInformation("Manifest has changed, app pool is restarting ({Path})", e.FullPath);
_umbracoApplicationLifetime.Restart();
Dispose(); // uh? if the app restarts then this should be disposed anyways?
}

View File

@@ -1,7 +1,7 @@
using System;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Mapping;
using Umbraco.Core.Models;
using Umbraco.Core.PropertyEditors;
@@ -17,11 +17,11 @@ namespace Umbraco.Web.Models.Mapping
where TDestination : ContentPropertyBasic, new()
{
private readonly IEntityService _entityService;
private readonly ILogger _logger;
private readonly ILogger<ContentPropertyBasicMapper<TDestination>> _logger;
private readonly PropertyEditorCollection _propertyEditors;
protected IDataTypeService DataTypeService { get; }
public ContentPropertyBasicMapper(IDataTypeService dataTypeService, IEntityService entityService, ILogger logger, PropertyEditorCollection propertyEditors)
public ContentPropertyBasicMapper(IDataTypeService dataTypeService, IEntityService entityService, ILogger<ContentPropertyBasicMapper<TDestination>> logger, PropertyEditorCollection propertyEditors)
{
_logger = logger;
_propertyEditors = propertyEditors;
@@ -38,7 +38,7 @@ namespace Umbraco.Web.Models.Mapping
var editor = _propertyEditors[property.PropertyType.PropertyEditorAlias];
if (editor == null)
{
_logger.Error<ContentPropertyBasicMapper<TDestination>>(
_logger.LogError(
new NullReferenceException("The property editor with alias " + property.PropertyType.PropertyEditorAlias + " does not exist"),
"No property editor '{PropertyEditorAlias}' found, converting to a Label",
property.PropertyType.PropertyEditorAlias);

View File

@@ -1,5 +1,5 @@
using Umbraco.Core.Dictionary;
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Dictionary;
using Umbraco.Core.Mapping;
using Umbraco.Core.Models;
using Umbraco.Core.PropertyEditors;
@@ -16,7 +16,7 @@ namespace Umbraco.Web.Models.Mapping
private readonly ICultureDictionary _cultureDictionary;
private readonly ILocalizedTextService _textService;
public ContentPropertyDisplayMapper(ICultureDictionary cultureDictionary, IDataTypeService dataTypeService, IEntityService entityService, ILocalizedTextService textService, ILogger logger, PropertyEditorCollection propertyEditors)
public ContentPropertyDisplayMapper(ICultureDictionary cultureDictionary, IDataTypeService dataTypeService, IEntityService entityService, ILocalizedTextService textService, ILogger<ContentPropertyDisplayMapper> logger, PropertyEditorCollection propertyEditors)
: base(dataTypeService, entityService, logger, propertyEditors)
{
_cultureDictionary = cultureDictionary;

View File

@@ -1,4 +1,4 @@
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Mapping;
using Umbraco.Core.Models;
using Umbraco.Core.PropertyEditors;
@@ -12,7 +12,7 @@ namespace Umbraco.Web.Models.Mapping
/// </summary>
internal class ContentPropertyDtoMapper : ContentPropertyBasicMapper<ContentPropertyDto>
{
public ContentPropertyDtoMapper(IDataTypeService dataTypeService, IEntityService entityService, ILogger logger, PropertyEditorCollection propertyEditors)
public ContentPropertyDtoMapper(IDataTypeService dataTypeService, IEntityService entityService, ILogger<ContentPropertyDtoMapper> logger, PropertyEditorCollection propertyEditors)
: base(dataTypeService, entityService, logger, propertyEditors)
{ }

View File

@@ -1,5 +1,5 @@
using Umbraco.Core.Dictionary;
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Dictionary;
using Umbraco.Core.Mapping;
using Umbraco.Core.Models;
using Umbraco.Core.PropertyEditors;
@@ -18,11 +18,11 @@ namespace Umbraco.Web.Models.Mapping
private readonly ContentPropertyDtoMapper _contentPropertyDtoConverter;
private readonly ContentPropertyDisplayMapper _contentPropertyDisplayMapper;
public ContentPropertyMapDefinition(ICultureDictionary cultureDictionary, IDataTypeService dataTypeService, IEntityService entityService, ILocalizedTextService textService, ILogger logger, PropertyEditorCollection propertyEditors)
public ContentPropertyMapDefinition(ICultureDictionary cultureDictionary, IDataTypeService dataTypeService, IEntityService entityService, ILocalizedTextService textService, ILoggerFactory loggerFactory, PropertyEditorCollection propertyEditors)
{
_contentPropertyBasicConverter = new ContentPropertyBasicMapper<ContentPropertyBasic>(dataTypeService, entityService, logger, propertyEditors);
_contentPropertyDtoConverter = new ContentPropertyDtoMapper(dataTypeService, entityService, logger, propertyEditors);
_contentPropertyDisplayMapper = new ContentPropertyDisplayMapper(cultureDictionary, dataTypeService, entityService, textService, logger, propertyEditors);
_contentPropertyBasicConverter = new ContentPropertyBasicMapper<ContentPropertyBasic>(dataTypeService, entityService, loggerFactory.CreateLogger<ContentPropertyBasicMapper<ContentPropertyBasic>>(), propertyEditors);
_contentPropertyDtoConverter = new ContentPropertyDtoMapper(dataTypeService, entityService, loggerFactory.CreateLogger<ContentPropertyDtoMapper>(), propertyEditors);
_contentPropertyDisplayMapper = new ContentPropertyDisplayMapper(cultureDictionary, dataTypeService, entityService, textService, loggerFactory.CreateLogger<ContentPropertyDisplayMapper>(), propertyEditors);
}
public void DefineMaps(UmbracoMapper mapper)

View File

@@ -2,8 +2,9 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.Serialization;
using Microsoft.Extensions.Logging;
using Umbraco.Composing;
using Umbraco.Core.Logging;
namespace Umbraco.Core.Models
{
@@ -414,7 +415,7 @@ namespace Umbraco.Core.Models
public virtual string ContentTypeAlias => ContentType.Alias;
/// <summary>
/// Internal/Experimental - only used for mapping queries.
/// Internal/Experimental - only used for mapping queries.
/// </summary>
/// <remarks>
/// Adding these to have first level properties instead of the Properties collection.
@@ -423,7 +424,7 @@ namespace Umbraco.Core.Models
[EditorBrowsable(EditorBrowsableState.Never)]
public string LongStringPropertyValue { get; set; }
/// <summary>
/// Internal/Experimental - only used for mapping queries.
/// Internal/Experimental - only used for mapping queries.
/// </summary>
/// <remarks>
/// Adding these to have first level properties instead of the Properties collection.
@@ -432,7 +433,7 @@ namespace Umbraco.Core.Models
[EditorBrowsable(EditorBrowsableState.Never)]
public string ShortStringPropertyValue { get; set; }
/// <summary>
/// Internal/Experimental - only used for mapping queries.
/// Internal/Experimental - only used for mapping queries.
/// </summary>
/// <remarks>
/// Adding these to have first level properties instead of the Properties collection.
@@ -441,7 +442,7 @@ namespace Umbraco.Core.Models
[EditorBrowsable(EditorBrowsableState.Never)]
public int IntegerPropertyValue { get; set; }
/// <summary>
/// Internal/Experimental - only used for mapping queries.
/// Internal/Experimental - only used for mapping queries.
/// </summary>
/// <remarks>
/// Adding these to have first level properties instead of the Properties collection.
@@ -450,7 +451,7 @@ namespace Umbraco.Core.Models
[EditorBrowsable(EditorBrowsableState.Never)]
public bool BoolPropertyValue { get; set; }
/// <summary>
/// Internal/Experimental - only used for mapping queries.
/// Internal/Experimental - only used for mapping queries.
/// </summary>
/// <remarks>
/// Adding these to have first level properties instead of the Properties collection.
@@ -459,7 +460,7 @@ namespace Umbraco.Core.Models
[EditorBrowsable(EditorBrowsableState.Never)]
public DateTime DateTimePropertyValue { get; set; }
/// <summary>
/// Internal/Experimental - only used for mapping queries.
/// Internal/Experimental - only used for mapping queries.
/// </summary>
/// <remarks>
/// Adding these to have first level properties instead of the Properties collection.
@@ -472,7 +473,7 @@ namespace Umbraco.Core.Models
{
void DoLog(string logPropertyAlias, string logPropertyName)
{
Current.Logger.Warn<Member>("Trying to access the '{PropertyName}' property on '{MemberType}' " +
Current.Logger.LogWarning("Trying to access the '{PropertyName}' property on '{MemberType}' " +
"but the {PropertyAlias} property does not exist on the member type so a default value is returned. " +
"Ensure that you have a property type with alias: {PropertyAlias} configured on your member type in order to use the '{PropertyName}' property on the model correctly.",
logPropertyName,
@@ -497,7 +498,7 @@ namespace Umbraco.Core.Models
{
void DoLog(string logPropertyAlias, string logPropertyName)
{
Current.Logger.Warn<Member>("An attempt was made to set a value on the property '{PropertyName}' on type '{MemberType}' but the " +
Current.Logger.LogWarning("An attempt was made to set a value on the property '{PropertyName}' on type '{MemberType}' but the " +
"property type {PropertyAlias} does not exist on the member type, ensure that this property type exists so that setting this property works correctly.",
logPropertyName,
typeof(Member),
@@ -524,6 +525,6 @@ namespace Umbraco.Core.Models
/// <inheritdoc />
[IgnoreDataMember]
public bool HasAdditionalData => _additionalData != null;
public bool HasAdditionalData => _additionalData != null;
}
}

View File

@@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging;
using Umbraco.Core.PackageActions;
namespace Umbraco.Core.Packaging
@@ -11,10 +11,10 @@ namespace Umbraco.Core.Packaging
/// </summary>
public class PackageActionRunner : IPackageActionRunner
{
private readonly ILogger _logger;
private readonly ILogger<PackageActionRunner> _logger;
private readonly PackageActionCollection _packageActions;
public PackageActionRunner(ILogger logger, PackageActionCollection packageActions)
public PackageActionRunner(ILogger<PackageActionRunner> logger, PackageActionCollection packageActions)
{
_logger = logger;
_packageActions = packageActions;
@@ -34,7 +34,7 @@ namespace Umbraco.Core.Packaging
catch (Exception ex)
{
e.Add($"{ipa.Alias()} - {ex.Message}");
_logger.Error<PackageActionRunner>(ex, "Error loading package action '{PackageActionAlias}' for package {PackageName}", ipa.Alias(), packageName);
_logger.LogError(ex, "Error loading package action '{PackageActionAlias}' for package {PackageName}", ipa.Alias(), packageName);
}
}
@@ -56,7 +56,7 @@ namespace Umbraco.Core.Packaging
catch (Exception ex)
{
e.Add($"{ipa.Alias()} - {ex.Message}");
_logger.Error<PackageActionRunner>(ex, "Error undoing package action '{PackageActionAlias}' for package {PackageName}", ipa.Alias(), packageName);
_logger.LogError(ex, "Error undoing package action '{PackageActionAlias}' for package {PackageName}", ipa.Alias(), packageName);
}
}
errors = e;

View File

@@ -2,8 +2,8 @@
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Packaging;
namespace Umbraco.Core.Packaging
@@ -13,10 +13,10 @@ namespace Umbraco.Core.Packaging
/// </summary>
public class PackageDefinitionXmlParser
{
private readonly ILogger _logger;
private readonly ILogger<PackageDefinitionXmlParser> _logger;
private readonly IUmbracoVersion _umbracoVersion;
public PackageDefinitionXmlParser(ILogger logger, IUmbracoVersion umbracoVersion)
public PackageDefinitionXmlParser(ILogger<PackageDefinitionXmlParser> logger, IUmbracoVersion umbracoVersion)
{
_logger = logger;
_umbracoVersion = umbracoVersion;
@@ -68,7 +68,7 @@ namespace Umbraco.Core.Packaging
}
catch (Exception e)
{
_logger.Warn<PackageDefinitionXmlParser>(e, "Could not add package actions to the package xml definition, the xml did not parse");
_logger.LogWarning(e, "Could not add package actions to the package xml definition, the xml did not parse");
}
var packageXml = new XElement("package",

View File

@@ -6,10 +6,10 @@ using System.IO.Compression;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Hosting;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Packaging;
using Umbraco.Core.Services;
@@ -29,7 +29,8 @@ namespace Umbraco.Core.Packaging
private readonly IMacroService _macroService;
private readonly ILocalizationService _languageService;
private readonly IEntityXmlSerializer _serializer;
private readonly ILogger _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly ILogger<PackagesRepository> _logger;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly string _packageRepositoryFileName;
private readonly string _mediaFolderPath;
@@ -60,7 +61,8 @@ namespace Umbraco.Core.Packaging
IDataTypeService dataTypeService, IFileService fileService, IMacroService macroService,
ILocalizationService languageService,
IHostingEnvironment hostingEnvironment,
IEntityXmlSerializer serializer, ILogger logger,
IEntityXmlSerializer serializer,
ILoggerFactory loggerFactory,
IUmbracoVersion umbracoVersion,
IOptions<GlobalSettings> globalSettings,
string packageRepositoryFileName,
@@ -74,7 +76,8 @@ namespace Umbraco.Core.Packaging
_macroService = macroService;
_languageService = languageService;
_serializer = serializer;
_logger = logger;
_loggerFactory = loggerFactory;
_logger = _loggerFactory.CreateLogger<PackagesRepository>();
_hostingEnvironment = hostingEnvironment;
_packageRepositoryFileName = packageRepositoryFileName;
@@ -82,7 +85,7 @@ namespace Umbraco.Core.Packaging
_packagesFolderPath = packagesFolderPath ?? Constants.SystemDirectories.Packages;
_mediaFolderPath = mediaFolderPath ?? globalSettings.Value.UmbracoMediaPath + "/created-packages";
_parser = new PackageDefinitionXmlParser(logger, umbracoVersion);
_parser = new PackageDefinitionXmlParser(_loggerFactory.CreateLogger<PackageDefinitionXmlParser>(), umbracoVersion);
_umbracoVersion = umbracoVersion;
}
@@ -214,7 +217,7 @@ namespace Umbraco.Core.Packaging
}
catch (Exception e)
{
_logger.Warn<PackagesRepository>(e, "Could not add package actions to the package, the xml did not parse");
_logger.LogWarning(e, "Could not add package actions to the package, the xml did not parse");
}
}

View File

@@ -1,4 +1,3 @@
using Umbraco.Core.Logging;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
@@ -6,6 +5,7 @@ using Umbraco.Core.Models.PublishedContent;
using System.Globalization;
using Umbraco.Core.Configuration.Models;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
namespace Umbraco.Web.Routing
{
@@ -17,11 +17,11 @@ namespace Umbraco.Web.Routing
/// </remarks>
public class ContentFinderByIdPath : IContentFinder
{
private readonly ILogger _logger;
private readonly ILogger<ContentFinderByIdPath> _logger;
private readonly IRequestAccessor _requestAccessor;
private readonly WebRoutingSettings _webRoutingSettings;
public ContentFinderByIdPath(IOptions<WebRoutingSettings> webRoutingSettings, ILogger logger, IRequestAccessor requestAccessor)
public ContentFinderByIdPath(IOptions<WebRoutingSettings> webRoutingSettings, ILogger<ContentFinderByIdPath> logger, IRequestAccessor requestAccessor)
{
_webRoutingSettings = webRoutingSettings.Value ?? throw new System.ArgumentNullException(nameof(webRoutingSettings));
_logger = logger ?? throw new System.ArgumentNullException(nameof(logger));
@@ -53,7 +53,7 @@ namespace Umbraco.Web.Routing
if (nodeId > 0)
{
_logger.Debug<ContentFinderByIdPath>("Id={NodeId}", nodeId);
_logger.LogDebug("Id={NodeId}", nodeId);
node = frequest.UmbracoContext.Content.GetById(nodeId);
if (node != null)
@@ -69,7 +69,7 @@ namespace Umbraco.Web.Routing
}
frequest.PublishedContent = node;
_logger.Debug<ContentFinderByIdPath>("Found node with id={PublishedContentId}", frequest.PublishedContent.Id);
_logger.LogDebug("Found node with id={PublishedContentId}", frequest.PublishedContent.Id);
}
else
{
@@ -79,7 +79,7 @@ namespace Umbraco.Web.Routing
}
if (nodeId == -1)
_logger.Debug<ContentFinderByIdPath>("Not a node id");
_logger.LogDebug("Not a node id");
return node != null;
}

View File

@@ -1,6 +1,6 @@
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Services;
namespace Umbraco.Web.Routing
@@ -15,10 +15,10 @@ namespace Umbraco.Web.Routing
public class ContentFinderByRedirectUrl : IContentFinder
{
private readonly IRedirectUrlService _redirectUrlService;
private readonly ILogger _logger;
private readonly ILogger<ContentFinderByRedirectUrl> _logger;
private readonly IPublishedUrlProvider _publishedUrlProvider;
public ContentFinderByRedirectUrl(IRedirectUrlService redirectUrlService, ILogger logger, IPublishedUrlProvider publishedUrlProvider)
public ContentFinderByRedirectUrl(IRedirectUrlService redirectUrlService, ILogger<ContentFinderByRedirectUrl> logger, IPublishedUrlProvider publishedUrlProvider)
{
_redirectUrlService = redirectUrlService;
_logger = logger;
@@ -41,7 +41,7 @@ namespace Umbraco.Web.Routing
if (redirectUrl == null)
{
_logger.Debug<ContentFinderByRedirectUrl>("No match for route: {Route}", route);
_logger.LogDebug("No match for route: {Route}", route);
return false;
}
@@ -49,14 +49,14 @@ namespace Umbraco.Web.Routing
var url = content == null ? "#" : content.Url(_publishedUrlProvider, redirectUrl.Culture);
if (url.StartsWith("#"))
{
_logger.Debug<ContentFinderByRedirectUrl>("Route {Route} matches content {ContentId} which has no url.", route, redirectUrl.ContentId);
_logger.LogDebug("Route {Route} matches content {ContentId} which has no url.", route, redirectUrl.ContentId);
return false;
}
// Appending any querystring from the incoming request to the redirect url.
url = string.IsNullOrEmpty(frequest.Uri.Query) ? url : url + frequest.Uri.Query;
_logger.Debug<ContentFinderByRedirectUrl>("Route {Route} matches content {ContentId} with url '{Url}', redirecting.", route, content.Id, url);
_logger.LogDebug("Route {Route} matches content {ContentId} with url '{Url}', redirecting.", route, content.Id, url);
frequest.SetRedirectPermanent(url);

View File

@@ -1,4 +1,4 @@
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Models.PublishedContent;
@@ -12,11 +12,11 @@ namespace Umbraco.Web.Routing
/// </remarks>
public class ContentFinderByUrl : IContentFinder
{
protected ILogger Logger { get; }
private readonly ILogger<ContentFinderByUrl> _logger;
public ContentFinderByUrl(ILogger logger)
public ContentFinderByUrl(ILogger<ContentFinderByUrl> logger)
{
Logger = logger;
_logger = logger;
}
/// <summary>
@@ -46,17 +46,17 @@ namespace Umbraco.Web.Routing
{
if (docreq == null) throw new System.ArgumentNullException(nameof(docreq));
Logger.Debug<ContentFinderByUrl>("Test route {Route}", route);
_logger.LogDebug("Test route {Route}", route);
var node = docreq.UmbracoContext.Content.GetByRoute(docreq.UmbracoContext.InPreviewMode, route, culture: docreq.Culture?.Name);
if (node != null)
{
docreq.PublishedContent = node;
Logger.Debug<ContentFinderByUrl>("Got content, id={NodeId}", node.Id);
_logger.LogDebug("Got content, id={NodeId}", node.Id);
}
else
{
Logger.Debug<ContentFinderByUrl>("No match.");
_logger.LogDebug("No match.");
}
return node;

View File

@@ -1,7 +1,7 @@
using System;
using System.Text;
using System.Linq;
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.Xml;
@@ -20,13 +20,13 @@ namespace Umbraco.Web.Routing
{
private readonly IPublishedValueFallback _publishedValueFallback;
private readonly IVariationContextAccessor _variationContextAccessor;
protected ILogger Logger { get; }
private readonly ILogger<ContentFinderByUrlAlias> _logger;
public ContentFinderByUrlAlias(ILogger logger, IPublishedValueFallback publishedValueFallback, IVariationContextAccessor variationContextAccessor)
public ContentFinderByUrlAlias(ILogger<ContentFinderByUrlAlias> logger, IPublishedValueFallback publishedValueFallback, IVariationContextAccessor variationContextAccessor)
{
_publishedValueFallback = publishedValueFallback;
_variationContextAccessor = variationContextAccessor;
Logger = logger;
_logger = logger;
}
/// <summary>
@@ -48,7 +48,7 @@ namespace Umbraco.Web.Routing
if (node != null)
{
frequest.PublishedContent = node;
Logger.Debug<ContentFinderByUrlAlias>("Path '{UriAbsolutePath}' is an alias for id={PublishedContentId}", frequest.Uri.AbsolutePath, frequest.PublishedContent.Id);
_logger.LogDebug("Path '{UriAbsolutePath}' is an alias for id={PublishedContentId}", frequest.Uri.AbsolutePath, frequest.PublishedContent.Id);
}
}

View File

@@ -1,10 +1,10 @@
using Umbraco.Core.Logging;
using Umbraco.Core;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.Services;
using Umbraco.Core.Configuration.Models;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
namespace Umbraco.Web.Routing
{
@@ -18,14 +18,16 @@ namespace Umbraco.Web.Routing
/// </remarks>
public class ContentFinderByUrlAndTemplate : ContentFinderByUrl
{
private readonly ILogger<ContentFinderByUrlAndTemplate> _logger;
private readonly IFileService _fileService;
private readonly IContentTypeService _contentTypeService;
private readonly WebRoutingSettings _webRoutingSettings;
public ContentFinderByUrlAndTemplate(ILogger logger, IFileService fileService, IContentTypeService contentTypeService, IOptions<WebRoutingSettings> webRoutingSettings)
public ContentFinderByUrlAndTemplate(ILogger<ContentFinderByUrlAndTemplate> logger, IFileService fileService, IContentTypeService contentTypeService, IOptions<WebRoutingSettings> webRoutingSettings)
: base(logger)
{
_logger = logger;
_fileService = fileService;
_contentTypeService = contentTypeService;
_webRoutingSettings = webRoutingSettings.Value;
@@ -48,7 +50,7 @@ namespace Umbraco.Web.Routing
// no template if "/"
if (path == "/")
{
Logger.Debug<ContentFinderByUrlAndTemplate>("No template in path '/'");
_logger.LogDebug("No template in path '/'");
return false;
}
@@ -61,11 +63,11 @@ namespace Umbraco.Web.Routing
if (template == null)
{
Logger.Debug<ContentFinderByUrlAndTemplate>("Not a valid template: '{TemplateAlias}'", templateAlias);
_logger.LogDebug("Not a valid template: '{TemplateAlias}'", templateAlias);
return false;
}
Logger.Debug<ContentFinderByUrlAndTemplate>("Valid template: '{TemplateAlias}'", templateAlias);
_logger.LogDebug("Valid template: '{TemplateAlias}'", templateAlias);
// look for node corresponding to the rest of the route
var route = frequest.HasDomain ? (frequest.Domain.ContentId + path) : path;
@@ -73,14 +75,14 @@ namespace Umbraco.Web.Routing
if (node == null)
{
Logger.Debug<ContentFinderByUrlAndTemplate>("Not a valid route to node: '{Route}'", route);
_logger.LogDebug("Not a valid route to node: '{Route}'", route);
return false;
}
// IsAllowedTemplate deals both with DisableAlternativeTemplates and ValidateAlternativeTemplates settings
if (!node.IsAllowedTemplate(_contentTypeService, _webRoutingSettings, template.Id))
{
Logger.Warn<ContentFinderByUrlAndTemplate>("Alternative template '{TemplateAlias}' is not allowed on node {NodeId}.", template.Alias, node.Id);
_logger.LogWarning("Alternative template '{TemplateAlias}' is not allowed on node {NodeId}.", template.Alias, node.Id);
frequest.PublishedContent = null; // clear
return false;
}

View File

@@ -1,10 +1,10 @@
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.PublishedContent;
namespace Umbraco.Web.Routing
@@ -15,13 +15,13 @@ namespace Umbraco.Web.Routing
public class DefaultUrlProvider : IUrlProvider
{
private readonly RequestHandlerSettings _requestSettings;
private readonly ILogger _logger;
private readonly ILogger<DefaultUrlProvider> _logger;
private readonly GlobalSettings _globalSettings;
private readonly ISiteDomainHelper _siteDomainHelper;
private readonly IUmbracoContextAccessor _umbracoContextAccessor;
private readonly UriUtility _uriUtility;
public DefaultUrlProvider(IOptions<RequestHandlerSettings> requestSettings, ILogger logger, IOptions<GlobalSettings> globalSettings, ISiteDomainHelper siteDomainHelper, IUmbracoContextAccessor umbracoContextAccessor, UriUtility uriUtility)
public DefaultUrlProvider(IOptions<RequestHandlerSettings> requestSettings, ILogger<DefaultUrlProvider> logger, IOptions<GlobalSettings> globalSettings, ISiteDomainHelper siteDomainHelper, IUmbracoContextAccessor umbracoContextAccessor, UriUtility uriUtility)
{
_requestSettings = requestSettings.Value;
_logger = logger;
@@ -49,7 +49,7 @@ namespace Umbraco.Web.Routing
{
if (string.IsNullOrWhiteSpace(route))
{
_logger.Debug<DefaultUrlProvider>("Couldn't find any page with nodeId={NodeId}. This is most likely caused by the page not being published.", id);
_logger.LogDebug("Couldn't find any page with nodeId={NodeId}. This is most likely caused by the page not being published.", id);
return null;
}

View File

@@ -3,6 +3,7 @@ using System.Linq;
using System.Threading;
using System.Globalization;
using System.IO;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Logging;
@@ -25,7 +26,7 @@ namespace Umbraco.Web.Routing
private readonly IContentLastChanceFinder _contentLastChanceFinder;
private readonly IProfilingLogger _profilingLogger;
private readonly IVariationContextAccessor _variationContextAccessor;
private readonly ILogger _logger;
private readonly ILogger<PublishedRouter> _logger;
private readonly IPublishedUrlProvider _publishedUrlProvider;
private readonly IRequestAccessor _requestAccessor;
private readonly IPublishedValueFallback _publishedValueFallback;
@@ -43,6 +44,7 @@ namespace Umbraco.Web.Routing
IContentLastChanceFinder contentLastChanceFinder,
IVariationContextAccessor variationContextAccessor,
IProfilingLogger proflog,
ILogger<PublishedRouter> logger,
IPublishedUrlProvider publishedUrlProvider,
IRequestAccessor requestAccessor,
IPublishedValueFallback publishedValueFallback,
@@ -56,7 +58,7 @@ namespace Umbraco.Web.Routing
_contentLastChanceFinder = contentLastChanceFinder ?? throw new ArgumentNullException(nameof(contentLastChanceFinder));
_profilingLogger = proflog ?? throw new ArgumentNullException(nameof(proflog));
_variationContextAccessor = variationContextAccessor ?? throw new ArgumentNullException(nameof(variationContextAccessor));
_logger = proflog;
_logger = logger;
_publishedUrlProvider = publishedUrlProvider;
_requestAccessor = requestAccessor;
_publishedValueFallback = publishedValueFallback;
@@ -249,7 +251,7 @@ namespace Umbraco.Web.Routing
// note - we are not handling schemes nor ports here.
_logger.Debug<PublishedRouter>("{TracePrefix}Uri={RequestUri}", tracePrefix, request.Uri);
_logger.LogDebug("{TracePrefix}Uri={RequestUri}", tracePrefix, request.Uri);
var domainsCache = request.UmbracoContext.PublishedSnapshot.Domains;
var domains = domainsCache.GetAll(includeWildcards: false).ToList();
@@ -286,7 +288,7 @@ namespace Umbraco.Web.Routing
if (domainAndUri != null)
{
// matching an existing domain
_logger.Debug<PublishedRouter>("{TracePrefix}Matches domain={Domain}, rootId={RootContentId}, culture={Culture}", tracePrefix, domainAndUri.Name, domainAndUri.ContentId, domainAndUri.Culture);
_logger.LogDebug("{TracePrefix}Matches domain={Domain}, rootId={RootContentId}, culture={Culture}", tracePrefix, domainAndUri.Name, domainAndUri.ContentId, domainAndUri.Culture);
request.Domain = domainAndUri;
request.Culture = domainAndUri.Culture;
@@ -301,12 +303,12 @@ namespace Umbraco.Web.Routing
else
{
// not matching any existing domain
_logger.Debug<PublishedRouter>("{TracePrefix}Matches no domain", tracePrefix);
_logger.LogDebug("{TracePrefix}Matches no domain", tracePrefix);
request.Culture = defaultCulture == null ? CultureInfo.CurrentUICulture : new CultureInfo(defaultCulture);
}
_logger.Debug<PublishedRouter>("{TracePrefix}Culture={CultureName}", tracePrefix, request.Culture.Name);
_logger.LogDebug("{TracePrefix}Culture={CultureName}", tracePrefix, request.Culture.Name);
return request.Domain != null;
}
@@ -322,7 +324,7 @@ namespace Umbraco.Web.Routing
return;
var nodePath = request.PublishedContent.Path;
_logger.Debug<PublishedRouter>("{TracePrefix}Path={NodePath}", tracePrefix, nodePath);
_logger.LogDebug("{TracePrefix}Path={NodePath}", tracePrefix, nodePath);
var rootNodeId = request.HasDomain ? request.Domain.ContentId : (int?)null;
var domain = DomainUtilities.FindWildcardDomainInPath(request.UmbracoContext.PublishedSnapshot.Domains.GetAll(true), nodePath, rootNodeId);
@@ -330,11 +332,11 @@ namespace Umbraco.Web.Routing
if (domain != null)
{
request.Culture = domain.Culture;
_logger.Debug<PublishedRouter>("{TracePrefix}Got domain on node {DomainContentId}, set culture to {CultureName}", tracePrefix, domain.ContentId, request.Culture.Name);
_logger.LogDebug("{TracePrefix}Got domain on node {DomainContentId}, set culture to {CultureName}", tracePrefix, domain.ContentId, request.Culture.Name);
}
else
{
_logger.Debug<PublishedRouter>("{TracePrefix}No match.", tracePrefix);
_logger.LogDebug("{TracePrefix}No match.", tracePrefix);
}
}
@@ -376,7 +378,7 @@ namespace Umbraco.Web.Routing
/// <returns>A value indicating whether a document and template were found.</returns>
private void FindPublishedContentAndTemplate(IPublishedRequest request)
{
_logger.Debug<PublishedRouter>("FindPublishedContentAndTemplate: Path={UriAbsolutePath}", request.Uri.AbsolutePath);
_logger.LogDebug("FindPublishedContentAndTemplate: Path={UriAbsolutePath}", request.Uri.AbsolutePath);
// run the document finders
FindPublishedContent(request);
@@ -419,7 +421,7 @@ namespace Umbraco.Web.Routing
//iterate but return on first one that finds it
var found = _contentFinders.Any(finder =>
{
_logger.Debug<PublishedRouter>("Finder {ContentFinderType}", finder.GetType().FullName);
_logger.LogDebug("Finder {ContentFinderType}", finder.GetType().FullName);
return finder.TryFindContent(request);
});
}
@@ -443,22 +445,22 @@ namespace Umbraco.Web.Routing
const int maxLoop = 8;
do
{
_logger.Debug<PublishedRouter>("HandlePublishedContent: Loop {LoopCounter}", i);
_logger.LogDebug("HandlePublishedContent: Loop {LoopCounter}", i);
// handle not found
if (request.HasPublishedContent == false)
{
request.Is404 = true;
_logger.Debug<PublishedRouter>("HandlePublishedContent: No document, try last chance lookup");
_logger.LogDebug("HandlePublishedContent: No document, try last chance lookup");
// if it fails then give up, there isn't much more that we can do
if (_contentLastChanceFinder.TryFindContent(request) == false)
{
_logger.Debug<PublishedRouter>("HandlePublishedContent: Failed to find a document, give up");
_logger.LogDebug("HandlePublishedContent: Failed to find a document, give up");
break;
}
_logger.Debug<PublishedRouter>("HandlePublishedContent: Found a document");
_logger.LogDebug("HandlePublishedContent: Found a document");
}
// follow internal redirects as long as it's not running out of control ie infinite loop of some sort
@@ -480,11 +482,11 @@ namespace Umbraco.Web.Routing
if (i == maxLoop || j == maxLoop)
{
_logger.Debug<PublishedRouter>("HandlePublishedContent: Looks like we are running into an infinite loop, abort");
_logger.LogDebug("HandlePublishedContent: Looks like we are running into an infinite loop, abort");
request.PublishedContent = null;
}
_logger.Debug<PublishedRouter>("HandlePublishedContent: End");
_logger.LogDebug("HandlePublishedContent: End");
}
/// <summary>
@@ -529,25 +531,25 @@ namespace Umbraco.Web.Routing
if (valid == false)
{
// bad redirect - log and display the current page (legacy behavior)
_logger.Debug<PublishedRouter>("FollowInternalRedirects: Failed to redirect to id={InternalRedirectId}: value is not an int nor a GuidUdi.",
_logger.LogDebug("FollowInternalRedirects: Failed to redirect to id={InternalRedirectId}: value is not an int nor a GuidUdi.",
request.PublishedContent.GetProperty(Constants.Conventions.Content.InternalRedirectId).GetSourceValue());
}
if (internalRedirectNode == null)
{
_logger.Debug<PublishedRouter>("FollowInternalRedirects: Failed to redirect to id={InternalRedirectId}: no such published document.",
_logger.LogDebug("FollowInternalRedirects: Failed to redirect to id={InternalRedirectId}: no such published document.",
request.PublishedContent.GetProperty(Constants.Conventions.Content.InternalRedirectId).GetSourceValue());
}
else if (internalRedirectId == request.PublishedContent.Id)
{
// redirect to self
_logger.Debug<PublishedRouter>("FollowInternalRedirects: Redirecting to self, ignore");
_logger.LogDebug("FollowInternalRedirects: Redirecting to self, ignore");
}
else
{
request.SetInternalRedirectPublishedContent(internalRedirectNode); // don't use .PublishedContent here
redirect = true;
_logger.Debug<PublishedRouter>("FollowInternalRedirects: Redirecting to id={InternalRedirectId}", internalRedirectId);
_logger.LogDebug("FollowInternalRedirects: Redirecting to id={InternalRedirectId}", internalRedirectId);
}
return redirect;
@@ -568,35 +570,35 @@ namespace Umbraco.Web.Routing
if (publicAccessAttempt)
{
_logger.Debug<PublishedRouter>("EnsurePublishedContentAccess: Page is protected, check for access");
_logger.LogDebug("EnsurePublishedContentAccess: Page is protected, check for access");
var status = _publicAccessChecker.HasMemberAccessToContent(request.PublishedContent.Id);
switch (status)
{
case PublicAccessStatus.NotLoggedIn:
_logger.Debug<PublishedRouter>("EnsurePublishedContentAccess: Not logged in, redirect to login page");
_logger.LogDebug("EnsurePublishedContentAccess: Not logged in, redirect to login page");
SetPublishedContentAsOtherPage(request, publicAccessAttempt.Result.LoginNodeId);
break;
case PublicAccessStatus.AccessDenied:
_logger.Debug<PublishedRouter>("EnsurePublishedContentAccess: Current member has not access, redirect to error page");
_logger.LogDebug("EnsurePublishedContentAccess: Current member has not access, redirect to error page");
SetPublishedContentAsOtherPage(request, publicAccessAttempt.Result.NoAccessNodeId);
break;
case PublicAccessStatus.LockedOut:
_logger.Debug<PublishedRouter>("Current member is locked out, redirect to error page");
_logger.LogDebug("Current member is locked out, redirect to error page");
SetPublishedContentAsOtherPage(request, publicAccessAttempt.Result.NoAccessNodeId);
break;
case PublicAccessStatus.NotApproved:
_logger.Debug<PublishedRouter>("Current member is unapproved, redirect to error page");
_logger.LogDebug("Current member is unapproved, redirect to error page");
SetPublishedContentAsOtherPage(request, publicAccessAttempt.Result.NoAccessNodeId);
break;
case PublicAccessStatus.AccessAccepted:
_logger.Debug<PublishedRouter>("Current member has access");
_logger.LogDebug("Current member has access");
break;
}
}
else
{
_logger.Debug<PublishedRouter>("EnsurePublishedContentAccess: Page is not protected");
_logger.LogDebug("EnsurePublishedContentAccess: Page is not protected");
}
}
@@ -639,7 +641,7 @@ namespace Umbraco.Web.Routing
if (request.HasTemplate)
{
_logger.Debug<IPublishedRequest>("FindTemplate: Has a template already, and no alternate template.");
_logger.LogDebug("FindTemplate: Has a template already, and no alternate template.");
return;
}
@@ -661,8 +663,8 @@ namespace Umbraco.Web.Routing
// ignore if the alias does not match - just trace
if (request.HasTemplate)
_logger.Debug<PublishedRouter>("FindTemplate: Has a template already, but also an alternative template.");
_logger.Debug<PublishedRouter>("FindTemplate: Look for alternative template alias={AltTemplate}", altTemplate);
_logger.LogDebug("FindTemplate: Has a template already, but also an alternative template.");
_logger.LogDebug("FindTemplate: Look for alternative template alias={AltTemplate}", altTemplate);
// IsAllowedTemplate deals both with DisableAlternativeTemplates and ValidateAlternativeTemplates settings
if (request.PublishedContent.IsAllowedTemplate(
@@ -678,16 +680,16 @@ namespace Umbraco.Web.Routing
if (template != null)
{
request.TemplateModel = template;
_logger.Debug<PublishedRouter>("FindTemplate: Got alternative template id={TemplateId} alias={TemplateAlias}", template.Id, template.Alias);
_logger.LogDebug("FindTemplate: Got alternative template id={TemplateId} alias={TemplateAlias}", template.Id, template.Alias);
}
else
{
_logger.Debug<PublishedRouter>("FindTemplate: The alternative template with alias={AltTemplate} does not exist, ignoring.", altTemplate);
_logger.LogDebug("FindTemplate: The alternative template with alias={AltTemplate} does not exist, ignoring.", altTemplate);
}
}
else
{
_logger.Warn<PublishedRouter>("FindTemplate: Alternative template {TemplateAlias} is not allowed on node {NodeId}, ignoring.", altTemplate, request.PublishedContent.Id);
_logger.LogWarning("FindTemplate: Alternative template {TemplateAlias} is not allowed on node {NodeId}, ignoring.", altTemplate, request.PublishedContent.Id);
// no allowed, back to default
var templateId = request.PublishedContent.TemplateId;
@@ -697,7 +699,7 @@ namespace Umbraco.Web.Routing
if (request.HasTemplate == false)
{
_logger.Debug<PublishedRouter>("FindTemplate: No template was found.");
_logger.LogDebug("FindTemplate: No template was found.");
// initial idea was: if we're not already 404 and UmbracoSettings.HandleMissingTemplateAs404 is true
// then reset _pcr.Document to null to force a 404.
@@ -710,7 +712,7 @@ namespace Umbraco.Web.Routing
}
else
{
_logger.Debug<PublishedRouter>("FindTemplate: Running with template id={TemplateId} alias={TemplateAlias}", request.TemplateModel.Id, request.TemplateModel.Alias);
_logger.LogDebug("FindTemplate: Running with template id={TemplateId} alias={TemplateAlias}", request.TemplateModel.Id, request.TemplateModel.Alias);
}
}
@@ -718,11 +720,11 @@ namespace Umbraco.Web.Routing
{
if (templateId.HasValue == false || templateId.Value == default)
{
_logger.Debug<PublishedRouter>("GetTemplateModel: No template.");
_logger.LogDebug("GetTemplateModel: No template.");
return null;
}
_logger.Debug<PublishedRouter>("GetTemplateModel: Get template id={TemplateId}", templateId);
_logger.LogDebug("GetTemplateModel: Get template id={TemplateId}", templateId);
if (templateId == null)
throw new InvalidOperationException("The template is not set, the page cannot render.");
@@ -730,7 +732,7 @@ namespace Umbraco.Web.Routing
var template = _fileService.GetTemplate(templateId.Value);
if (template == null)
throw new InvalidOperationException("The template with Id " + templateId + " does not exist, the page cannot render.");
_logger.Debug<PublishedRouter>("GetTemplateModel: Got template id={TemplateId} alias={TemplateAlias}", template.Id, template.Alias);
_logger.LogDebug("GetTemplateModel: Got template id={TemplateId} alias={TemplateAlias}", template.Id, template.Alias);
return template;
}

View File

@@ -1,10 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Services;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.PublishedContent;
namespace Umbraco.Web.Routing
@@ -25,7 +25,7 @@ namespace Umbraco.Web.Routing
ILocalizedTextService textService,
IContentService contentService,
IVariationContextAccessor variationContextAccessor,
ILogger logger,
ILogger<IContent> logger,
UriUtility uriUtility,
IPublishedUrlProvider publishedUrlProvider)
{
@@ -123,7 +123,7 @@ namespace Umbraco.Web.Routing
}
catch (Exception ex)
{
logger.Error<UrlProvider>(ex, "GetUrl exception.");
logger.LogError(ex, "GetUrl exception.");
url = "#ex";
}

View File

@@ -3,8 +3,8 @@ using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Threading;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Hosting;
using Umbraco.Core.Logging;
namespace Umbraco.Core.Runtime
{
@@ -20,7 +20,7 @@ namespace Umbraco.Core.Runtime
{
#region Vars
private readonly ILogger _logger;
private readonly ILogger<MainDom> _logger;
private IApplicationShutdownRegistry _hostingEnvironment;
private readonly IMainDomLock _mainDomLock;
@@ -42,7 +42,7 @@ namespace Umbraco.Core.Runtime
#region Ctor
// initializes a new instance of MainDom
public MainDom(ILogger logger, IMainDomLock systemLock)
public MainDom(ILogger<MainDom> logger, IMainDomLock systemLock)
{
_logger = logger;
_mainDomLock = systemLock;
@@ -86,7 +86,7 @@ namespace Umbraco.Core.Runtime
if (_signaled) return false;
if (_isMainDom == false)
{
_logger.Warn<MainDom>("Register called when MainDom has not been acquired");
_logger.LogWarning("Register called when MainDom has not been acquired");
return false;
}
@@ -105,14 +105,14 @@ namespace Umbraco.Core.Runtime
lock (_locko)
{
_logger.Debug<MainDom>("Signaled ({Signaled}) ({SignalSource})", _signaled ? "again" : "first", source);
_logger.LogDebug("Signaled ({Signaled}) ({SignalSource})", _signaled ? "again" : "first", source);
if (_signaled) return;
if (_isMainDom == false) return; // probably not needed
_signaled = true;
try
{
_logger.Info<MainDom>("Stopping ({SignalSource})", source);
_logger.LogInformation("Stopping ({SignalSource})", source);
foreach (var callback in _callbacks.OrderBy(x => x.Key).Select(x => x.Value))
{
try
@@ -121,19 +121,19 @@ namespace Umbraco.Core.Runtime
}
catch (Exception e)
{
_logger.Error<MainDom>(e, "Error while running callback");
_logger.LogError(e, "Error while running callback");
continue;
}
}
_logger.Debug<MainDom>("Stopped ({SignalSource})", source);
_logger.LogDebug("Stopped ({SignalSource})", source);
}
finally
{
// in any case...
_isMainDom = false;
_mainDomLock.Dispose();
_logger.Info<MainDom>("Released ({SignalSource})", source);
_logger.LogInformation("Released ({SignalSource})", source);
}
}
@@ -146,18 +146,18 @@ namespace Umbraco.Core.Runtime
// the handler is not installed so that would be the hosting environment
if (_signaled)
{
_logger.Info<MainDom>("Cannot acquire (signaled).");
_logger.LogInformation("Cannot acquire (signaled).");
return false;
}
_logger.Info<MainDom>("Acquiring.");
_logger.LogInformation("Acquiring.");
// Get the lock
var acquired = _mainDomLock.AcquireLockAsync(LockTimeoutMilliseconds).GetAwaiter().GetResult();
if (!acquired)
{
_logger.Info<MainDom>("Cannot acquire (timeout).");
_logger.LogInformation("Cannot acquire (timeout).");
// In previous versions we'd let a TimeoutException be thrown
// and the appdomain would not start. We have the opportunity to allow it to
@@ -177,10 +177,10 @@ namespace Umbraco.Core.Runtime
catch (OperationCanceledException ex)
{
// the waiting task could be canceled if this appdomain is naturally shutting down, we'll just swallow this exception
_logger.Warn<MainDom>(ex, ex.Message);
_logger.LogWarning(ex, ex.Message);
}
_logger.Info<MainDom>("Acquired.");
_logger.LogInformation("Acquired.");
return true;
}

View File

@@ -7,6 +7,7 @@ using Umbraco.Core;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Logging;
using Umbraco.Core.Sync;
using Microsoft.Extensions.Logging;
namespace Umbraco.Web.Scheduling
{
@@ -15,18 +16,20 @@ namespace Umbraco.Web.Scheduling
private readonly IRequestAccessor _requestAccessor;
private readonly IMainDom _mainDom;
private readonly KeepAliveSettings _keepAliveSettings;
private readonly IProfilingLogger _logger;
private readonly ILogger<KeepAlive> _logger;
private readonly IProfilingLogger _profilingLogger;
private readonly IServerRegistrar _serverRegistrar;
private static HttpClient _httpClient;
public KeepAlive(IBackgroundTaskRunner<RecurringTaskBase> runner, int delayMilliseconds, int periodMilliseconds,
IRequestAccessor requestAccessor, IMainDom mainDom, IOptions<KeepAliveSettings> keepAliveSettings, IProfilingLogger logger, IServerRegistrar serverRegistrar)
IRequestAccessor requestAccessor, IMainDom mainDom, IOptions<KeepAliveSettings> keepAliveSettings, ILogger<KeepAlive> logger, IProfilingLogger profilingLogger, IServerRegistrar serverRegistrar)
: base(runner, delayMilliseconds, periodMilliseconds)
{
_requestAccessor = requestAccessor;
_mainDom = mainDom;
_keepAliveSettings = keepAliveSettings.Value;
_logger = logger;
_profilingLogger = profilingLogger;
_serverRegistrar = serverRegistrar;
if (_httpClient == null)
{
@@ -40,21 +43,21 @@ namespace Umbraco.Web.Scheduling
switch (_serverRegistrar.GetCurrentServerRole())
{
case ServerRole.Replica:
_logger.Debug<KeepAlive>("Does not run on replica servers.");
_logger.LogDebug("Does not run on replica servers.");
return true; // role may change!
case ServerRole.Unknown:
_logger.Debug<KeepAlive>("Does not run on servers with unknown role.");
_logger.LogDebug("Does not run on servers with unknown role.");
return true; // role may change!
}
// ensure we do not run if not main domain, but do NOT lock it
if (_mainDom.IsMainDom == false)
{
_logger.Debug<KeepAlive>("Does not run if not MainDom.");
_logger.LogDebug("Does not run if not MainDom.");
return false; // do NOT repeat, going down
}
using (_logger.DebugDuration<KeepAlive>("Keep alive executing", "Keep alive complete"))
using (_profilingLogger.DebugDuration<KeepAlive>("Keep alive executing", "Keep alive complete"))
{
var keepAlivePingUrl = _keepAliveSettings.KeepAlivePingUrl;
try
@@ -64,7 +67,7 @@ namespace Umbraco.Web.Scheduling
var umbracoAppUrl = _requestAccessor.GetApplicationUrl().ToString();
if (umbracoAppUrl.IsNullOrWhiteSpace())
{
_logger.Warn<KeepAlive>("No umbracoApplicationUrl for service (yet), skip.");
_logger.LogWarning("No umbracoApplicationUrl for service (yet), skip.");
return true; // repeat
}
@@ -76,7 +79,7 @@ namespace Umbraco.Web.Scheduling
}
catch (Exception ex)
{
_logger.Error<KeepAlive>(ex, "Keep alive failed (at '{keepAlivePingUrl}').", keepAlivePingUrl);
_logger.LogError(ex, "Keep alive failed (at '{keepAlivePingUrl}').", keepAlivePingUrl);
}
}

View File

@@ -4,6 +4,7 @@ using System.IO;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging;
namespace Umbraco.Web.Scheduling
{
@@ -15,11 +16,12 @@ namespace Umbraco.Web.Scheduling
private readonly DirectoryInfo[] _tempFolders;
private readonly TimeSpan _age;
private readonly IMainDom _mainDom;
private readonly IProfilingLogger _logger;
private readonly IProfilingLogger _profilingLogger;
private readonly ILogger<TempFileCleanup> _logger;
public TempFileCleanup(IBackgroundTaskRunner<RecurringTaskBase> runner, int delayMilliseconds, int periodMilliseconds,
IEnumerable<DirectoryInfo> tempFolders, TimeSpan age,
IMainDom mainDom, IProfilingLogger logger)
IMainDom mainDom, IProfilingLogger profilingLogger, ILogger<TempFileCleanup> logger)
: base(runner, delayMilliseconds, periodMilliseconds)
{
//SystemDirectories.TempFileUploads
@@ -27,6 +29,7 @@ namespace Umbraco.Web.Scheduling
_tempFolders = tempFolders.ToArray();
_age = age;
_mainDom = mainDom;
_profilingLogger = profilingLogger;
_logger = logger;
}
@@ -35,7 +38,7 @@ namespace Umbraco.Web.Scheduling
// ensure we do not run if not main domain
if (_mainDom.IsMainDom == false)
{
_logger.Debug<TempFileCleanup>("Does not run if not MainDom.");
_logger.LogDebug("Does not run if not MainDom.");
return false; // do NOT repeat, going down
}
@@ -50,7 +53,7 @@ namespace Umbraco.Web.Scheduling
dir.Refresh(); //in case it's changed during runtime
if (!dir.Exists)
{
_logger.Debug<TempFileCleanup>("The cleanup folder doesn't exist {Folder}", dir.FullName);
_logger.LogDebug("The cleanup folder doesn't exist {Folder}", dir.FullName);
return;
}
@@ -66,7 +69,7 @@ namespace Umbraco.Web.Scheduling
}
catch (Exception ex)
{
_logger.Error<TempFileCleanup>(ex, "Could not delete temp file {FileName}", file.FullName);
_logger.LogError(ex, "Could not delete temp file {FileName}", file.FullName);
}
}
}

View File

@@ -1,5 +1,6 @@
using System.Text.RegularExpressions;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
@@ -9,17 +10,19 @@ namespace Umbraco.Web.Templates
public sealed class HtmlUrlParser
{
private readonly ContentSettings _contentSettings;
private readonly ILogger<HtmlUrlParser> _logger;
private readonly IIOHelper _ioHelper;
private readonly IProfilingLogger _logger;
private readonly IProfilingLogger _profilingLogger;
private static readonly Regex ResolveUrlPattern = new Regex("(=[\"\']?)(\\W?\\~(?:.(?![\"\']?\\s+(?:\\S+)=|[>\"\']))+.)[\"\']?",
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
public HtmlUrlParser(IOptions<ContentSettings> contentSettings, IProfilingLogger logger, IIOHelper ioHelper)
public HtmlUrlParser(IOptions<ContentSettings> contentSettings, ILogger<HtmlUrlParser> logger ,IProfilingLogger profilingLogger, IIOHelper ioHelper)
{
_contentSettings = contentSettings.Value;
_ioHelper = ioHelper;
_logger = logger;
_ioHelper = ioHelper;
_profilingLogger = profilingLogger;
}
/// <summary>
@@ -35,11 +38,11 @@ namespace Umbraco.Web.Templates
{
if (_contentSettings.ResolveUrlsFromTextString == false) return text;
using (var timer = _logger.DebugDuration(typeof(IOHelper), "ResolveUrlsFromTextString starting", "ResolveUrlsFromTextString complete"))
using (var timer = _profilingLogger.DebugDuration(typeof(IOHelper), "ResolveUrlsFromTextString starting", "ResolveUrlsFromTextString complete"))
{
// find all relative urls (ie. urls that contain ~)
var tags = ResolveUrlPattern.Matches(text);
_logger.Debug(typeof(IOHelper), "After regex: {Duration} matched: {TagsCount}", timer.Stopwatch.ElapsedMilliseconds, tags.Count);
_logger.LogDebug("After regex: {Duration} matched: {TagsCount}", timer.Stopwatch.ElapsedMilliseconds, tags.Count);
foreach (Match tag in tags)
{
var url = "";

View File

@@ -15,6 +15,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="3.1.8" />
<PackageReference Include="Microsoft.Extensions.Options" Version="3.1.8" />
<PackageReference Include="System.ComponentModel.Annotations" Version="4.7.0" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="4.7.0" />
@@ -38,5 +39,8 @@
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>Umbraco.Tests.Integration</_Parameter1>
</AssemblyAttribute>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>DynamicProxyGenAssembly2</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
</Project>

View File

@@ -1,6 +1,7 @@
using System;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Composing;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.Models;
@@ -159,7 +160,7 @@ namespace Umbraco.Core
}
catch (ArgumentException)
{
Current.Logger.Debug(typeof(UriExtensions), "Failed to determine if request was client side (invalid chars in path \"{Path}\"?)", url.LocalPath);
Current.Logger.LogDebug("Failed to determine if request was client side (invalid chars in path \"{Path}\"?)", url.LocalPath);
return false;
}
}

View File

@@ -1,5 +1,6 @@
using System;
using System.Linq;
using Microsoft.Extensions.Logging;
using Examine;
using Examine.LuceneEngine.Providers;
using Lucene.Net.Analysis;
@@ -8,7 +9,6 @@ using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Umbraco.Core;
using Version = Lucene.Net.Util.Version;
using Umbraco.Core.Logging;
using System.Threading;
namespace Umbraco.Examine
@@ -29,7 +29,7 @@ namespace Umbraco.Examine
/// <remarks>
/// Configures and unlocks all Lucene based indexes registered with the <see cref="IExamineManager"/>.
/// </remarks>
internal static void ConfigureIndexes(this IExamineManager examineManager, IMainDom mainDom, ILogger logger)
internal static void ConfigureIndexes(this IExamineManager examineManager, IMainDom mainDom, ILogger<IExamineManager> logger)
{
LazyInitializer.EnsureInitialized(
ref _configuredInit,
@@ -71,7 +71,7 @@ namespace Umbraco.Examine
/// <remarks>
/// This is not thread safe, use with care
/// </remarks>
private static void ConfigureLuceneIndexes(this IExamineManager examineManager, ILogger logger, bool disableExamineIndexing)
private static void ConfigureLuceneIndexes(this IExamineManager examineManager, ILogger<IExamineManager> logger, bool disableExamineIndexing)
{
foreach (var luceneIndexer in examineManager.Indexes.OfType<LuceneIndex>())
{
@@ -87,7 +87,7 @@ namespace Umbraco.Examine
var dir = luceneIndexer.GetLuceneDirectory();
if (IndexWriter.IsLocked(dir))
{
logger.Info(typeof(ExamineExtensions), "Forcing index {IndexerName} to be unlocked since it was left in a locked state", luceneIndexer.Name);
logger.LogDebug("Forcing index {IndexerName} to be unlocked since it was left in a locked state", luceneIndexer.Name);
IndexWriter.Unlock(dir);
}
}

View File

@@ -1,8 +1,8 @@
using Examine;
using Microsoft.Extensions.Logging;
using Examine;
using Examine.LuceneEngine.Directories;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
namespace Umbraco.Examine
{
@@ -12,14 +12,14 @@ namespace Umbraco.Examine
private readonly IndexRebuilder _indexRebuilder;
private readonly IExamineManager _examineManager;
private readonly IMainDom _mainDom;
private readonly ILogger _logger;
private readonly ILoggerFactory _loggerFactory;
public ExamineLuceneComponent(IndexRebuilder indexRebuilder, IExamineManager examineManager, IMainDom mainDom, ILogger logger)
public ExamineLuceneComponent(IndexRebuilder indexRebuilder, IExamineManager examineManager, IMainDom mainDom, ILoggerFactory loggerFactory)
{
_indexRebuilder = indexRebuilder;
_examineManager = examineManager;
_mainDom = mainDom;
_logger = logger;
_loggerFactory = loggerFactory;
}
public void Initialize()
@@ -41,7 +41,7 @@ namespace Umbraco.Examine
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void IndexRebuilder_RebuildingIndexes(object sender, IndexRebuildingEventArgs e) => _examineManager.ConfigureIndexes(_mainDom, _logger);
private void IndexRebuilder_RebuildingIndexes(object sender, IndexRebuildingEventArgs e) => _examineManager.ConfigureIndexes(_mainDom, _loggerFactory.CreateLogger<IExamineManager>());
public void Terminate()
{

View File

@@ -1,19 +1,19 @@
using Examine;
using Microsoft.Extensions.Logging;
using Examine;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
namespace Umbraco.Examine
{
public class ExamineLuceneFinalComponent : IComponent
{
private readonly IProfilingLogger _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly IExamineManager _examineManager;
private readonly IMainDom _mainDom;
public ExamineLuceneFinalComponent(IProfilingLogger logger, IExamineManager examineManager, IMainDom mainDom)
public ExamineLuceneFinalComponent(ILoggerFactory loggerFactory, IExamineManager examineManager, IMainDom mainDom)
{
_logger = logger;
_loggerFactory = loggerFactory;
_examineManager = examineManager;
_mainDom = mainDom;
}
@@ -23,7 +23,7 @@ namespace Umbraco.Examine
if (!_mainDom.IsMainDom) return;
// Ensures all lucene based indexes are unlocked and ready to go
_examineManager.ConfigureIndexes(_mainDom, _logger);
_examineManager.ConfigureIndexes(_mainDom, _loggerFactory.CreateLogger<IExamineManager>());
}
public void Terminate()

View File

@@ -1,7 +1,7 @@
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Examine.LuceneEngine.Providers;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Lucene.Net.Store;
using Umbraco.Core.IO;
using System.Linq;
@@ -14,7 +14,7 @@ namespace Umbraco.Examine
{
private readonly IHostingEnvironment _hostingEnvironment;
public LuceneIndexDiagnostics(LuceneIndex index, ILogger logger, IHostingEnvironment hostingEnvironment)
public LuceneIndexDiagnostics(LuceneIndex index, ILogger<LuceneIndexDiagnostics> logger, IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
Index = index;
@@ -22,7 +22,7 @@ namespace Umbraco.Examine
}
public LuceneIndex Index { get; }
public ILogger Logger { get; }
public ILogger<LuceneIndexDiagnostics> Logger { get; }
public int DocumentCount
{
@@ -34,7 +34,7 @@ namespace Umbraco.Examine
}
catch (AlreadyClosedException)
{
Logger.Warn(typeof(UmbracoContentIndex), "Cannot get GetIndexDocumentCount, the writer is already closed");
Logger.LogWarning("Cannot get GetIndexDocumentCount, the writer is already closed");
return 0;
}
}
@@ -50,7 +50,7 @@ namespace Umbraco.Examine
}
catch (AlreadyClosedException)
{
Logger.Warn(typeof(UmbracoContentIndex), "Cannot get GetIndexFieldCount, the writer is already closed");
Logger.LogWarning("Cannot get GetIndexFieldCount, the writer is already closed");
return 0;
}
}

View File

@@ -1,7 +1,7 @@
using Examine;
using Examine.LuceneEngine.Providers;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Hosting;
using Umbraco.Core.Logging;
using Umbraco.Core.IO;
namespace Umbraco.Examine
@@ -12,12 +12,12 @@ namespace Umbraco.Examine
/// </summary>
public class LuceneIndexDiagnosticsFactory : IndexDiagnosticsFactory
{
private readonly ILogger _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly IHostingEnvironment _hostingEnvironment;
public LuceneIndexDiagnosticsFactory(ILogger logger, IHostingEnvironment hostingEnvironment)
public LuceneIndexDiagnosticsFactory(ILoggerFactory loggerFactory, IHostingEnvironment hostingEnvironment)
{
_logger = logger;
_loggerFactory = loggerFactory;
_hostingEnvironment = hostingEnvironment;
}
@@ -26,7 +26,7 @@ namespace Umbraco.Examine
if (!(index is IIndexDiagnostics indexDiag))
{
if (index is LuceneIndex luceneIndex)
indexDiag = new LuceneIndexDiagnostics(luceneIndex, _logger, _hostingEnvironment);
indexDiag = new LuceneIndexDiagnostics(luceneIndex, _loggerFactory.CreateLogger<LuceneIndexDiagnostics>(), _hostingEnvironment);
else
indexDiag = base.Create(index);
}

View File

@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using Microsoft.Extensions.Logging;
using Examine;
using Umbraco.Core;
using Umbraco.Core.Services;
@@ -21,6 +22,7 @@ namespace Umbraco.Examine
/// </summary>
public class UmbracoContentIndex : UmbracoExamineIndex, IUmbracoContentIndex, IDisposable
{
private readonly ILogger<UmbracoContentIndex> _logger;
protected ILocalizationService LanguageService { get; }
#region Constructors
@@ -33,6 +35,8 @@ namespace Umbraco.Examine
/// <param name="luceneDirectory"></param>
/// <param name="defaultAnalyzer"></param>
/// <param name="profilingLogger"></param>
/// <param name="logger"></param>
/// <param name="loggerFactory"></param>
/// <param name="hostingEnvironment"></param>
/// <param name="runtimeState"></param>
/// <param name="languageService"></param>
@@ -44,14 +48,17 @@ namespace Umbraco.Examine
FieldDefinitionCollection fieldDefinitions,
Analyzer defaultAnalyzer,
IProfilingLogger profilingLogger,
ILogger<UmbracoContentIndex> logger,
ILoggerFactory loggerFactory,
IHostingEnvironment hostingEnvironment,
IRuntimeState runtimeState,
ILocalizationService languageService,
IContentValueSetValidator validator,
IReadOnlyDictionary<string, IFieldValueTypeFactory> indexValueTypes = null)
: base(name, luceneDirectory, fieldDefinitions, defaultAnalyzer, profilingLogger, hostingEnvironment, runtimeState, validator, indexValueTypes)
: base(name, luceneDirectory, fieldDefinitions, defaultAnalyzer, profilingLogger, logger, loggerFactory ,hostingEnvironment, runtimeState, validator, indexValueTypes)
{
if (validator == null) throw new ArgumentNullException(nameof(validator));
_logger = logger;
LanguageService = languageService ?? throw new ArgumentNullException(nameof(languageService));
if (validator is IContentValueSetValidator contentValueSetValidator)
@@ -138,7 +145,8 @@ namespace Umbraco.Examine
var filtered = c.NativeQuery(rawQuery);
var results = filtered.Execute();
ProfilingLogger.Debug(GetType(), "DeleteFromIndex with query: {Query} (found {TotalItems} results)", rawQuery, results.TotalItemCount);
_logger.
LogDebug("DeleteFromIndex with query: {Query} (found {TotalItems} results)", rawQuery, results.TotalItemCount);
//need to queue a delete item for each one found
QueueIndexOperation(results.Select(r => new IndexOperation(new ValueSet(r.Id), IndexOperationType.Delete)));

View File

@@ -13,6 +13,7 @@ using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Directory = Lucene.Net.Store.Directory;
using Microsoft.Extensions.Logging;
namespace Umbraco.Examine
{
@@ -22,6 +23,9 @@ namespace Umbraco.Examine
/// </summary>
public abstract class UmbracoExamineIndex : LuceneIndex, IUmbracoIndex, IIndexDiagnostics
{
private readonly ILogger<UmbracoExamineIndex> _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly IRuntimeState _runtimeState;
// note
// wrapping all operations that end up calling base.SafelyProcessQueueItems in a safe call
@@ -29,7 +33,6 @@ namespace Umbraco.Examine
// call context (and the database it can contain)! ideally we should be able to override
// SafelyProcessQueueItems but that's not possible in the current version of Examine.
/// <summary>
/// Create a new <see cref="UmbracoExamineIndex"/>
@@ -39,6 +42,8 @@ namespace Umbraco.Examine
/// <param name="luceneDirectory"></param>
/// <param name="defaultAnalyzer"></param>
/// <param name="profilingLogger"></param>
/// <param name="logger"></param>
/// <param name="loggerFactory"></param>
/// <param name="hostingEnvironment"></param>
/// <param name="runtimeState"></param>
/// <param name="validator"></param>
@@ -49,12 +54,16 @@ namespace Umbraco.Examine
FieldDefinitionCollection fieldDefinitions,
Analyzer defaultAnalyzer,
IProfilingLogger profilingLogger,
ILogger<UmbracoExamineIndex> logger,
ILoggerFactory loggerFactory,
IHostingEnvironment hostingEnvironment,
IRuntimeState runtimeState,
IValueSetValidator validator = null,
IReadOnlyDictionary<string, IFieldValueTypeFactory> indexValueTypes = null)
: base(name, luceneDirectory, fieldDefinitions, defaultAnalyzer, validator, indexValueTypes)
{
_logger = logger;
_loggerFactory = loggerFactory;
_runtimeState = runtimeState;
ProfilingLogger = profilingLogger ?? throw new ArgumentNullException(nameof(profilingLogger));
@@ -62,7 +71,7 @@ namespace Umbraco.Examine
if (luceneDirectory is FSDirectory fsDir)
LuceneIndexFolder = fsDir.Directory;
_diagnostics = new UmbracoExamineIndexDiagnostics(this, ProfilingLogger, hostingEnvironment);
_diagnostics = new UmbracoExamineIndexDiagnostics(this, _loggerFactory.CreateLogger<UmbracoExamineIndexDiagnostics>(), hostingEnvironment);
}
private readonly bool _configBased = false;
@@ -118,7 +127,7 @@ namespace Umbraco.Examine
/// <param name="ex"></param>
protected override void OnIndexingError(IndexingErrorEventArgs ex)
{
ProfilingLogger.Error(GetType(), ex.InnerException, ex.Message);
_logger.LogError(ex.InnerException, ex.Message);
base.OnIndexingError(ex);
}
@@ -154,8 +163,7 @@ namespace Umbraco.Examine
/// </summary>
protected override void AddDocument(Document doc, ValueSet valueSet, IndexWriter writer)
{
ProfilingLogger.Debug(GetType(),
"Write lucene doc id:{DocumentId}, category:{DocumentCategory}, type:{DocumentItemType}",
_logger.LogDebug("Write lucene doc id:{DocumentId}, category:{DocumentCategory}, type:{DocumentItemType}",
valueSet.Id,
valueSet.Category,
valueSet.ItemType);

View File

@@ -1,10 +1,10 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Lucene.Net.Store;
using Umbraco.Core;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
namespace Umbraco.Examine
{
@@ -12,7 +12,7 @@ namespace Umbraco.Examine
{
private readonly UmbracoExamineIndex _index;
public UmbracoExamineIndexDiagnostics(UmbracoExamineIndex index, ILogger logger, IHostingEnvironment hostingEnvironment)
public UmbracoExamineIndexDiagnostics(UmbracoExamineIndex index, ILogger<UmbracoExamineIndexDiagnostics> logger, IHostingEnvironment hostingEnvironment)
: base(index, logger, hostingEnvironment)
{
_index = index;

View File

@@ -11,6 +11,7 @@ using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
using Umbraco.Core.Configuration.Models;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
namespace Umbraco.Examine
{
@@ -25,6 +26,7 @@ namespace Umbraco.Examine
public UmbracoIndexesCreator(
ITypeFinder typeFinder,
IProfilingLogger profilingLogger,
ILoggerFactory loggerFactory,
ILocalizationService languageService,
IPublicAccessService publicAccessService,
IMemberService memberService,
@@ -35,6 +37,7 @@ namespace Umbraco.Examine
ILuceneDirectoryFactory directoryFactory) : base(typeFinder, hostingEnvironment, settings)
{
ProfilingLogger = profilingLogger ?? throw new System.ArgumentNullException(nameof(profilingLogger));
LoggerFactory = loggerFactory;
LanguageService = languageService ?? throw new System.ArgumentNullException(nameof(languageService));
PublicAccessService = publicAccessService ?? throw new System.ArgumentNullException(nameof(publicAccessService));
MemberService = memberService ?? throw new System.ArgumentNullException(nameof(memberService));
@@ -45,6 +48,7 @@ namespace Umbraco.Examine
}
protected IProfilingLogger ProfilingLogger { get; }
protected ILoggerFactory LoggerFactory { get; }
protected IHostingEnvironment HostingEnvironment { get; }
protected IRuntimeState RuntimeState { get; }
protected ILuceneDirectoryFactory DirectoryFactory { get; }
@@ -75,6 +79,8 @@ namespace Umbraco.Examine
new UmbracoFieldDefinitionCollection(),
new CultureInvariantWhitespaceAnalyzer(),
ProfilingLogger,
LoggerFactory.CreateLogger<UmbracoContentIndex>(),
LoggerFactory,
HostingEnvironment,
RuntimeState,
LanguageService,
@@ -91,6 +97,8 @@ namespace Umbraco.Examine
new UmbracoFieldDefinitionCollection(),
new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30),
ProfilingLogger,
LoggerFactory.CreateLogger<UmbracoContentIndex>(),
LoggerFactory,
HostingEnvironment,
RuntimeState,
LanguageService,
@@ -106,6 +114,8 @@ namespace Umbraco.Examine
DirectoryFactory.CreateDirectory(Constants.UmbracoIndexes.MembersIndexPath),
new CultureInvariantWhitespaceAnalyzer(),
ProfilingLogger,
LoggerFactory.CreateLogger<UmbracoMemberIndex>(),
LoggerFactory,
HostingEnvironment,
RuntimeState,
UmbracoIndexConfig.GetMemberValueSetValidator()

View File

@@ -1,5 +1,6 @@
using Examine;
using Lucene.Net.Analysis;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
@@ -31,10 +32,12 @@ namespace Umbraco.Examine
Directory luceneDirectory,
Analyzer analyzer,
IProfilingLogger profilingLogger,
ILogger<UmbracoMemberIndex> logger,
ILoggerFactory loggerFactory,
IHostingEnvironment hostingEnvironment,
IRuntimeState runtimeState,
IValueSetValidator validator = null) :
base(name, luceneDirectory, fieldDefinitions, analyzer, profilingLogger, hostingEnvironment, runtimeState, validator)
base(name, luceneDirectory, fieldDefinitions, analyzer, profilingLogger, logger, loggerFactory, hostingEnvironment, runtimeState, validator)
{
}

View File

@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Sync;
@@ -32,13 +33,14 @@ namespace Umbraco.Web
IScopeProvider scopeProvider,
ISqlContext sqlContext,
IProfilingLogger proflog,
ILogger<BatchedDatabaseServerMessenger> logger,
IServerRegistrar serverRegistrar,
DatabaseServerMessengerOptions options,
IHostingEnvironment hostingEnvironment,
CacheRefresherCollection cacheRefreshers,
IRequestCache requestCache,
IRequestAccessor requestAccessor)
: base(mainDom, scopeProvider, sqlContext, proflog, serverRegistrar, true, options, hostingEnvironment, cacheRefreshers)
: base(mainDom, scopeProvider, sqlContext, proflog, logger, serverRegistrar, true, options, hostingEnvironment, cacheRefreshers)
{
_databaseFactory = databaseFactory;
_requestCache = requestCache;
@@ -52,7 +54,7 @@ namespace Umbraco.Web
if (_databaseFactory.CanConnect == false)
{
Logger.Warn<BatchedDatabaseServerMessenger>("Cannot connect to the database, distributed calls will not be enabled for this server.");
Logger.LogWarning("Cannot connect to the database, distributed calls will not be enabled for this server.");
}
else
{

View File

@@ -3,9 +3,9 @@ using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;
namespace Umbraco.Web.Cache
{
@@ -17,12 +17,12 @@ namespace Umbraco.Web.Cache
private static readonly ConcurrentDictionary<string, MethodInfo> FoundHandlers = new ConcurrentDictionary<string, MethodInfo>();
private readonly DistributedCache _distributedCache;
private readonly IUmbracoContextFactory _umbracoContextFactory;
private readonly ILogger _logger;
private readonly ILogger<DistributedCacheBinder> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="DistributedCacheBinder"/> class.
/// </summary>
public DistributedCacheBinder(DistributedCache distributedCache, IUmbracoContextFactory umbracoContextFactory, ILogger logger)
public DistributedCacheBinder(DistributedCache distributedCache, IUmbracoContextFactory umbracoContextFactory, ILogger<DistributedCacheBinder> logger)
{
_distributedCache = distributedCache;
_logger = logger;
@@ -73,7 +73,7 @@ namespace Umbraco.Web.Cache
{
// TODO: should this be fatal (ie, an exception)?
var name = e.Sender.GetType().Name + "_" + e.EventName;
_logger.Warn<DistributedCacheBinder>("Dropping event {EventName} because no corresponding handler was found.", name);
_logger.LogWarning("Dropping event {EventName} because no corresponding handler was found.", name);
continue;
}

View File

@@ -1,8 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Services;
@@ -43,7 +43,7 @@ namespace Umbraco.Web.Cache
if (supportUnbinding)
_unbinders = new List<Action>();
_logger.Info<DistributedCacheBinderComponent>("Initializing Umbraco internal event handlers for cache refreshing.");
_logger.LogInformation("Initializing Umbraco internal event handlers for cache refreshing.");
// bind to user and user group events
Bind(() => UserService.SavedUserGroup += UserService_SavedUserGroup,

View File

@@ -1,9 +1,9 @@
using System;
using System.Threading;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Hosting;
using Umbraco.Core.Logging;
using Umbraco.Core.Services;
using Umbraco.Core.Services.Changes;
using Umbraco.Core.Sync;
@@ -83,7 +83,8 @@ namespace Umbraco.Web.Compose
private object _locker = new object();
private readonly DatabaseServerRegistrar _registrar;
private readonly IBatchedDatabaseServerMessenger _messenger;
private readonly ILogger _logger;
private readonly ILogger<DatabaseServerRegistrarAndMessengerComponent> _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly IServerRegistrationService _registrationService;
private readonly BackgroundTaskRunner<IBackgroundTask> _touchTaskRunner;
private readonly BackgroundTaskRunner<IBackgroundTask> _processTaskRunner;
@@ -95,11 +96,13 @@ namespace Umbraco.Web.Compose
IServerRegistrar serverRegistrar,
IServerMessenger serverMessenger,
IServerRegistrationService registrationService,
ILogger logger,
ILogger<DatabaseServerRegistrarAndMessengerComponent> logger,
ILoggerFactory loggerFactory,
IApplicationShutdownRegistry hostingEnvironment,
IRequestAccessor requestAccessor)
{
_logger = logger;
_loggerFactory = loggerFactory;
_registrationService = registrationService;
_requestAccessor = requestAccessor;
@@ -108,7 +111,7 @@ namespace Umbraco.Web.Compose
if (_registrar != null)
{
_touchTaskRunner = new BackgroundTaskRunner<IBackgroundTask>("ServerRegistration",
new BackgroundTaskRunnerOptions { AutoStart = true }, logger, hostingEnvironment);
new BackgroundTaskRunnerOptions { AutoStart = true }, _loggerFactory.CreateLogger<BackgroundTaskRunner<IBackgroundTask>>(), hostingEnvironment);
}
// create task runner for BatchedDatabaseServerMessenger
@@ -116,7 +119,7 @@ namespace Umbraco.Web.Compose
if (_messenger != null)
{
_processTaskRunner = new BackgroundTaskRunner<IBackgroundTask>("ServerInstProcess",
new BackgroundTaskRunnerOptions { AutoStart = true }, logger, hostingEnvironment);
new BackgroundTaskRunnerOptions { AutoStart = true }, _loggerFactory.CreateLogger<BackgroundTaskRunner<IBackgroundTask>>(), hostingEnvironment);
}
}
@@ -225,7 +228,7 @@ namespace Umbraco.Web.Compose
}
catch (Exception e)
{
_logger.Error<InstructionProcessTask>(e, "Failed (will repeat).");
_logger.LogError(e, "Failed (will repeat).");
}
return true; // repeat
}
@@ -268,7 +271,7 @@ namespace Umbraco.Web.Compose
}
catch (Exception ex)
{
_logger.Error<DatabaseServerRegistrarAndMessengerComponent>(ex, "Failed to update server record in database.");
_logger.LogError(ex, "Failed to update server record in database.");
return false; // probably stop if we have an error
}
}

View File

@@ -1,8 +1,8 @@
using System.IO;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Composing;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Manifest;
using Umbraco.Net;
@@ -11,7 +11,7 @@ namespace Umbraco.Core.Compose
public sealed class ManifestWatcherComponent : IComponent
{
private readonly IHostingEnvironment _hosting;
private readonly ILogger _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly IIOHelper _ioHelper;
private readonly IUmbracoApplicationLifetime _umbracoApplicationLifetime;
@@ -19,10 +19,10 @@ namespace Umbraco.Core.Compose
// package.manifest chances and restarts the application on any change
private ManifestWatcher _mw;
public ManifestWatcherComponent(IHostingEnvironment hosting, ILogger logger, IIOHelper ioHelper, IUmbracoApplicationLifetime umbracoApplicationLifetime)
public ManifestWatcherComponent(IHostingEnvironment hosting, ILoggerFactory loggerFactory, IIOHelper ioHelper, IUmbracoApplicationLifetime umbracoApplicationLifetime)
{
_hosting = hosting;
_logger = logger;
_loggerFactory = loggerFactory;
_ioHelper = ioHelper;
_umbracoApplicationLifetime = umbracoApplicationLifetime;
}
@@ -37,7 +37,7 @@ namespace Umbraco.Core.Compose
var appPlugins = _ioHelper.MapPath("~/App_Plugins/");
if (Directory.Exists(appPlugins) == false) return;
_mw = new ManifestWatcher(_logger, _umbracoApplicationLifetime);
_mw = new ManifestWatcher(_loggerFactory.CreateLogger<ManifestWatcher>(), _umbracoApplicationLifetime);
_mw.Start(Directory.GetDirectories(appPlugins));
}

View File

@@ -3,10 +3,10 @@ using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Entities;
using Umbraco.Core.Models.Membership;
@@ -189,7 +189,7 @@ namespace Umbraco.Web.Compose
private readonly IUserService _userService;
private readonly ILocalizedTextService _textService;
private readonly GlobalSettings _globalSettings;
private readonly ILogger _logger;
private readonly ILogger<Notifier> _logger;
/// <summary>
/// Constructor
@@ -208,7 +208,7 @@ namespace Umbraco.Web.Compose
IUserService userService,
ILocalizedTextService textService,
IOptions<GlobalSettings> globalSettings,
ILogger logger)
ILogger<Notifier> logger)
{
_umbracoContextAccessor = umbracoContextAccessor;
_requestAccessor = requestAccessor;
@@ -226,11 +226,11 @@ namespace Umbraco.Web.Compose
//if there is no current user, then use the admin
if (user == null)
{
_logger.Debug(typeof(Notifier), "There is no current Umbraco user logged in, the notifications will be sent from the administrator");
_logger.LogDebug("There is no current Umbraco user logged in, the notifications will be sent from the administrator");
user = _userService.GetUserById(Constants.Security.SuperUserId);
if (user == null)
{
_logger.Warn(typeof(Notifier), "Notifications can not be sent, no admin user with id {SuperUserId} could be resolved", Constants.Security.SuperUserId);
_logger.LogWarning("Notifications can not be sent, no admin user with id {SuperUserId} could be resolved", Constants.Security.SuperUserId);
return;
}
}
@@ -243,7 +243,7 @@ namespace Umbraco.Web.Compose
if (sender == null) throw new ArgumentNullException(nameof(sender));
if (siteUri == null)
{
_logger.Warn(typeof(Notifier), "Notifications can not be sent, no site url is set (might be during boot process?)");
_logger.LogWarning("Notifications can not be sent, no site url is set (might be during boot process?)");
return;
}

View File

@@ -1,10 +1,10 @@
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
using Umbraco.Core.IO.MediaPathSchemes;
using Umbraco.Core.Logging;
namespace Umbraco.Core.Composing.CompositionExtensions
{
@@ -98,7 +98,7 @@ namespace Umbraco.Core.Composing.CompositionExtensions
{
var ioHelper = factory.GetInstance<IIOHelper>();
var hostingEnvironment = factory.GetInstance<IHostingEnvironment>();
var logger = factory.GetInstance<ILogger>();
var logger = factory.GetInstance<ILogger<PhysicalFileSystem>>();
var globalSettings = factory.GetInstance<IOptions<GlobalSettings>>().Value;
var rootPath = hostingEnvironment.MapPathWebRoot(globalSettings.UmbracoMediaPath);

View File

@@ -2,13 +2,13 @@
using System.IO;
using System.Linq;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Cache;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Events;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Packaging;
using Umbraco.Core.Routing;
using Umbraco.Core.Services;
@@ -61,7 +61,7 @@ namespace Umbraco.Core.Composing.CompositionExtensions
composition.Register<LocalizedTextServiceFileSources>(SourcesFactory);
composition.RegisterUnique<ILocalizedTextService>(factory => new LocalizedTextService(
factory.GetInstance<Lazy<LocalizedTextServiceFileSources>>(),
factory.GetInstance<ILogger>()));
factory.GetInstance<ILogger<LocalizedTextService>>()));
composition.RegisterUnique<IEntityXmlSerializer, EntityXmlSerializer>();
@@ -94,7 +94,7 @@ namespace Umbraco.Core.Composing.CompositionExtensions
factory.GetInstance<ILocalizationService>(),
factory.GetInstance<IHostingEnvironment>(),
factory.GetInstance<IEntityXmlSerializer>(),
factory.GetInstance<ILogger>(),
factory.GetInstance<ILoggerFactory>(),
factory.GetInstance<IUmbracoVersion>(),
factory.GetInstance<IOptions<GlobalSettings>>(),
packageRepoFileName);
@@ -122,7 +122,7 @@ namespace Umbraco.Core.Composing.CompositionExtensions
.Select(x => new LocalizedTextServiceSupplementaryFileSource(x, true));
return new LocalizedTextServiceFileSources(
container.GetInstance<ILogger>(),
container.GetInstance<ILogger<LocalizedTextServiceFileSources>>(),
container.GetInstance<AppCaches>(),
mainLangFolder,
pluginLangFolders.Concat(userLangFolders));

View File

@@ -2,6 +2,7 @@
using LightInject.Microsoft.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Umbraco.Composing;
using Umbraco.Core.Composing.LightInject;
@@ -87,7 +88,7 @@ namespace Umbraco.Core.Composing
{
// after cross wiring, configure "Current"
Current.Initialize(
_container.GetInstance<Umbraco.Core.Logging.ILogger>(),
_container.GetInstance<ILogger<object>>(),
_container.GetInstance<IOptions<SecuritySettings>>().Value,
_container.GetInstance<IOptions<GlobalSettings>>().Value,
_container.GetInstance<IIOHelper>(),

View File

@@ -1,4 +1,5 @@
using Umbraco.Core.Cache;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Cache;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration;
using Umbraco.Core.Hosting;
@@ -24,21 +25,21 @@ namespace Umbraco.Core
// then we pre-resolve them which means that the instance re-resolved later is different... BUT if we register that
// pre-resolved instance here again, then it will be the same instance re-resolved later, just like we are doing with
// IDbProviderFactoryCreator.
ILogger logger, IProfiler profiler, IProfilingLogger profilingLogger,
ILogger logger, ILoggerFactory loggerFactory, IProfiler profiler, IProfilingLogger profilingLogger,
IMainDom mainDom,
AppCaches appCaches,
IUmbracoDatabaseFactory databaseFactory,
TypeLoader typeLoader,
IRuntimeState state,
ITypeFinder typeFinder,
IIOHelper ioHelper,
IUmbracoVersion umbracoVersion,
IDbProviderFactoryCreator dbProviderFactoryCreator,
IHostingEnvironment hostingEnvironment,
IBackOfficeInfo backOfficeInfo)
{
{
composition.RegisterUnique(logger);
composition.RegisterUnique(loggerFactory);
composition.RegisterUnique(profiler);
composition.RegisterUnique(profilingLogger);
composition.RegisterUnique(mainDom);

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using Examine;
using Umbraco.Core.Composing;
@@ -14,12 +15,14 @@ namespace Umbraco.Examine
/// </summary>
public class IndexRebuilder
{
private readonly IProfilingLogger _logger;
private readonly IProfilingLogger _profilingLogger;
private readonly ILogger<IndexRebuilder> _logger;
private readonly IEnumerable<IIndexPopulator> _populators;
public IExamineManager ExamineManager { get; }
public IndexRebuilder(IProfilingLogger logger, IExamineManager examineManager, IEnumerable<IIndexPopulator> populators)
public IndexRebuilder(IProfilingLogger profilingLogger , ILogger<IndexRebuilder> logger, IExamineManager examineManager, IEnumerable<IIndexPopulator> populators)
{
_profilingLogger = profilingLogger ;
_populators = populators;
_logger = logger;
ExamineManager = examineManager;
@@ -65,7 +68,7 @@ namespace Umbraco.Examine
}
catch (Exception e)
{
_logger.Error<IndexRebuilder>(e, "Index populating failed for populator {Populator}", populator.GetType());
_logger.LogError(e, "Index populating failed for populator {Populator}", populator.GetType());
}
}
}

View File

@@ -2,8 +2,8 @@
using Examine;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.PropertyEditors.ValueConverters;
@@ -17,13 +17,13 @@ namespace Umbraco.Examine
{
private readonly UrlSegmentProviderCollection _urlSegmentProviders;
private readonly IUserService _userService;
private readonly ILogger _logger;
private readonly ILogger<MediaValueSetBuilder> _logger;
private readonly IShortStringHelper _shortStringHelper;
private readonly IJsonSerializer _serializer;
public MediaValueSetBuilder(PropertyEditorCollection propertyEditors,
UrlSegmentProviderCollection urlSegmentProviders,
IUserService userService, ILogger logger, IShortStringHelper shortStringHelper, IJsonSerializer serializer)
IUserService userService, ILogger<MediaValueSetBuilder> logger, IShortStringHelper shortStringHelper, IJsonSerializer serializer)
: base(propertyEditors, false)
{
_urlSegmentProviders = urlSegmentProviders;
@@ -55,7 +55,7 @@ namespace Umbraco.Examine
}
catch (Exception ex)
{
_logger.Error<MediaValueSetBuilder>(ex, $"Could not Deserialize ImageCropperValue for item with key {m.Key} ");
_logger.LogError(ex, $"Could not Deserialize ImageCropperValue for item with key {m.Key} ");
}
if (cropper != null)

View File

@@ -5,7 +5,7 @@ using System.Text;
using HeyRed.MarkdownSharp;
using Umbraco.Composing;
using Umbraco.Core.Configuration.HealthChecks;
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging;
namespace Umbraco.Web.HealthCheck
{
@@ -27,7 +27,7 @@ namespace Umbraco.Web.HealthCheck
}
catch (Exception ex)
{
Logger.Error<HealthCheckResults>(ex, "Error running scheduled health check: {HealthCheckName}", t.Name);
Logger.LogError(ex, "Error running scheduled health check: {HealthCheckName}", t.Name);
var message = $"Health check failed with exception: {ex.Message}. See logs for details.";
return new List<HealthCheckStatus>
{
@@ -54,7 +54,7 @@ namespace Umbraco.Web.HealthCheck
public void LogResults()
{
Logger.Info<HealthCheckResults>("Scheduled health check results:");
Logger.LogInformation("Scheduled health check results:");
foreach (var result in _results)
{
var checkName = result.Key;
@@ -62,16 +62,16 @@ namespace Umbraco.Web.HealthCheck
var checkIsSuccess = result.Value.All(x => x.ResultType == StatusResultType.Success);
if (checkIsSuccess)
{
Logger.Info<HealthCheckResults>("Checks for '{HealthCheckName}' all completed successfully.", checkName);
Logger.LogInformation("Checks for '{HealthCheckName}' all completed successfully.", checkName);
}
else
{
Logger.Warn<HealthCheckResults>("Checks for '{HealthCheckName}' completed with errors.", checkName);
Logger.LogWarning("Checks for '{HealthCheckName}' completed with errors.", checkName);
}
foreach (var checkResult in checkResults)
{
Logger.Info<HealthCheckResults>("Result for {HealthCheckName}: {HealthCheckResult}, Message: '{HealthCheckMessage}'", checkName, checkResult.ResultType, checkResult.Message);
Logger.LogInformation("Result for {HealthCheckName}: {HealthCheckResult}, Message: '{HealthCheckMessage}'", checkName, checkResult.ResultType, checkResult.Message);
}
}
}

View File

@@ -3,9 +3,9 @@ using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.Migrations.Install;
using Umbraco.Core.Models;
using Umbraco.Net;
@@ -22,7 +22,7 @@ namespace Umbraco.Web.Install
{
private static HttpClient _httpClient;
private readonly DatabaseBuilder _databaseBuilder;
private readonly ILogger _logger;
private readonly ILogger<InstallHelper> _logger;
private readonly IUmbracoVersion _umbracoVersion;
private readonly ConnectionStrings _connectionStrings;
private readonly IInstallationService _installationService;
@@ -33,7 +33,7 @@ namespace Umbraco.Web.Install
private InstallationType? _installationType;
public InstallHelper(DatabaseBuilder databaseBuilder,
ILogger logger,
ILogger<InstallHelper> logger,
IUmbracoVersion umbracoVersion,
IOptions<ConnectionStrings> connectionStrings,
IInstallationService installationService,
@@ -105,7 +105,7 @@ namespace Umbraco.Web.Install
}
catch (Exception ex)
{
_logger.Error<InstallHelper>(ex, "An error occurred in InstallStatus trying to check upgrades");
_logger.LogError(ex, "An error occurred in InstallStatus trying to check upgrades");
}
}
@@ -156,7 +156,7 @@ namespace Umbraco.Web.Install
}
catch (AggregateException ex)
{
_logger.Error<InstallHelper>(ex, "Could not download list of available starter kits");
_logger.LogError(ex, "Could not download list of available starter kits");
}
return packages;

View File

@@ -1,8 +1,8 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Migrations.Install;
using Umbraco.Web.Install.Models;
using Umbraco.Core.Configuration.Models;
@@ -16,13 +16,14 @@ namespace Umbraco.Web.Install.InstallSteps
public class DatabaseConfigureStep : InstallSetupStep<DatabaseModel>
{
private readonly DatabaseBuilder _databaseBuilder;
private readonly ILogger _logger;
private readonly ILogger<DatabaseConfigureStep> _logger;
private readonly ConnectionStrings _connectionStrings;
public DatabaseConfigureStep(DatabaseBuilder databaseBuilder, IOptions<ConnectionStrings> connectionStrings)
public DatabaseConfigureStep(DatabaseBuilder databaseBuilder, IOptions<ConnectionStrings> connectionStrings, ILogger<DatabaseConfigureStep> logger)
{
_databaseBuilder = databaseBuilder;
_connectionStrings = connectionStrings.Value ?? throw new ArgumentNullException(nameof(connectionStrings));
_logger = logger;
}
public override Task<InstallSetupResult> ExecuteAsync(DatabaseModel database)
@@ -120,7 +121,7 @@ namespace Umbraco.Web.Install.InstallSteps
}
catch (Exception ex)
{
_logger.Error<DatabaseConfigureStep>(ex, "An error occurred, reconfiguring...");
_logger.LogError(ex, "An error occurred, reconfiguring...");
//something went wrong, could not connect so probably need to reconfigure
return true;
}

View File

@@ -2,11 +2,11 @@
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Migrations.Install;
using Umbraco.Core.Migrations.Upgrade;
using Umbraco.Web.Install.Models;
@@ -20,14 +20,14 @@ namespace Umbraco.Web.Install.InstallSteps
{
private readonly DatabaseBuilder _databaseBuilder;
private readonly IRuntimeState _runtime;
private readonly ILogger _logger;
private readonly ILogger<DatabaseUpgradeStep> _logger;
private readonly IUmbracoVersion _umbracoVersion;
private readonly ConnectionStrings _connectionStrings;
public DatabaseUpgradeStep(
DatabaseBuilder databaseBuilder,
IRuntimeState runtime,
ILogger logger,
ILogger<DatabaseUpgradeStep> logger,
IUmbracoVersion umbracoVersion,
IOptions<ConnectionStrings> connectionStrings)
{
@@ -46,7 +46,7 @@ namespace Umbraco.Web.Install.InstallSteps
if (upgrade)
{
_logger.Info<DatabaseUpgradeStep>("Running 'Upgrade' service");
_logger.LogInformation("Running 'Upgrade' service");
var plan = new UmbracoPlan(_umbracoVersion);
plan.AddPostMigration<ClearCsrfCookies>(); // needed when running installer (back-office)

View File

@@ -1,6 +1,7 @@
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Extensions.Logging;
@@ -12,7 +13,7 @@ namespace Umbraco.Core.Logging.Serilog
///<summary>
/// Implements <see cref="ILogger"/> on top of Serilog.
///</summary>
public class SerilogLogger : ILogger, IDisposable
public class SerilogLogger : IDisposable
{
public global::Serilog.ILogger SerilogLog { get; }
@@ -215,5 +216,6 @@ namespace Umbraco.Core.Logging.Serilog
{
SerilogLog.DisposeIfDisposable();
}
}
}

View File

@@ -1,4 +1,5 @@
using System.IO;
using Microsoft.Extensions.Logging;
using Serilog;
using Umbraco.Core.Composing;
using Umbraco.Core.Hosting;
@@ -16,7 +17,7 @@ namespace Umbraco.Core.Logging.Viewer
composition.RegisterUnique<ILogViewer>(factory =>
{
return new SerilogJsonLogViewer(factory.GetInstance<ILogger>(),
return new SerilogJsonLogViewer(factory.GetInstance<ILogger<SerilogJsonLogViewer>>(),
factory.GetInstance<ILogViewerConfig>(),
factory.GetInstance<ILoggingConfiguration>(),
Log.Logger);

View File

@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Serilog.Events;
using Serilog.Formatting.Compact.Reader;
@@ -11,10 +12,10 @@ namespace Umbraco.Core.Logging.Viewer
internal class SerilogJsonLogViewer : SerilogLogViewerSourceBase
{
private readonly string _logsPath;
private readonly ILogger _logger;
private readonly ILogger<SerilogJsonLogViewer> _logger;
public SerilogJsonLogViewer(
ILogger logger,
ILogger<SerilogJsonLogViewer> logger,
ILogViewerConfig logViewerConfig,
ILoggingConfiguration loggingConfiguration,
global::Serilog.ILogger serilogLog)
@@ -128,7 +129,7 @@ namespace Umbraco.Core.Logging.Viewer
{
// As we are reading/streaming one line at a time in the JSON file
// Thus we can not report the line number, as it will always be 1
_logger.Error<SerilogJsonLogViewer>(ex, "Unable to parse a line in the JSON log file");
_logger.LogError(ex, "Unable to parse a line in the JSON log file");
evt = null;
return true;

View File

@@ -1,9 +1,9 @@
using System;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Core.Composing;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Serialization;
using Umbraco.Core.Services;
@@ -16,7 +16,7 @@ namespace Umbraco.Core.Manifest
/// </summary>
internal class DataEditorConverter : JsonReadConverter<IDataEditor>
{
private readonly ILogger _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly IIOHelper _ioHelper;
private readonly IDataTypeService _dataTypeService;
private readonly ILocalizationService _localizationService;
@@ -26,9 +26,9 @@ namespace Umbraco.Core.Manifest
/// <summary>
/// Initializes a new instance of the <see cref="DataEditorConverter"/> class.
/// </summary>
public DataEditorConverter(ILogger logger, IIOHelper ioHelper, IDataTypeService dataTypeService, ILocalizationService localizationService, ILocalizedTextService textService, IShortStringHelper shortStringHelper)
public DataEditorConverter(ILoggerFactory loggerFactory, IIOHelper ioHelper, IDataTypeService dataTypeService, ILocalizationService localizationService, ILocalizedTextService textService, IShortStringHelper shortStringHelper)
{
_logger = logger;
_loggerFactory = loggerFactory;
_ioHelper = ioHelper;
_dataTypeService = dataTypeService;
_localizationService = localizationService;
@@ -61,7 +61,7 @@ namespace Umbraco.Core.Manifest
type = EditorType.MacroParameter;
}
return new DataEditor(_logger, _dataTypeService, _localizationService, _textService, _shortStringHelper, type);
return new DataEditor(_loggerFactory, _dataTypeService, _localizationService, _textService, _shortStringHelper, type);
}
/// <inheritdoc />

View File

@@ -3,10 +3,10 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Umbraco.Core.Cache;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Serialization;
using Umbraco.Core.Services;
@@ -19,13 +19,14 @@ namespace Umbraco.Core.Manifest
/// </summary>
public class ManifestParser : IManifestParser
{
private readonly ILoggerFactory _loggerFactory;
private readonly IJsonSerializer _jsonSerializer;
private readonly ILocalizedTextService _localizedTextService;
private readonly IShortStringHelper _shortStringHelper;
private static readonly string Utf8Preamble = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
private readonly IAppPolicyCache _cache;
private readonly ILogger _logger;
private readonly ILogger<ManifestParser> _logger;
private readonly IIOHelper _ioHelper;
private readonly IDataTypeService _dataTypeService;
private readonly ILocalizationService _localizationService;
@@ -41,15 +42,17 @@ namespace Umbraco.Core.Manifest
AppCaches appCaches,
ManifestValueValidatorCollection validators,
ManifestFilterCollection filters,
ILogger logger,
ILogger<ManifestParser> logger,
ILoggerFactory loggerFactory,
IIOHelper ioHelper,
IDataTypeService dataTypeService,
ILocalizationService localizationService,
IJsonSerializer jsonSerializer,
ILocalizedTextService localizedTextService,
IShortStringHelper shortStringHelper)
: this(appCaches, validators, filters, "~/App_Plugins", logger, ioHelper, dataTypeService, localizationService)
: this(appCaches, validators, filters, "~/App_Plugins", logger, loggerFactory, ioHelper, dataTypeService, localizationService)
{
_loggerFactory = loggerFactory;
_jsonSerializer = jsonSerializer;
_localizedTextService = localizedTextService;
_shortStringHelper = shortStringHelper;
@@ -58,7 +61,7 @@ namespace Umbraco.Core.Manifest
/// <summary>
/// Initializes a new instance of the <see cref="ManifestParser"/> class.
/// </summary>
private ManifestParser(AppCaches appCaches, ManifestValueValidatorCollection validators, ManifestFilterCollection filters, string path, ILogger logger, IIOHelper ioHelper, IDataTypeService dataTypeService, ILocalizationService localizationService)
private ManifestParser(AppCaches appCaches, ManifestValueValidatorCollection validators, ManifestFilterCollection filters, string path, ILogger<ManifestParser> logger, ILoggerFactory loggerFactory, IIOHelper ioHelper, IDataTypeService dataTypeService, ILocalizationService localizationService)
{
if (appCaches == null) throw new ArgumentNullException(nameof(appCaches));
_cache = appCaches.RuntimeCache;
@@ -70,6 +73,7 @@ namespace Umbraco.Core.Manifest
if (path == null) throw new ArgumentNullException(nameof(path));
if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(path));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
_ioHelper = ioHelper;
Path = path;
@@ -115,7 +119,7 @@ namespace Umbraco.Core.Manifest
}
catch (Exception e)
{
_logger.Error<ManifestParser>(e, "Failed to parse manifest at '{Path}', ignoring.", path);
_logger.LogError(e, "Failed to parse manifest at '{Path}', ignoring.", path);
}
}
@@ -189,7 +193,7 @@ namespace Umbraco.Core.Manifest
if (string.IsNullOrWhiteSpace(text)) throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(text));
var manifest = JsonConvert.DeserializeObject<PackageManifest>(text,
new DataEditorConverter(_logger, _ioHelper, _dataTypeService, _localizationService, _localizedTextService, _shortStringHelper),
new DataEditorConverter(_loggerFactory, _ioHelper, _dataTypeService, _localizationService, _localizedTextService, _shortStringHelper),
new ValueValidatorConverter(_validators),
new DashboardAccessRuleConverter());

View File

@@ -1,10 +1,10 @@
using System;
using System.Drawing;
using System.IO;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Media;
using Umbraco.Core.Models;
@@ -16,12 +16,12 @@ namespace Umbraco.Web.Media
public class UploadAutoFillProperties
{
private readonly IMediaFileSystem _mediaFileSystem;
private readonly ILogger _logger;
private readonly ILogger<UploadAutoFillProperties> _logger;
private readonly IImageUrlGenerator _imageUrlGenerator;
public UploadAutoFillProperties(
IMediaFileSystem mediaFileSystem,
ILogger logger,
ILogger<UploadAutoFillProperties> logger,
IImageUrlGenerator imageUrlGenerator)
{
_mediaFileSystem = mediaFileSystem ?? throw new ArgumentNullException(nameof(mediaFileSystem));
@@ -77,7 +77,7 @@ namespace Umbraco.Web.Media
}
catch (Exception ex)
{
_logger.Error(typeof(UploadAutoFillProperties), ex, "Could not populate upload auto-fill properties for file '{File}'.", filepath);
_logger.LogError(ex, "Could not populate upload auto-fill properties for file '{File}'.", filepath);
ResetProperties(content, autoFillConfig, culture, segment);
}
}

View File

@@ -1,6 +1,6 @@
using System;
using System.Collections.Generic;
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Persistence;
namespace Umbraco.Core.Migrations
@@ -13,7 +13,7 @@ namespace Umbraco.Core.Migrations
/// <summary>
/// Gets the logger.
/// </summary>
ILogger Logger { get; }
ILogger<IMigrationContext> Logger { get; }
/// <summary>
/// Gets the database instance.

View File

@@ -2,12 +2,12 @@
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Migrations.Upgrade;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Dtos;
@@ -27,7 +27,8 @@ namespace Umbraco.Core.Migrations.Install
private readonly IMigrationBuilder _migrationBuilder;
private readonly IKeyValueService _keyValueService;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly ILogger _logger;
private readonly ILogger<DatabaseBuilder> _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly IUmbracoVersion _umbracoVersion;
private readonly IDbProviderFactoryCreator _dbProviderFactoryCreator;
private readonly IConfigManipulator _configManipulator;
@@ -41,7 +42,8 @@ namespace Umbraco.Core.Migrations.Install
IScopeProvider scopeProvider,
IUmbracoDatabaseFactory databaseFactory,
IRuntimeState runtime,
ILogger logger,
ILogger<DatabaseBuilder> logger,
ILoggerFactory loggerFactory,
IMigrationBuilder migrationBuilder,
IKeyValueService keyValueService,
IHostingEnvironment hostingEnvironment,
@@ -53,6 +55,7 @@ namespace Umbraco.Core.Migrations.Install
_databaseFactory = databaseFactory;
_runtime = runtime;
_logger = logger;
_loggerFactory = loggerFactory;
_migrationBuilder = migrationBuilder;
_keyValueService = keyValueService;
_hostingEnvironment = hostingEnvironment;
@@ -318,7 +321,7 @@ namespace Umbraco.Core.Migrations.Install
return _databaseSchemaValidationResult;
var database = scope.Database;
var dbSchema = new DatabaseSchemaCreator(database, _logger, _umbracoVersion);
var dbSchema = new DatabaseSchemaCreator(database, _loggerFactory.CreateLogger<DatabaseSchemaCreator>(), _loggerFactory, _umbracoVersion);
_databaseSchemaValidationResult = dbSchema.ValidateSchema();
return _databaseSchemaValidationResult;
}
@@ -350,7 +353,7 @@ namespace Umbraco.Core.Migrations.Install
return readyForInstall.Result;
}
_logger.Info<DatabaseBuilder>("Database configuration status: Started");
_logger.LogInformation("Database configuration status: Started");
var database = scope.Database;
@@ -366,18 +369,18 @@ namespace Umbraco.Core.Migrations.Install
if (_runtime.Level == RuntimeLevel.Run)
throw new Exception("Umbraco is already configured!");
var creator = new DatabaseSchemaCreator(database, _logger, _umbracoVersion);
var creator = new DatabaseSchemaCreator(database, _loggerFactory.CreateLogger<DatabaseSchemaCreator>(), _loggerFactory, _umbracoVersion);
creator.InitializeDatabaseSchema();
message = message + "<p>Installation completed!</p>";
//now that everything is done, we need to determine the version of SQL server that is executing
_logger.Info<DatabaseBuilder>("Database configuration status: {DbConfigStatus}", message);
_logger.LogInformation("Database configuration status: {DbConfigStatus}", message);
return new Result { Message = message, Success = true, Percentage = "100" };
}
//we need to do an upgrade so return a new status message and it will need to be done during the next step
_logger.Info<DatabaseBuilder>("Database requires upgrade");
_logger.LogInformation("Database requires upgrade");
message = "<p>Upgrading database, this may take some time...</p>";
return new Result
{
@@ -411,17 +414,17 @@ namespace Umbraco.Core.Migrations.Install
return readyForInstall.Result;
}
_logger.Info<DatabaseBuilder>("Database upgrade started");
_logger.LogInformation("Database upgrade started");
// upgrade
var upgrader = new Upgrader(plan);
upgrader.Execute(_scopeProvider, _migrationBuilder, _keyValueService, _logger);
upgrader.Execute(_scopeProvider, _migrationBuilder, _keyValueService, _loggerFactory.CreateLogger<Upgrader>(), _loggerFactory);
var message = "<p>Upgrade completed!</p>";
//now that everything is done, we need to determine the version of SQL server that is executing
_logger.Info<DatabaseBuilder>("Database configuration status: {DbConfigStatus}", message);
_logger.LogInformation("Database configuration status: {DbConfigStatus}", message);
return new Result { Message = message, Success = true, Percentage = "100" };
}
@@ -448,11 +451,11 @@ namespace Umbraco.Core.Migrations.Install
private Result HandleInstallException(Exception ex)
{
_logger.Error<DatabaseBuilder>(ex, "Database configuration failed");
_logger.LogError(ex, "Database configuration failed");
if (_databaseSchemaValidationResult != null)
{
_logger.Info<DatabaseBuilder>("The database schema validation produced the following summary: {DbSchemaSummary}", _databaseSchemaValidationResult.GetSummary());
_logger.LogInformation("The database schema validation produced the following summary: {DbSchemaSummary}", _databaseSchemaValidationResult.GetSummary());
}
return new Result

View File

@@ -1,8 +1,8 @@
using System;
using Microsoft.Extensions.Logging;
using NPoco;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Logging;
using Umbraco.Core.Migrations.Upgrade;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence.Dtos;
@@ -15,10 +15,10 @@ namespace Umbraco.Core.Migrations.Install
internal class DatabaseDataCreator
{
private readonly IDatabase _database;
private readonly ILogger _logger;
private readonly ILogger<DatabaseDataCreator> _logger;
private readonly IUmbracoVersion _umbracoVersion;
public DatabaseDataCreator(IDatabase database, ILogger logger, IUmbracoVersion umbracoVersion)
public DatabaseDataCreator(IDatabase database, ILogger<DatabaseDataCreator> logger, IUmbracoVersion umbracoVersion)
{
_database = database;
_logger = logger;
@@ -32,7 +32,7 @@ namespace Umbraco.Core.Migrations.Install
/// <param name="tableName">Name of the table to create base data for</param>
public void InitializeBaseData(string tableName)
{
_logger.Info<DatabaseDataCreator>("Creating data in {TableName}", tableName);
_logger.LogInformation("Creating data in {TableName}", tableName);
if (tableName.Equals(Constants.DatabaseSchema.Tables.Node))
CreateNodeData();
@@ -76,7 +76,7 @@ namespace Umbraco.Core.Migrations.Install
if (tableName.Equals(Constants.DatabaseSchema.Tables.KeyValue))
CreateKeyValueData();
_logger.Info<DatabaseDataCreator>("Done creating table {TableName} data.", tableName);
_logger.LogInformation("Done creating table {TableName} data.", tableName);
}
private void CreateNodeData()

View File

@@ -1,11 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using NPoco;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.Dtos;
@@ -19,13 +19,15 @@ namespace Umbraco.Core.Migrations.Install
public class DatabaseSchemaCreator
{
private readonly IUmbracoDatabase _database;
private readonly ILogger _logger;
private readonly ILogger<DatabaseSchemaCreator> _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly IUmbracoVersion _umbracoVersion;
public DatabaseSchemaCreator(IUmbracoDatabase database, ILogger logger, IUmbracoVersion umbracoVersion)
public DatabaseSchemaCreator(IUmbracoDatabase database, ILogger<DatabaseSchemaCreator> logger, ILoggerFactory loggerFactory, IUmbracoVersion umbracoVersion)
{
_database = database;
_logger = logger;
_loggerFactory = loggerFactory;
_umbracoVersion = umbracoVersion;
}
@@ -92,14 +94,14 @@ namespace Umbraco.Core.Migrations.Install
/// </summary>
internal void UninstallDatabaseSchema()
{
_logger.Info<DatabaseSchemaCreator>("Start UninstallDatabaseSchema");
_logger.LogInformation("Start UninstallDatabaseSchema");
foreach (var table in OrderedTables.AsEnumerable().Reverse())
{
var tableNameAttribute = table.FirstAttribute<TableNameAttribute>();
var tableName = tableNameAttribute == null ? table.Name : tableNameAttribute.Value;
_logger.Info<DatabaseSchemaCreator>("Uninstall {TableName}", tableName);
_logger.LogInformation("Uninstall {TableName}", tableName);
try
{
@@ -110,7 +112,7 @@ namespace Umbraco.Core.Migrations.Install
{
//swallow this for now, not sure how best to handle this with diff databases... though this is internal
// and only used for unit tests. If this fails its because the table doesn't exist... generally!
_logger.Error<DatabaseSchemaCreator>(ex, "Could not drop table {TableName}", tableName);
_logger.LogError(ex, "Could not drop table {TableName}", tableName);
}
}
}
@@ -129,7 +131,7 @@ namespace Umbraco.Core.Migrations.Install
if (e.Cancel == false)
{
var dataCreation = new DatabaseDataCreator(_database, _logger, _umbracoVersion);
var dataCreation = new DatabaseDataCreator(_database, _loggerFactory.CreateLogger<DatabaseDataCreator>(), _umbracoVersion);
foreach (var table in OrderedTables)
CreateTable(false, table, dataCreation);
}
@@ -399,7 +401,7 @@ namespace Umbraco.Core.Migrations.Install
where T : new()
{
var tableType = typeof(T);
CreateTable(overwrite, tableType, new DatabaseDataCreator(_database, _logger, _umbracoVersion));
CreateTable(overwrite, tableType, new DatabaseDataCreator(_database, _loggerFactory.CreateLogger<DatabaseDataCreator>(), _umbracoVersion));
}
/// <summary>
@@ -435,7 +437,7 @@ namespace Umbraco.Core.Migrations.Install
var tableExist = TableExists(tableName);
if (overwrite && tableExist)
{
_logger.Info<DatabaseSchemaCreator>("Table {TableName} already exists, but will be recreated", tableName);
_logger.LogInformation("Table {TableName} already exists, but will be recreated", tableName);
DropTable(tableName);
tableExist = false;
@@ -444,19 +446,19 @@ namespace Umbraco.Core.Migrations.Install
if (tableExist)
{
// The table exists and was not recreated/overwritten.
_logger.Info<Database>("Table {TableName} already exists - no changes were made", tableName);
_logger.LogInformation("Table {TableName} already exists - no changes were made", tableName);
return;
}
//Execute the Create Table sql
var created = _database.Execute(new Sql(createSql));
_logger.Info<DatabaseSchemaCreator>("Create Table {TableName} ({Created}): \n {Sql}", tableName, created, createSql);
_logger.LogInformation("Create Table {TableName} ({Created}): \n {Sql}", tableName, created, createSql);
//If any statements exists for the primary key execute them here
if (string.IsNullOrEmpty(createPrimaryKeySql) == false)
{
var createdPk = _database.Execute(new Sql(createPrimaryKeySql));
_logger.Info<DatabaseSchemaCreator>("Create Primary Key ({CreatedPk}):\n {Sql}", createdPk, createPrimaryKeySql);
_logger.LogInformation("Create Primary Key ({CreatedPk}):\n {Sql}", createdPk, createPrimaryKeySql);
}
if (SqlSyntax.SupportsIdentityInsert() && tableDefinition.Columns.Any(x => x.IsIdentity))
@@ -474,23 +476,23 @@ namespace Umbraco.Core.Migrations.Install
foreach (var sql in indexSql)
{
var createdIndex = _database.Execute(new Sql(sql));
_logger.Info<DatabaseSchemaCreator>("Create Index ({CreatedIndex}):\n {Sql}", createdIndex, sql);
_logger.LogInformation("Create Index ({CreatedIndex}):\n {Sql}", createdIndex, sql);
}
//Loop through foreignkey statements and execute sql
foreach (var sql in foreignSql)
{
var createdFk = _database.Execute(new Sql(sql));
_logger.Info<DatabaseSchemaCreator>("Create Foreign Key ({CreatedFk}):\n {Sql}", createdFk, sql);
_logger.LogInformation("Create Foreign Key ({CreatedFk}):\n {Sql}", createdFk, sql);
}
if (overwrite)
{
_logger.Info<Database>("Table {TableName} was recreated", tableName);
_logger.LogInformation("Table {TableName} was recreated", tableName);
}
else
{
_logger.Info<Database>("New table {TableName} was created", tableName);
_logger.LogInformation("New table {TableName} was created", tableName);
}
}

View File

@@ -1,6 +1,6 @@
using System;
using NPoco;
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Migrations.Expressions.Alter;
using Umbraco.Core.Migrations.Expressions.Create;
using Umbraco.Core.Migrations.Expressions.Delete;

View File

@@ -1,6 +1,6 @@
using System;
using System.Collections.Generic;
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Persistence;
namespace Umbraco.Core.Migrations
@@ -13,14 +13,14 @@ namespace Umbraco.Core.Migrations
/// <summary>
/// Initializes a new instance of the <see cref="MigrationContext"/> class.
/// </summary>
public MigrationContext(IUmbracoDatabase database, ILogger logger)
public MigrationContext(IUmbracoDatabase database, ILogger<MigrationContext> logger)
{
Database = database ?? throw new ArgumentNullException(nameof(database));
Logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
/// <inheritdoc />
public ILogger Logger { get; }
public ILogger<IMigrationContext> Logger { get; }
/// <inheritdoc />
public IUmbracoDatabase Database { get; }

View File

@@ -2,8 +2,8 @@
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Extensions.Logging;
using NPoco;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.SqlSyntax;
@@ -55,7 +55,7 @@ namespace Umbraco.Core.Migrations
if (string.IsNullOrWhiteSpace(sql))
{
Logger.Info(GetType(), "SQL [{ContextIndex}]: <empty>", Context.Index);
Logger.LogInformation("SQL [{ContextIndex}]: <empty>", Context.Index);
}
else
{
@@ -96,11 +96,11 @@ namespace Umbraco.Core.Migrations
if (sql == null)
{
Logger.Info(GetType(), $"SQL [{Context.Index}]: <empty>");
Logger.LogInformation($"SQL [{Context.Index}]: <empty>");
}
else
{
Logger.Info(GetType(), $"SQL [{Context.Index}]: {sql.ToText()}");
Logger.LogInformation($"SQL [{Context.Index}]: {sql.ToText()}");
Database.Execute(sql);
}
@@ -116,7 +116,7 @@ namespace Umbraco.Core.Migrations
private void ExecuteStatement(StringBuilder stmtBuilder)
{
var stmt = stmtBuilder.ToString();
Logger.Info(GetType(), "SQL [{ContextIndex}]: {Sql}", Context.Index, stmt);
Logger.LogInformation("SQL [{ContextIndex}]: {Sql}", Context.Index, stmt);
Database.Execute(stmt);
stmtBuilder.Clear();
}

View File

@@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Scoping;
using Type = System.Type;
@@ -285,30 +285,31 @@ namespace Umbraco.Core.Migrations
/// <param name="fromState">The state to start execution at.</param>
/// <param name="migrationBuilder">A migration builder.</param>
/// <param name="logger">A logger.</param>
/// <param name="loggerFactory"></param>
/// <returns>The final state.</returns>
/// <remarks>The plan executes within the scope, which must then be completed.</remarks>
public string Execute(IScope scope, string fromState, IMigrationBuilder migrationBuilder, ILogger logger)
public string Execute(IScope scope, string fromState, IMigrationBuilder migrationBuilder, ILogger<MigrationPlan> logger, ILoggerFactory loggerFactory)
{
Validate();
if (migrationBuilder == null) throw new ArgumentNullException(nameof(migrationBuilder));
if (logger == null) throw new ArgumentNullException(nameof(logger));
logger.Info<MigrationPlan>("Starting '{MigrationName}'...", Name);
logger.LogInformation("Starting '{MigrationName}'...", Name);
var origState = fromState ?? string.Empty;
logger.Info<MigrationPlan>("At {OrigState}", string.IsNullOrWhiteSpace(origState) ? "origin": origState);
logger.LogInformation("At {OrigState}", string.IsNullOrWhiteSpace(origState) ? "origin": origState);
if (!_transitions.TryGetValue(origState, out var transition))
ThrowOnUnknownInitialState(origState);
var context = new MigrationContext(scope.Database, logger);
var context = new MigrationContext(scope.Database, loggerFactory.CreateLogger<MigrationContext>());
context.PostMigrations.AddRange(_postMigrationTypes);
while (transition != null)
{
logger.Info<MigrationPlan>("Execute {MigrationType}", transition.MigrationType.Name);
logger.LogInformation("Execute {MigrationType}", transition.MigrationType.Name);
var migration = migrationBuilder.Build(transition.MigrationType, context);
migration.Migrate();
@@ -316,7 +317,7 @@ namespace Umbraco.Core.Migrations
var nextState = transition.TargetState;
origState = nextState;
logger.Info<MigrationPlan>("At {OrigState}", origState);
logger.LogInformation("At {OrigState}", origState);
// throw a raw exception here: this should never happen as the plan has
// been validated - this is just a paranoid safety test
@@ -333,12 +334,12 @@ namespace Umbraco.Core.Migrations
// run post-migrations
foreach (var postMigrationType in postMigrationTypes)
{
logger.Info<MigrationPlan>($"PostMigration: {postMigrationType.FullName}.");
logger.LogInformation($"PostMigration: {postMigrationType.FullName}.");
var postMigration = migrationBuilder.Build(postMigrationType, context);
postMigration.Migrate();
}
logger.Info<MigrationPlan>("Done (pending scope completion).");
logger.LogInformation("Done (pending scope completion).");
// safety check - again, this should never happen as the plan has been validated,
// and this is just a paranoid safety test

View File

@@ -1,5 +1,5 @@
using System;
using Umbraco.Core.Logging;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Scoping;
using Umbraco.Core.Services;
@@ -40,7 +40,8 @@ namespace Umbraco.Core.Migrations.Upgrade
/// <param name="migrationBuilder">A migration builder.</param>
/// <param name="keyValueService">A key-value service.</param>
/// <param name="logger">A logger.</param>
public void Execute(IScopeProvider scopeProvider, IMigrationBuilder migrationBuilder, IKeyValueService keyValueService, ILogger logger)
/// <param name="loggerFactory">A logger factory</param>
public void Execute(IScopeProvider scopeProvider, IMigrationBuilder migrationBuilder, IKeyValueService keyValueService, ILogger<Upgrader> logger, ILoggerFactory loggerFactory)
{
if (scopeProvider == null) throw new ArgumentNullException(nameof(scopeProvider));
if (migrationBuilder == null) throw new ArgumentNullException(nameof(migrationBuilder));
@@ -64,7 +65,7 @@ namespace Umbraco.Core.Migrations.Upgrade
}
// execute plan
var state = plan.Execute(scope, currentState, migrationBuilder, logger);
var state = plan.Execute(scope, currentState, migrationBuilder, loggerFactory.CreateLogger<MigrationPlan>(), loggerFactory);
if (string.IsNullOrWhiteSpace(state))
throw new Exception("Plan execution returned an invalid null or empty state.");
@@ -83,13 +84,13 @@ namespace Umbraco.Core.Migrations.Upgrade
/// <summary>
/// Executes as part of the upgrade scope and before all migrations have executed.
/// </summary>
public virtual void BeforeMigrations(IScope scope, ILogger logger)
public virtual void BeforeMigrations(IScope scope, ILogger<Upgrader> logger)
{ }
/// <summary>
/// Executes as part of the upgrade scope and after all migrations have executed.
/// </summary>
public virtual void AfterMigrations(IScope scope, ILogger logger)
public virtual void AfterMigrations(IScope scope, ILogger<Upgrader> logger)
{ }
}

View File

@@ -2,8 +2,8 @@
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
using Umbraco.Core.Migrations.Upgrade.V_8_0_0.DataTypes;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Dtos;
@@ -17,7 +17,7 @@ namespace Umbraco.Core.Migrations.Upgrade.V_8_0_0
{
private readonly PreValueMigratorCollection _preValueMigrators;
private readonly PropertyEditorCollection _propertyEditors;
private readonly ILogger _logger;
private readonly ILogger<DataTypeMigration> _logger;
private static readonly ISet<string> LegacyAliases = new HashSet<string>()
{
@@ -31,7 +31,7 @@ namespace Umbraco.Core.Migrations.Upgrade.V_8_0_0
Constants.PropertyEditors.Legacy.Aliases.MultiNodeTreePicker2,
};
public DataTypeMigration(IMigrationContext context, PreValueMigratorCollection preValueMigrators, PropertyEditorCollection propertyEditors, ILogger logger)
public DataTypeMigration(IMigrationContext context, PreValueMigratorCollection preValueMigrators, PropertyEditorCollection propertyEditors, ILogger<DataTypeMigration> logger)
: base(context)
{
_preValueMigrators = preValueMigrators;
@@ -94,7 +94,7 @@ namespace Umbraco.Core.Migrations.Upgrade.V_8_0_0
{
if (!LegacyAliases.Contains(dataType.EditorAlias))
{
_logger.Warn<DataTypeMigration>(
_logger.LogWarning(
"Skipping validation of configuration for data type {NodeId} : {EditorAlias}."
+ " Please ensure that the configuration is valid. The site may fail to start and / or load data types and run.",
dataType.NodeId, dataType.EditorAlias);
@@ -104,7 +104,7 @@ namespace Umbraco.Core.Migrations.Upgrade.V_8_0_0
{
if (!LegacyAliases.Contains(newAlias))
{
_logger.Warn<DataTypeMigration>("Skipping validation of configuration for data type {NodeId} : {NewEditorAlias} (was: {EditorAlias})"
_logger.LogWarning("Skipping validation of configuration for data type {NodeId} : {NewEditorAlias} (was: {EditorAlias})"
+ " because no property editor with that alias was found."
+ " Please ensure that the configuration is valid. The site may fail to start and / or load data types and run.",
dataType.NodeId, newAlias, dataType.EditorAlias);
@@ -119,7 +119,7 @@ namespace Umbraco.Core.Migrations.Upgrade.V_8_0_0
}
catch (Exception e)
{
_logger.Warn<DataTypeMigration>(e, "Failed to validate configuration for data type {NodeId} : {NewEditorAlias} (was: {EditorAlias})."
_logger.LogWarning(e, "Failed to validate configuration for data type {NodeId} : {NewEditorAlias} (was: {EditorAlias})."
+ " Please fix the configuration and ensure it is valid. The site may fail to start and / or load data types and run.",
dataType.NodeId, newAlias, dataType.EditorAlias);
}

View File

@@ -1,25 +1,25 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
namespace Umbraco.Core.Migrations.Upgrade.V_8_0_0.DataTypes
{
public class PreValueMigratorCollection : BuilderCollectionBase<IPreValueMigrator>
{
private readonly ILogger _logger;
private readonly ILogger<PreValueMigratorCollection> _logger;
public PreValueMigratorCollection(IEnumerable<IPreValueMigrator> items, ILogger logger)
public PreValueMigratorCollection(IEnumerable<IPreValueMigrator> items, ILogger<PreValueMigratorCollection> logger)
: base(items)
{
_logger = logger;
_logger.Debug(GetType(), "Migrators: " + string.Join(", ", items.Select(x => x.GetType().Name)));
_logger.LogDebug("Migrators: " + string.Join(", ", items.Select(x => x.GetType().Name)));
}
public IPreValueMigrator GetMigrator(string editorAlias)
{
var migrator = this.FirstOrDefault(x => x.CanMigrate(editorAlias));
_logger.Debug(GetType(), "Getting migrator for \"{EditorAlias}\" = {MigratorType}", editorAlias, migrator == null ? "<null>" : migrator.GetType().Name);
_logger.LogDebug("Getting migrator for \"{EditorAlias}\" = {MigratorType}", editorAlias, migrator == null ? "<null>" : migrator.GetType().Name);
return migrator;
}
}

View File

@@ -1,11 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Core.IO;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Dtos;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Logging;
using Umbraco.Core.Migrations.PostMigrations;
using Umbraco.Core.Models;
@@ -51,7 +51,7 @@ namespace Umbraco.Core.Migrations.Upgrade.V_8_0_0
}
catch (Exception ex)
{
Logger.Error<DropDownPropertyEditorsMigration>(
Logger.LogError(
ex, "Invalid configuration: \"{Configuration}\", cannot convert editor.",
dataType.Configuration);

Some files were not shown because too many files have changed in this diff Show More