Update more logging messages to use templates as opposed to string formats that were using the LoggerExtensions <T>

This commit is contained in:
Warren
2018-08-16 12:00:12 +01:00
parent d632b46f9a
commit 47c8651609
24 changed files with 88 additions and 60 deletions

View File

@@ -40,13 +40,15 @@ namespace Umbraco.Core.Configuration.Grid
var gridConfig = Path.Combine(_configFolder.FullName, "grid.editors.config.js");
if (File.Exists(gridConfig))
{
var sourceString = File.ReadAllText(gridConfig);
try
{
editors.AddRange(parser.ParseGridEditors(File.ReadAllText(gridConfig)));
editors.AddRange(parser.ParseGridEditors(sourceString));
}
catch (Exception ex)
{
_logger.Error<GridEditorsConfig>("Could not parse the contents of grid.editors.config.js into a JSON array", ex);
_logger.Error<GridEditorsConfig>("Could not parse the contents of grid.editors.config.js into a JSON array '{Json}", ex, sourceString);
}
}

View File

@@ -111,7 +111,7 @@ namespace Umbraco.Core.IO
}
catch (Exception e)
{
Logger.Error<MediaFileSystem>("Failed to delete attached file \"" + file + "\".", e);
Logger.Error<MediaFileSystem>("Failed to delete attached file '{File}'", e, file);
}
});
}

View File

@@ -73,11 +73,11 @@ namespace Umbraco.Core.IO
}
catch (UnauthorizedAccessException ex)
{
Current.Logger.Error<PhysicalFileSystem>("Not authorized to get directories", ex);
Current.Logger.Error<PhysicalFileSystem>("Not authorized to get directories for '{Path}'", ex, fullPath);
}
catch (DirectoryNotFoundException ex)
{
Current.Logger.Error<PhysicalFileSystem>("Directory not found", ex);
Current.Logger.Error<PhysicalFileSystem>("Directory not found for '{Path}'", ex, fullPath);
}
return Enumerable.Empty<string>();
@@ -109,7 +109,7 @@ namespace Umbraco.Core.IO
}
catch (DirectoryNotFoundException ex)
{
Current.Logger.Error<PhysicalFileSystem>("Directory not found", ex);
Current.Logger.Error<PhysicalFileSystem>("Directory not found for '{Path}'", ex, fullPath);
}
}
@@ -189,11 +189,11 @@ namespace Umbraco.Core.IO
}
catch (UnauthorizedAccessException ex)
{
Current.Logger.Error<PhysicalFileSystem>("Not authorized to get directories", ex);
Current.Logger.Error<PhysicalFileSystem>("Not authorized to get directories for '{Path}'", ex, fullPath);
}
catch (DirectoryNotFoundException ex)
{
Current.Logger.Error<PhysicalFileSystem>("Directory not found", ex);
Current.Logger.Error<PhysicalFileSystem>("Directory not found for '{FullPath}'", ex, fullPath);
}
return Enumerable.Empty<string>();

View File

@@ -14,7 +14,6 @@ namespace Umbraco.Core.Logging
/// <param name="logger">The logger.</param>
/// <param name="message">A message.</param>
/// <param name="exception">An exception.</param>
//[Obsolete("Use the Error<T> with message template", true)]
public static void Error<T>(this ILogger logger, string message, Exception exception = null)
{
logger.Error(typeof(T), message, exception);

View File

@@ -81,7 +81,7 @@ namespace Umbraco.Core.Manifest
}
catch (Exception e)
{
_logger.Error<ManifestParser>($"Failed to parse manifest at \"{path}\", ignoring.", e);
_logger.Error<ManifestParser>($"Failed to parse manifest at '{Path}', ignoring.", e, path);
}
}

View File

@@ -54,7 +54,7 @@ namespace Umbraco.Core.Manifest
if (_isRestarting) return;
_isRestarting = true;
_logger.Info<ManifestWatcher>("manifest has changed, app pool is restarting (" + e.FullPath + ")");
_logger.Info<ManifestWatcher>("Manifest has changed, app pool is restarting ({Path})", e.FullPath);
HttpRuntime.UnloadAppDomain();
Dispose(); // uh? if the app restarts then this should be disposed anyways?
}

View File

@@ -109,7 +109,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>("Could not drop table " + tableName, ex);
_logger.Error<DatabaseSchemaCreator>("Could not drop table {TableName}", ex, tableName);
}
}
}

View File

@@ -41,7 +41,7 @@ namespace Umbraco.Core.Models
}
catch (Exception ex)
{
logger.Error<ImageCropperValueConverter>("Could not parse the string " + jsonString + " to a json object", ex);
logger.Error<ImageCropperValueConverter>("Could not parse the string '{JsonString}' to a json object", ex, jsonString);
return string.Empty;
}
}

View File

@@ -552,9 +552,15 @@ namespace Umbraco.Core.Models
private Attempt<T> WarnIfPropertyTypeNotFoundOnGet<T>(string propertyAlias, string propertyName, T defaultVal)
{
void DoLog(string logPropertyAlias, string logPropertyName)
=> Current.Logger.Warn<Member>($"Trying to access the '{logPropertyName}' property on " + typeof(Member)
+ $" but the {logPropertyAlias} property does not exist on the member type so a default value is returned. Ensure that you have a property type with alias: "
+ logPropertyAlias + $" configured on your member type in order to use the '{logPropertyName}' property on the model correctly.");
{
//WB: TODO Check that we do not need to specify properties again if used later on again in message template
Current.Logger.Warn<Member>("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,
typeof(Member),
logPropertyAlias);
}
// if the property doesn't exist,
if (Properties.Contains(propertyAlias) == false)
@@ -572,8 +578,13 @@ namespace Umbraco.Core.Models
private bool WarnIfPropertyTypeNotFoundOnSet(string propertyAlias, string propertyName)
{
void DoLog(string logPropertyAlias, string logPropertyName)
=> Current.Logger.Warn<Member>($"An attempt was made to set a value on the property '{logPropertyName}' on type " + typeof(Member)
+ $" but the property type {logPropertyAlias} does not exist on the member type, ensure that this property type exists so that setting this property works correctly.");
{
Current.Logger.Warn<Member>("An attempt was made to set a value on the property '{PropertyName}' on type typeof(Member) 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),
logPropertyAlias);
}
// if the property doesn't exist,
if (Properties.Contains(propertyAlias) == false)

View File

@@ -192,7 +192,7 @@ namespace Umbraco.Core.Packaging
assemblyName.Name,
"' see error log for full details."));
assembliesWithErrors.Add(a);
Current.Logger.Error<PackageBinaryInspector>("An error occurred scanning package assemblies", ex);
Current.Logger.Error<PackageBinaryInspector>("An error occurred scanning package assembly '{AssemblyName}'", ex, assemblyName.FullName);
}
}
}
@@ -236,7 +236,7 @@ namespace Umbraco.Core.Packaging
a.GetName().Name,
"' see error log for full details."));
assembliesWithErrors.Add(a);
Current.Logger.Error<PackageBinaryInspector>("An error occurred scanning package assemblies", ex);
Current.Logger.Error<PackageBinaryInspector>("An error occurred scanning package assembly '{AssemblyName}'", ex, a.GetName().FullName);
}
}

View File

@@ -487,10 +487,9 @@ namespace Umbraco.Core.Persistence.Repositories.Implement
if (result.ContainsKey(temp.VersionId))
{
var msg = $"The query returned multiple property sets for content {temp.Id}, {temp.ContentType.Name}";
if (ContentRepositoryBase.ThrowOnWarning)
throw new InvalidOperationException(msg);
Logger.Warn<ContentRepositoryBase<TId, TEntity, TRepository>>(msg);
throw new InvalidOperationException($"The query returned multiple property sets for content {temp.Id}, {temp.ContentType.Name}");
Logger.Warn<ContentRepositoryBase<TId, TEntity, TRepository>>("The query returned multiple property sets for content {ContentId}, {ContentTypeName}", temp.Id, temp.ContentType.Name);
}
result[temp.VersionId] = new PropertyCollection(properties);

View File

@@ -227,9 +227,8 @@ namespace Umbraco.Core.Persistence.Repositories.Implement
{
if (string.IsNullOrWhiteSpace(entity.Alias))
{
var m = $"ContentType '{entity.Name}' cannot have an empty Alias. This is most likely due to invalid characters stripped from the Alias.";
var e = new Exception(m);
Logger.Error<ContentTypeRepository>(m, e);
var e = new Exception($"ContentType '{entity.Name}' cannot have an empty Alias. This is most likely due to invalid characters stripped from the Alias.");
Logger.Error<ContentTypeRepository>("ContentType '{EntityName}' cannot have an empty Alias. This is most likely due to invalid characters stripped from the Alias.", e, entity.Name);
throw e;
}

View File

@@ -521,9 +521,12 @@ AND umbracoNode.id <> @id",
{
if (string.IsNullOrWhiteSpace(pt.Alias))
{
var m = $"Property Type '{pt.Name}' cannot have an empty Alias. This is most likely due to invalid characters stripped from the Alias.";
var e = new InvalidOperationException(m);
Logger.Error<ContentTypeRepositoryBase<TEntity>>(m, e);
var e = new InvalidOperationException($"Property Type '{pt.Name}' cannot have an empty Alias. This is most likely due to invalid characters stripped from the Alias.");
Logger.Error<ContentTypeRepositoryBase<TEntity>>(
"Property Type '{PropertyTypeName}' cannot have an empty Alias. This is most likely due to invalid characters stripped from the Alias.",
e, pt.Name);
throw e;
}
}
@@ -532,10 +535,14 @@ AND umbracoNode.id <> @id",
{
if (string.IsNullOrWhiteSpace(entity.Alias))
{
var m = $"{typeof(TEntity).Name} '{entity.Name}' cannot have an empty Alias. This is most likely due to invalid characters stripped from the Alias.";
var e = new InvalidOperationException(m);
Logger.Error<ContentTypeRepositoryBase<TEntity>>(m, e);
throw e;
var ex = new InvalidOperationException($"{typeof(TEntity).Name} '{entity.Name}' cannot have an empty Alias. This is most likely due to invalid characters stripped from the Alias.");
Logger.Error<ContentTypeRepositoryBase<TEntity>>("{EntityTypeName} '{EntityName}' cannot have an empty Alias. This is most likely due to invalid characters stripped from the Alias.",
ex,
typeof(TEntity).Name,
entity.Name);
throw ex;
}
}

View File

@@ -190,13 +190,13 @@ namespace Umbraco.Core.Persistence
}
#endif
protected override void OnException(Exception x)
protected override void OnException(Exception ex)
{
_logger.Error<UmbracoDatabase>("Exception (" + InstanceId + ").", x);
_logger.Error<UmbracoDatabase>("Exception ({InstanceId}).", ex, InstanceId);
_logger.Debug<UmbracoDatabase>("At:\r\n{StackTrace}", Environment.StackTrace);
if (EnableSqlTrace == false)
_logger.Debug<UmbracoDatabase>("Sql:\r\n{Sql}", CommandToString(LastSQL, LastArgs));
base.OnException(x);
base.OnException(ex);
}
private DbCommand _cmd;

View File

@@ -100,7 +100,7 @@ namespace Umbraco.Core.PropertyEditors.ValueConverters
}
catch (Exception ex)
{
Current.Logger.Error<GridValueConverter>("Could not parse the string " + sourceString + " to a json object", ex);
Current.Logger.Error<GridValueConverter>("Could not parse the string '{JsonString}' to a json object", ex, sourceString);
}
}

View File

@@ -43,7 +43,7 @@ namespace Umbraco.Core.PropertyEditors.ValueConverters
catch (Exception ex)
{
// cannot deserialize, assume it may be a raw image url
Current.Logger.Error<ImageCropperValueConverter>($"Could not deserialize string \"{sourceString}\" into an image cropper value.", ex);
Current.Logger.Error<ImageCropperValueConverter>("Could not deserialize string '{JsonString}' into an image cropper value.", ex, sourceString);
value = new ImageCropperValue { Src = sourceString };
}

View File

@@ -57,7 +57,7 @@ namespace Umbraco.Core.PropertyEditors.ValueConverters
}
catch (Exception ex)
{
Current.Logger.Error<JsonValueConverter>("Could not parse the string " + sourceString + " to a json object", ex);
Current.Logger.Error<JsonValueConverter>("Could not parse the string '{JsonString}' to a json object", ex, sourceString);
}
}

View File

@@ -1240,11 +1240,11 @@ namespace Umbraco.Core.Services.Implement
d.PublishCulture(); // fixme variants?
result = SaveAndPublish(d, userId: d.WriterId);
if (result.Success == false)
Logger.Error<ContentService>($"Failed to publish document id={d.Id}, reason={result.Result}.");
Logger.Error<ContentService>("Failed to publish document id={DocumentId}, reason={Reason}.", null, d.Id, result.Result);
}
catch (Exception e)
{
Logger.Error<ContentService>($"Failed to publish document id={d.Id}, an exception was thrown.", e);
Logger.Error<ContentService>("Failed to publish document id={DocumentId}, an exception was thrown.", e, d.Id);
throw;
}
yield return result;
@@ -1256,11 +1256,11 @@ namespace Umbraco.Core.Services.Implement
d.ExpireDate = null;
var result = Unpublish(d, userId: d.WriterId);
if (result.Success == false)
Logger.Error<ContentService>($"Failed to unpublish document id={d.Id}, reason={result.Result}.");
Logger.Error<ContentService>("Failed to unpublish document id={DocumentId}, reason={Reason}.", null, d.Id, result.Result);
}
catch (Exception e)
{
Logger.Error<ContentService>($"Failed to unpublish document id={d.Id}, an exception was thrown.", e);
Logger.Error<ContentService>("Failed to unpublish document id={DocumentId}, an exception was thrown.", e, d.Id);
throw;
}
}
@@ -1439,7 +1439,7 @@ namespace Umbraco.Core.Services.Implement
// fixme not going to work, do it differently
_mediaFileSystem.DeleteFiles(args.MediaFilesToDelete, // remove flagged files
(file, e) => Logger.Error<ContentService>("An error occurred while deleting file attached to nodes: " + file, e));
(file, e) => Logger.Error<ContentService>("An error occurred while deleting file attached to nodes: {File}", e, file));
}
}

View File

@@ -204,7 +204,7 @@ namespace Umbraco.Core.Services.Implement
}
catch (Exception ex)
{
_logger.Error<LocalizedTextServiceFileSources>("Could not load file into XML " + supplementaryFile.File.FullName, ex);
_logger.Error<LocalizedTextServiceFileSources>("Could not load file into XML {File}", ex, supplementaryFile.File.FullName);
continue;
}

View File

@@ -892,7 +892,7 @@ namespace Umbraco.Core.Services.Implement
scope.Events.Dispatch(Deleted, this, args);
_mediaFileSystem.DeleteFiles(args.MediaFilesToDelete, // remove flagged files
(file, e) => Logger.Error<MediaService>("An error occurred while deleting file attached to nodes: " + file, e));
(file, e) => Logger.Error<MediaService>("An error occurred while deleting file attached to nodes: {File}", e, file));
}
}

View File

@@ -930,7 +930,7 @@ namespace Umbraco.Core.Services.Implement
// fixme - this is MOOT because the event will not trigger immediately
// it's been refactored already (think it's the dispatcher that deals with it?)
_mediaFileSystem.DeleteFiles(args.MediaFilesToDelete, // remove flagged files
(file, e) => Logger.Error<MemberService>("An error occurred while deleting file attached to nodes: " + file, e));
(file, e) => Logger.Error<MemberService>("An error occurred while deleting file attached to nodes: {File}", e, file));
}
#endregion

View File

@@ -491,7 +491,7 @@ namespace Umbraco.Core.Services.Implement
var tryCreateFolder = _contentTypeService.CreateContainer(-1, rootFolder);
if (tryCreateFolder == false)
{
_logger.Error<PackagingService>("Could not create folder: " + rootFolder, tryCreateFolder.Exception);
_logger.Error<PackagingService>("Could not create folder: {FolderName}", tryCreateFolder.Exception, rootFolder);
throw tryCreateFolder.Exception;
}
var rootFolderId = tryCreateFolder.Result.Entity.Id;
@@ -525,7 +525,7 @@ namespace Umbraco.Core.Services.Implement
var tryCreateFolder = _contentTypeService.CreateContainer(current.Id, folderName);
if (tryCreateFolder == false)
{
_logger.Error<PackagingService>("Could not create folder: " + folderName, tryCreateFolder.Exception);
_logger.Error<PackagingService>("Could not create folder: {FolderName}", tryCreateFolder.Exception, folderName);
throw tryCreateFolder.Exception;
}
return _contentTypeService.GetContainer(tryCreateFolder.Result.Entity.Id);
@@ -949,7 +949,7 @@ namespace Umbraco.Core.Services.Implement
var tryCreateFolder = _dataTypeService.CreateContainer(-1, rootFolder);
if (tryCreateFolder == false)
{
_logger.Error<PackagingService>("Could not create folder: " + rootFolder, tryCreateFolder.Exception);
_logger.Error<PackagingService>("Could not create folder: {FolderName}", tryCreateFolder.Exception, rootFolder);
throw tryCreateFolder.Exception;
}
current = _dataTypeService.GetContainer(tryCreateFolder.Result.Entity.Id);
@@ -982,7 +982,7 @@ namespace Umbraco.Core.Services.Implement
var tryCreateFolder = _dataTypeService.CreateContainer(current.Id, folderName);
if (tryCreateFolder == false)
{
_logger.Error<PackagingService>("Could not create folder: " + folderName, tryCreateFolder.Exception);
_logger.Error<PackagingService>("Could not create folder: {FolderName}", tryCreateFolder.Exception, folderName);
throw tryCreateFolder.Exception;
}
return _dataTypeService.GetContainer(tryCreateFolder.Result.Entity.Id);
@@ -1529,7 +1529,10 @@ namespace Umbraco.Core.Services.Implement
else if (string.IsNullOrEmpty((string)elementCopy.Element("Master")) == false &&
templateElements.Any(x => (string)x.Element("Alias") == (string)elementCopy.Element("Master")) == false)
{
_logger.Info<PackagingService>(string.Format("Template '{0}' has an invalid Master '{1}', so the reference has been ignored.", (string)elementCopy.Element("Alias"), (string)elementCopy.Element("Master")));
_logger.Info<PackagingService>(
"Template '{TemplateAlias}' has an invalid Master '{TemplateMaster}', so the reference has been ignored.",
(string) elementCopy.Element("Alias"),
(string) elementCopy.Element("Master"));
}
graph.AddItem(TopoGraph.CreateNode((string) elementCopy.Element("Alias"), elementCopy, dependencies));

View File

@@ -352,7 +352,11 @@ namespace Umbraco.Core.Sync
}
catch (JsonException ex)
{
Logger.Error<DatabaseServerMessenger>($"Failed to deserialize instructions ({dto.Id}: \"{dto.Instructions}\").", ex);
Logger.Error<DatabaseServerMessenger>("Failed to deserialize instructions ({DtoId}: '{DtoInstructions}').",
ex,
dto.Id,
dto.Instructions);
lastId = dto.Id; // skip
continue;
}
@@ -408,7 +412,10 @@ namespace Umbraco.Core.Sync
catch (Exception ex)
{
Logger.Error<DatabaseServerMessenger>(
$"DISTRIBUTED CACHE IS NOT UPDATED. Failed to execute instructions ({dto.Id}: \"{dto.Instructions}\"). Instruction is being skipped/ignored", ex);
"DISTRIBUTED CACHE IS NOT UPDATED. Failed to execute instructions ({DtoId}: '{DtoInstructions}'). Instruction is being skipped/ignored",
ex,
dto.Id,
dto.Instructions);
//we cannot throw here because this invalid instruction will just keep getting processed over and over and errors
// will be thrown over and over. The only thing we can do is ignore and move on.

View File

@@ -185,14 +185,15 @@ namespace Umbraco.Core
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField,
null, runtime, null);
var shutdownMsg = $"Application shutdown. Details: {HostingEnvironment.ShutdownReason}\r\n\r\n_shutDownMessage={shutDownMessage}\r\n\r\n_shutDownStack={shutDownStack}";
logger.Info<UmbracoApplicationBase>(shutdownMsg);
logger.Info<UmbracoApplicationBase>("Application shutdown. Details: {ShutdownReason}\r\n\r\n_shutDownMessage={ShutdownMessage}\r\n\r\n_shutDownStack={ShutdownStack}",
HostingEnvironment.ShutdownReason,
shutDownMessage,
shutDownStack);
}
catch (Exception)
{
//if for some reason that fails, then log the normal output
logger.Info<UmbracoApplicationBase>("Application shutdown. Reason: " + HostingEnvironment.ShutdownReason);
logger.Info<UmbracoApplicationBase>("Application shutdown. Reason: {ShutdownReason}", HostingEnvironment.ShutdownReason);
}
}
@@ -224,7 +225,7 @@ namespace Umbraco.Core
// ignore HTTP errors
if (exception.GetType() == typeof(HttpException)) return;
Current.Logger.Error<UmbracoApplicationBase>("An unhandled exception occurred.", exception);
Current.Logger.Error<UmbracoApplicationBase>("An unhandled exception occurred", exception);
}
// called by ASP.NET (auto event wireup) at any phase in the application life cycle
@@ -247,7 +248,7 @@ namespace Umbraco.Core
}
catch (Exception ex)
{
Current.Logger.Error<UmbracoApplicationBase>($"Error in {name} handler.", ex);
Current.Logger.Error<UmbracoApplicationBase>("Error in {Name} handler.", ex, name);
throw;
}
}