diff --git a/Source/ACE.Common/Logging/LogExtensions.cs b/Source/ACE.Common/Logging/LogExtensions.cs deleted file mode 100644 index e9aa3ac14b..0000000000 --- a/Source/ACE.Common/Logging/LogExtensions.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System; -using System.Globalization; - -using Microsoft.Extensions.Logging; - -namespace ACE.Common.Logging -{ - /// - /// A log4net-shaped surface over Microsoft.Extensions.Logging.ILogger, so existing call sites compile - /// unchanged while the underlying logger is Microsoft's abstraction. - /// Pre-formatted text is always passed as the {Message} property, never as the message template: a message - /// that happens to contain braces (packet dumps, JSON, exception text) would otherwise be parsed as a - /// template and throw at format time. The ':l' format renders it literally (no quotes) under Serilog. - /// Every method checks IsEnabled before doing anything else, so a disabled level costs one check and no - /// allocation. The LoggerMessage.Define delegates are compiled once; nothing is parsed per call. - /// - public static class LogExtensions - { - private static readonly Action WriteDebug = LoggerMessage.Define(LogLevel.Debug, default, "{Message:l}"); - private static readonly Action WriteInfo = LoggerMessage.Define(LogLevel.Information, default, "{Message:l}"); - private static readonly Action WriteWarn = LoggerMessage.Define(LogLevel.Warning, default, "{Message:l}"); - private static readonly Action WriteError = LoggerMessage.Define(LogLevel.Error, default, "{Message:l}"); - private static readonly Action WriteFatal = LoggerMessage.Define(LogLevel.Critical, default, "{Message:l}"); - - extension(ILogger log) - { - public bool IsDebugEnabled => log.IsEnabled(LogLevel.Debug); - public bool IsInfoEnabled => log.IsEnabled(LogLevel.Information); - public bool IsWarnEnabled => log.IsEnabled(LogLevel.Warning); - public bool IsErrorEnabled => log.IsEnabled(LogLevel.Error); - public bool IsFatalEnabled => log.IsEnabled(LogLevel.Critical); - } - - // object, not string: log4net's ILog takes object, and call sites pass exceptions (log.Error(ex)) and other non-strings. - public static void Debug(this ILogger log, object message) => Write(log, LogLevel.Debug, WriteDebug, message, null); - public static void Debug(this ILogger log, object message, Exception exception) => Write(log, LogLevel.Debug, WriteDebug, message, exception); - public static void Info (this ILogger log, object message) => Write(log, LogLevel.Information, WriteInfo, message, null); - public static void Info (this ILogger log, object message, Exception exception) => Write(log, LogLevel.Information, WriteInfo, message, exception); - public static void Warn (this ILogger log, object message) => Write(log, LogLevel.Warning, WriteWarn, message, null); - public static void Warn (this ILogger log, object message, Exception exception) => Write(log, LogLevel.Warning, WriteWarn, message, exception); - public static void Error(this ILogger log, object message) => Write(log, LogLevel.Error, WriteError, message, null); - public static void Error(this ILogger log, object message, Exception exception) => Write(log, LogLevel.Error, WriteError, message, exception); - public static void Fatal(this ILogger log, object message) => Write(log, LogLevel.Critical, WriteFatal, message, null); - public static void Fatal(this ILogger log, object message, Exception exception) => Write(log, LogLevel.Critical, WriteFatal, message, exception); - - public static void DebugFormat(this ILogger log, string format, params object[] args) => WriteFormat(log, LogLevel.Debug, WriteDebug, format, args); - public static void InfoFormat (this ILogger log, string format, params object[] args) => WriteFormat(log, LogLevel.Information, WriteInfo, format, args); - public static void WarnFormat (this ILogger log, string format, params object[] args) => WriteFormat(log, LogLevel.Warning, WriteWarn, format, args); - public static void ErrorFormat(this ILogger log, string format, params object[] args) => WriteFormat(log, LogLevel.Error, WriteError, format, args); - public static void FatalFormat(this ILogger log, string format, params object[] args) => WriteFormat(log, LogLevel.Critical, WriteFatal, format, args); - - private static void Write(ILogger log, LogLevel level, Action write, object message, Exception exception) - { - if (!log.IsEnabled(level)) - return; - - // log4net idiom: log.Error(ex) - the exception IS the message. Carry it as the structured exception - // so sinks get the stack trace, with its text as the message. - if (exception == null && message is Exception ex) - { - write(log, ex.Message, ex); - return; - } - - write(log, message?.ToString(), exception); - } - - private static void WriteFormat(ILogger log, LogLevel level, Action write, string format, object[] args) - { - if (!log.IsEnabled(level)) - return; - - string text; - try - { - text = string.Format(CultureInfo.InvariantCulture, format, args); - } - catch (FormatException) - { - // log4net never throws from *Format; a bad format string must not take the server down. - text = format; - } - - write(log, text, null); - } - } -} diff --git a/Source/ACE.DatLoader/DatDatabase.cs b/Source/ACE.DatLoader/DatDatabase.cs index 6007b6be0b..e72c110151 100644 --- a/Source/ACE.DatLoader/DatDatabase.cs +++ b/Source/ACE.DatLoader/DatDatabase.cs @@ -107,7 +107,7 @@ public DatReader GetReaderForFile(uint fileId) //log.DebugFormat("Unable to find object_id {0:X8} in {1}", fileId, Enum.GetName(typeof(DatDatabaseType), Header.DataSet)); } else - log.InfoFormat("Unable to find object_id {0:X8} in {1}", fileId, Enum.GetName(typeof(DatDatabaseType), Header.DataSet)); + log.LogInformation("Unable to find object_id {FileId:X8} in {Name}", fileId, Enum.GetName(typeof(DatDatabaseType), Header.DataSet)); return null; } @@ -157,12 +157,12 @@ private int GetTotalIterations() if (iteration.TotalIterations > 0) { if (iteration.Ints.Count > 1) - log.Error($"{FilePath} contains an incomplete dat file!"); + log.LogError("{FilePath} contains an incomplete dat file!", FilePath); return iteration.TotalIterations; } else { - log.Error($"Unable to read iteration from {FilePath}"); + log.LogError("Unable to read iteration from {FilePath}", FilePath); return 0; } } diff --git a/Source/ACE.DatLoader/DatManager.cs b/Source/ACE.DatLoader/DatManager.cs index 85406544fe..933d113a9c 100644 --- a/Source/ACE.DatLoader/DatManager.cs +++ b/Source/ACE.DatLoader/DatManager.cs @@ -36,14 +36,14 @@ public static void Initialize(string datFileDirectory, bool keepOpen = false, bo datFile = Path.Combine(datDir, "client_cell_1.dat"); CellDat = new CellDatDatabase(datFile, keepOpen); count = CellDat.AllFiles.Count; - log.Info($"Successfully opened {datFile} file, containing {count} records, iteration {CellDat.Iteration}"); + log.LogInformation("Successfully opened {DatFile} file, containing {Count} records, iteration {Iteration}", datFile, count, CellDat.Iteration); if (CellDat.Iteration != ITERATION_CELL) - log.Warn($"{datFile} iteration does not match expected end-of-retail version of {ITERATION_CELL}."); + log.LogWarning("{DatFile} iteration does not match expected end-of-retail version of {ITERATION_CELL}.", datFile, ITERATION_CELL); } catch (FileNotFoundException ex) { - log.Error($"An exception occured while attempting to open {datFile} file! This needs to be corrected in order for Landblocks to load!"); - log.Error($"Exception: {ex.Message}"); + log.LogError("An exception occured while attempting to open {DatFile} file! This needs to be corrected in order for Landblocks to load!", datFile); + log.LogError("Exception: {Message}", ex.Message); } } @@ -53,14 +53,14 @@ public static void Initialize(string datFileDirectory, bool keepOpen = false, bo PortalDat = new PortalDatDatabase(datFile, keepOpen); PortalDat.SkillTable.AddRetiredSkills(); count = PortalDat.AllFiles.Count; - log.Info($"Successfully opened {datFile} file, containing {count} records, iteration {PortalDat.Iteration}"); + log.LogInformation("Successfully opened {DatFile} file, containing {Count} records, iteration {Iteration}", datFile, count, PortalDat.Iteration); if (PortalDat.Iteration != ITERATION_PORTAL) - log.Warn($"{datFile} iteration does not match expected end-of-retail version of {ITERATION_PORTAL}."); + log.LogWarning("{DatFile} iteration does not match expected end-of-retail version of {ITERATION_PORTAL}.", datFile, ITERATION_PORTAL); } catch (FileNotFoundException ex) { - log.Error($"An exception occured while attempting to open {datFile} file!\n\n *** Please check your 'DatFilesDirectory' setting in the config.js file. ***\n *** ACE will not run properly without this properly configured! ***\n"); - log.Error($"Exception: {ex.Message}"); + log.LogError("An exception occured while attempting to open {DatFile} file!\n\n *** Please check your 'DatFilesDirectory' setting in the config.js file. ***\n *** ACE will not run properly without this properly configured! ***\n", datFile); + log.LogError("Exception: {Message}", ex.Message); } // Load the client_highres.dat file. This is not required for ACE operation, so no exception needs to be generated. @@ -69,9 +69,9 @@ public static void Initialize(string datFileDirectory, bool keepOpen = false, bo { HighResDat = new DatDatabase(datFile, keepOpen); count = HighResDat.AllFiles.Count; - log.Info($"Successfully opened {datFile} file, containing {count} records, iteration {HighResDat.Iteration}"); + log.LogInformation("Successfully opened {DatFile} file, containing {Count} records, iteration {Iteration}", datFile, count, HighResDat.Iteration); if (HighResDat.Iteration != ITERATION_HIRES) - log.Warn($"{datFile} iteration does not match expected end-of-retail version of {ITERATION_HIRES}."); + log.LogWarning("{DatFile} iteration does not match expected end-of-retail version of {ITERATION_HIRES}.", datFile, ITERATION_HIRES); } try @@ -79,14 +79,14 @@ public static void Initialize(string datFileDirectory, bool keepOpen = false, bo datFile = Path.Combine(datDir, "client_local_English.dat"); LanguageDat = new LanguageDatDatabase(datFile, keepOpen); count = LanguageDat.AllFiles.Count; - log.Info($"Successfully opened {datFile} file, containing {count} records, iteration {LanguageDat.Iteration}"); + log.LogInformation("Successfully opened {DatFile} file, containing {Count} records, iteration {Iteration}", datFile, count, LanguageDat.Iteration); if(LanguageDat.Iteration != ITERATION_LANGUAGE) - log.Warn($"{datFile} iteration does not match expected end-of-retail version of {ITERATION_LANGUAGE}."); + log.LogWarning("{DatFile} iteration does not match expected end-of-retail version of {ITERATION_LANGUAGE}.", datFile, ITERATION_LANGUAGE); } catch (FileNotFoundException ex) { - log.Error($"An exception occured while attempting to open {datFile} file!\n\n *** Please check your 'DatFilesDirectory' setting in the config.json file. ***\n *** ACE will not run properly without this properly configured! ***\n"); - log.Error($"Exception: {ex.Message}"); + log.LogError("An exception occured while attempting to open {DatFile} file!\n\n *** Please check your 'DatFilesDirectory' setting in the config.json file. ***\n *** ACE will not run properly without this properly configured! ***\n", datFile); + log.LogError("Exception: {Message}", ex.Message); } } } diff --git a/Source/ACE.DatLoader/Entity/AnimationHook.cs b/Source/ACE.DatLoader/Entity/AnimationHook.cs index d94608a9f5..620a531843 100644 --- a/Source/ACE.DatLoader/Entity/AnimationHook.cs +++ b/Source/ACE.DatLoader/Entity/AnimationHook.cs @@ -149,7 +149,7 @@ public static AnimationHook ReadHook(BinaryReader reader) break; default: - log.Warn($"Not Implemented Hook type encountered: {hookType}"); + log.LogWarning("Not Implemented Hook type encountered: {HookType}", hookType); hook = null; break; } diff --git a/Source/ACE.Database/AuthenticationDatabase.cs b/Source/ACE.Database/AuthenticationDatabase.cs index 69de988fff..155b4a9eed 100644 --- a/Source/ACE.Database/AuthenticationDatabase.cs +++ b/Source/ACE.Database/AuthenticationDatabase.cs @@ -31,12 +31,12 @@ public bool Exists(bool retryUntilFound) { if (((RelationalDatabaseCreator)context.Database.GetService()).Exists()) { - log.InfoFormat("[DATABASE] Successfully connected to {0} database on {1}:{2}.", config.Database, config.Host, config.Port); + log.LogInformation("[DATABASE] Successfully connected to {Database} database on {Host}:{Port}.", config.Database, config.Host, config.Port); return true; } } - log.Error($"[DATABASE] Attempting to reconnect to {config.Database} database on {config.Host}:{config.Port} in 5 seconds..."); + log.LogError("[DATABASE] Attempting to reconnect to {Database} database on {Host}:{Port} in 5 seconds...", config.Database, config.Host, config.Port); if (retryUntilFound) Thread.Sleep(5000); diff --git a/Source/ACE.Database/DatabaseManager.cs b/Source/ACE.Database/DatabaseManager.cs index 051fa275f9..ff8c95fdc8 100644 --- a/Source/ACE.Database/DatabaseManager.cs +++ b/Source/ACE.Database/DatabaseManager.cs @@ -30,7 +30,7 @@ public static void Initialize(bool autoRetry = true) if (Authentication.GetListofAccountsByAccessLevel(ACE.Entity.Enum.AccessLevel.Admin).Count == 0) { - log.Warn("Authentication Database does not contain any admin accounts. The next account to be created will automatically be promoted to an Admin account."); + log.LogWarning("Authentication Database does not contain any admin accounts. The next account to be created will automatically be promoted to an Admin account."); AutoPromoteNextAccountToAdmin = true; } else @@ -40,7 +40,7 @@ public static void Initialize(bool autoRetry = true) if (!World.IsWorldDatabaseGuidRangeValid()) { - log.Fatal("World Database contains instance GUIDs outside of static range which will prevent GuidManager from properly assigning GUIDs and can result in GUID exhaustion prematurely."); + log.LogCritical("World Database contains instance GUIDs outside of static range which will prevent GuidManager from properly assigning GUIDs and can result in GUID exhaustion prematurely."); InitializationFailure = true; return; } @@ -48,7 +48,7 @@ public static void Initialize(bool autoRetry = true) var playerWeenieLoadTest = World.GetCachedWeenie("human"); if (playerWeenieLoadTest == null) { - log.Fatal("World Database does not contain the weenie for human (1). Characters cannot be created or logged into until the missing weenie is restored."); + log.LogCritical("World Database does not contain the weenie for human (1). Characters cannot be created or logged into until the missing weenie is restored."); InitializationFailure = true; return; } diff --git a/Source/ACE.Database/Models/Auth/AccountExtensions.cs b/Source/ACE.Database/Models/Auth/AccountExtensions.cs index 8535255a50..a2213f3d81 100644 --- a/Source/ACE.Database/Models/Auth/AccountExtensions.cs +++ b/Source/ACE.Database/Models/Auth/AccountExtensions.cs @@ -40,7 +40,7 @@ public static bool PasswordMatches(this Account account, string password) } else // Account password is using SHA512 salt { - log.DebugFormat("{0} password verified using SHA512 hash/salt, migrating to bcrypt.", account.AccountName); + log.LogDebug("{AccountName} password verified using SHA512 hash/salt, migrating to bcrypt.", account.AccountName); var input = GetPasswordHash(account, password); @@ -79,12 +79,12 @@ private static string GetPasswordHash(string password) if (workFactor < 4) { - log.Warn("PasswordHashWorkFactor in config less than minimum value of 4, using 4 and continuing."); + log.LogWarning("PasswordHashWorkFactor in config less than minimum value of 4, using 4 and continuing."); workFactor = 4; } else if (workFactor > 31) { - log.Warn("PasswordHashWorkFactor in config greater than maximum value of 31, using 31 and continuing."); + log.LogWarning("PasswordHashWorkFactor in config greater than maximum value of 31, using 31 and continuing."); workFactor = 31; } diff --git a/Source/ACE.Database/OfflineTools/Shard/BiotaGuidConsolidator.cs b/Source/ACE.Database/OfflineTools/Shard/BiotaGuidConsolidator.cs index 46d86c7a88..d9dfcc7316 100644 --- a/Source/ACE.Database/OfflineTools/Shard/BiotaGuidConsolidator.cs +++ b/Source/ACE.Database/OfflineTools/Shard/BiotaGuidConsolidator.cs @@ -96,7 +96,7 @@ private static bool MightBreakPlugins(Biota biota) public static void ConsolidateBiotaGuids(uint startingGuid, bool tryNotToBreakPlugins, bool skipUserInputAfterWarning, out int numberOfBiotasConsolidated, out int numberOfBiotasSkipped, out int numberOfErrors) { - log.Info($"Consolidating biotas, starting at guid 0x{startingGuid:X8}, tryNotToBreakPlugins: {tryNotToBreakPlugins}..."); + log.LogInformation("Consolidating biotas, starting at guid 0x{StartingGuid:X8}, tryNotToBreakPlugins: {TryNotToBreakPlugins}...", startingGuid, tryNotToBreakPlugins); Thread.Sleep(1000); // Give the logger type to flush to the client so that our output lines up in order @@ -152,7 +152,7 @@ public static void ConsolidateBiotaGuids(uint startingGuid, bool tryNotToBreakPl if (fullBiota == null) { Interlocked.Increment(ref numOfErrors); - log.WarnFormat("Failed to get biota with id 0x{0:X8} from the database. This shouldn't happen. It also shouldn't require a rollback.", partialBiota.Id); + log.LogWarning("Failed to get biota with id 0x{Id:X8} from the database. This shouldn't happen. It also shouldn't require a rollback.", partialBiota.Id); return; } @@ -183,7 +183,7 @@ public static void ConsolidateBiotaGuids(uint startingGuid, bool tryNotToBreakPl if (newId == 0) { Interlocked.Increment(ref numOfErrors); - log.Fatal("Failed to generate new id. No more id's available for consolidation. This shouldn't require a rollback."); + log.LogCritical("Failed to generate new id. No more id's available for consolidation. This shouldn't require a rollback."); return; } @@ -197,7 +197,7 @@ public static void ConsolidateBiotaGuids(uint startingGuid, bool tryNotToBreakPl if (!shardDatabase.SaveBiota(converted, new ReaderWriterLockSlim())) { Interlocked.Increment(ref numOfErrors); - log.FatalFormat("Failed to save new biota with id 0x{0:X8} to the database. Please rollback your shard.", fullBiota.Id); + log.LogCritical("Failed to save new biota with id 0x{Id:X8} to the database. Please rollback your shard.", fullBiota.Id); return; } @@ -205,7 +205,7 @@ public static void ConsolidateBiotaGuids(uint startingGuid, bool tryNotToBreakPl if (!shardDatabase.RemoveBiota(fullBiota.Id)) { Interlocked.Increment(ref numOfErrors); - log.FatalFormat("Failed to remove original biota with id 0x{0:X8} from database. Please rollback your shard.", fullBiota.Id); + log.LogCritical("Failed to remove original biota with id 0x{Id:X8} from database. Please rollback your shard.", fullBiota.Id); return; } @@ -240,7 +240,7 @@ public static void ConsolidateBiotaGuids(uint startingGuid, bool tryNotToBreakPl if (fullBiota == null) { Interlocked.Increment(ref numOfErrors); - log.WarnFormat("Failed to get biota with id 0x{0:X8} from the database. This shouldn't happen. It also shouldn't require a rollback.", partialBiota.Id); + log.LogWarning("Failed to get biota with id 0x{Id:X8} from the database. This shouldn't happen. It also shouldn't require a rollback.", partialBiota.Id); break; } @@ -271,7 +271,7 @@ public static void ConsolidateBiotaGuids(uint startingGuid, bool tryNotToBreakPl if (newId == 0) { Interlocked.Increment(ref numOfErrors); - log.Fatal("Failed to generate new id. No more id's available for consolidation. This shouldn't require a rollback."); + log.LogCritical("Failed to generate new id. No more id's available for consolidation. This shouldn't require a rollback."); break; } @@ -285,7 +285,7 @@ public static void ConsolidateBiotaGuids(uint startingGuid, bool tryNotToBreakPl if (!shardDatabase.SaveBiota(converted, new ReaderWriterLockSlim())) { Interlocked.Increment(ref numOfErrors); - log.FatalFormat("Failed to save new biota with id 0x{0:X8} to the database. Please rollback your shard.", fullBiota.Id); + log.LogCritical("Failed to save new biota with id 0x{Id:X8} to the database. Please rollback your shard.", fullBiota.Id); break; } @@ -309,7 +309,7 @@ public static void ConsolidateBiotaGuids(uint startingGuid, bool tryNotToBreakPl if (!shardDatabase.RemoveBiota(fullBiota.Id)) { Interlocked.Increment(ref numOfErrors); - log.FatalFormat("Failed to remove original biota with id 0x{0:X8} from database. Please rollback your shard.", fullBiota.Id); + log.LogCritical("Failed to remove original biota with id 0x{Id:X8} from database. Please rollback your shard.", fullBiota.Id); break; } @@ -367,7 +367,7 @@ public static void ConsolidateBiotaGuids(uint startingGuid, bool tryNotToBreakPl numberOfBiotasSkipped = numOfBiotasSkipped; numberOfErrors = numOfErrors; - log.Info($"Consolidated {numberOfBiotasConsolidated:N0} biotas, {numberOfBiotasSkipped:N0} skipped, with {numberOfErrors:N0} errors out of {partialBiotas.Count:N0} total."); + log.LogInformation("Consolidated {NumberOfBiotasConsolidated:N0} biotas, {NumberOfBiotasSkipped:N0} skipped, with {NumberOfErrors:N0} errors out of {Count:N0} total.", numberOfBiotasConsolidated, numberOfBiotasSkipped, numberOfErrors, partialBiotas.Count); } } } diff --git a/Source/ACE.Database/SerializedShardDatabase.cs b/Source/ACE.Database/SerializedShardDatabase.cs index e72ec2babc..c7245eeb47 100644 --- a/Source/ACE.Database/SerializedShardDatabase.cs +++ b/Source/ACE.Database/SerializedShardDatabase.cs @@ -59,7 +59,7 @@ private void DoWork() } catch (Exception ex) { - log.Error($"[DATABASE] DoWork task failed with exception: {ex}"); + log.LogError("[DATABASE] DoWork task failed with exception: {Ex}", ex); // perhaps add failure callbacks? // swallow for now. can't block other db work because 1 fails. } diff --git a/Source/ACE.Database/ShardDatabase.cs b/Source/ACE.Database/ShardDatabase.cs index 563191b6ac..8a0ed550c6 100644 --- a/Source/ACE.Database/ShardDatabase.cs +++ b/Source/ACE.Database/ShardDatabase.cs @@ -35,12 +35,12 @@ public bool Exists(bool retryUntilFound) { if (((RelationalDatabaseCreator)context.Database.GetService()).Exists()) { - log.InfoFormat("[DATABASE] Successfully connected to {0} database on {1}:{2}.", config.Database, config.Host, config.Port); + log.LogInformation("[DATABASE] Successfully connected to {Database} database on {Host}:{Port}.", config.Database, config.Host, config.Port); return true; } } - log.Error($"[DATABASE] Attempting to reconnect to {config.Database} database on {config.Host}:{config.Port} in 5 seconds..."); + log.LogError("[DATABASE] Attempting to reconnect to {Database} database on {Host}:{Port} in 5 seconds...", config.Database, config.Host, config.Port); if (retryUntilFound) Thread.Sleep(5000); @@ -320,7 +320,7 @@ protected bool DoSaveBiota(ShardDbContext context, Biota biota) context.SaveChanges(); if (firstException != null) - log.InfoFormat("[DATABASE] DoSaveBiota 0x{0:X8}:{1} retry succeeded after initial exception of: {2}", biota.Id, biota.GetProperty(PropertyString.Name), firstException.GetFullMessage()); + log.LogInformation("[DATABASE] DoSaveBiota 0x{Id:X8}:{Property} retry succeeded after initial exception of: {FullMessage}", biota.Id, biota.GetProperty(PropertyString.Name), firstException.GetFullMessage()); return true; } @@ -333,8 +333,8 @@ protected bool DoSaveBiota(ShardDbContext context, Biota biota) } // Character name might be in use or some other fault - log.Error($"[DATABASE] DoSaveBiota 0x{biota.Id:X8}:{biota.GetProperty(PropertyString.Name)} failed first attempt with exception: {firstException.GetFullMessage()}"); - log.Error($"[DATABASE] DoSaveBiota 0x{biota.Id:X8}:{biota.GetProperty(PropertyString.Name)} failed second attempt with exception: {ex.GetFullMessage()}"); + log.LogError("[DATABASE] DoSaveBiota 0x{Id:X8}:{Property} failed first attempt with exception: {FullMessage}", biota.Id, biota.GetProperty(PropertyString.Name), firstException.GetFullMessage()); + log.LogError("[DATABASE] DoSaveBiota 0x{Id:X8}:{Property} failed second attempt with exception: {FullMessage}", biota.Id, biota.GetProperty(PropertyString.Name), ex.GetFullMessage()); return false; } } @@ -402,7 +402,7 @@ public virtual bool RemoveBiota(uint id) context.SaveChanges(); if (firstException != null) - log.InfoFormat("[DATABASE] RemoveBiota 0x{0:X8} retry succeeded after initial exception of: {1}", id, firstException.GetFullMessage()); + log.LogInformation("[DATABASE] RemoveBiota 0x{Id:X8} retry succeeded after initial exception of: {FullMessage}", id, firstException.GetFullMessage()); return true; } @@ -415,8 +415,8 @@ public virtual bool RemoveBiota(uint id) } // Character name might be in use or some other fault - log.Error($"[DATABASE] RemoveBiota 0x{id:X8} failed first attempt with exception: {firstException.GetFullMessage()}"); - log.Error($"[DATABASE] RemoveBiota 0x{id:X8} failed second attempt with exception: {ex.GetFullMessage()}"); + log.LogError("[DATABASE] RemoveBiota 0x{Id:X8} failed first attempt with exception: {FullMessage}", id, firstException.GetFullMessage()); + log.LogError("[DATABASE] RemoveBiota 0x{Id:X8} failed second attempt with exception: {FullMessage}", id, ex.GetFullMessage()); return false; } } @@ -680,7 +680,7 @@ public bool SaveCharacter(Character character, ReaderWriterLockSlim rwLock) cachedContext.SaveChanges(); if (firstException != null) - log.InfoFormat("[DATABASE] SaveCharacter-1 0x{0:X8}:{1} retry succeeded after initial exception of: {2}", character.Id, character.Name, firstException.GetFullMessage()); + log.LogInformation("[DATABASE] SaveCharacter-1 0x{Id:X8}:{Name} retry succeeded after initial exception of: {FullMessage}", character.Id, character.Name, firstException.GetFullMessage()); return true; } @@ -693,8 +693,8 @@ public bool SaveCharacter(Character character, ReaderWriterLockSlim rwLock) } // Character name might be in use or some other fault - log.Error($"[DATABASE] SaveCharacter-1 0x{character.Id:X8}:{character.Name} failed first attempt with exception: {firstException.GetFullMessage()}"); - log.Error($"[DATABASE] SaveCharacter-1 0x{character.Id:X8}:{character.Name} failed second attempt with exception: {ex.GetFullMessage()}"); + log.LogError("[DATABASE] SaveCharacter-1 0x{Id:X8}:{Name} failed first attempt with exception: {FullMessage}", character.Id, character.Name, firstException.GetFullMessage()); + log.LogError("[DATABASE] SaveCharacter-1 0x{Id:X8}:{Name} failed second attempt with exception: {FullMessage}", character.Id, character.Name, ex.GetFullMessage()); return false; } } @@ -721,7 +721,7 @@ public bool SaveCharacter(Character character, ReaderWriterLockSlim rwLock) context.SaveChanges(); if (firstException != null) - log.InfoFormat("[DATABASE] SaveCharacter-2 0x{0:X8}:{1} retry succeeded after initial exception of: {2}", character.Id, character.Name, firstException.GetFullMessage()); + log.LogInformation("[DATABASE] SaveCharacter-2 0x{Id:X8}:{Name} retry succeeded after initial exception of: {FullMessage}", character.Id, character.Name, firstException.GetFullMessage()); return true; } @@ -734,8 +734,8 @@ public bool SaveCharacter(Character character, ReaderWriterLockSlim rwLock) } // Character name might be in use or some other fault - log.Error($"[DATABASE] SaveCharacter-2 0x{character.Id:X8}:{character.Name} failed first attempt with exception: {firstException.GetFullMessage()}"); - log.Error($"[DATABASE] SaveCharacter-2 0x{character.Id:X8}:{character.Name} failed second attempt with exception: {ex.GetFullMessage()}"); + log.LogError("[DATABASE] SaveCharacter-2 0x{Id:X8}:{Name} failed first attempt with exception: {FullMessage}", character.Id, character.Name, firstException.GetFullMessage()); + log.LogError("[DATABASE] SaveCharacter-2 0x{Id:X8}:{Name} failed second attempt with exception: {FullMessage}", character.Id, character.Name, ex.GetFullMessage()); return false; } } @@ -786,7 +786,7 @@ public bool AddCharacterInParallel(ACE.Entity.Models.Biota biota, ReaderWriterLo biotas.Add(convertedBiota); } else - log.Error($"ShardDatabase.GetAllPlayerBiotasInParallel() - couldn't find biota for character 0x{result.Id:X8}"); + log.LogError("ShardDatabase.GetAllPlayerBiotasInParallel() - couldn't find biota for character 0x{Id:X8}", result.Id); }); } @@ -822,7 +822,7 @@ public bool RenameCharacter(Character character, string newName, ReaderWriterLoc cachedContext.SaveChanges(); if (firstException != null) - log.InfoFormat("[DATABASE] RenameCharacter 0x{0:X8}:{1} retry succeeded after initial exception of: {2}", character.Id, character.Name, firstException.GetFullMessage()); + log.LogInformation("[DATABASE] RenameCharacter 0x{Id:X8}:{Name} retry succeeded after initial exception of: {FullMessage}", character.Id, character.Name, firstException.GetFullMessage()); return true; } @@ -835,8 +835,8 @@ public bool RenameCharacter(Character character, string newName, ReaderWriterLoc } // Character name might be in use or some other fault - log.Error($"[DATABASE] RenameCharacter 0x{character.Id:X8}:{character.Name} failed first attempt with exception: {firstException.GetFullMessage()}"); - log.Error($"[DATABASE] RenameCharacter 0x{character.Id:X8}:{character.Name} failed second attempt with exception: {ex.GetFullMessage()}"); + log.LogError("[DATABASE] RenameCharacter 0x{Id:X8}:{Name} failed first attempt with exception: {FullMessage}", character.Id, character.Name, firstException.GetFullMessage()); + log.LogError("[DATABASE] RenameCharacter 0x{Id:X8}:{Name} failed second attempt with exception: {FullMessage}", character.Id, character.Name, ex.GetFullMessage()); return false; } } @@ -865,7 +865,7 @@ public bool RenameCharacter(Character character, string newName, ReaderWriterLoc context.SaveChanges(); if (firstException != null) - log.InfoFormat("[DATABASE] RenameCharacter 0x{0:X8}:{1} retry succeeded after initial exception of: {2}", character.Id, character.Name, firstException.GetFullMessage()); + log.LogInformation("[DATABASE] RenameCharacter 0x{Id:X8}:{Name} retry succeeded after initial exception of: {FullMessage}", character.Id, character.Name, firstException.GetFullMessage()); return true; } @@ -878,8 +878,8 @@ public bool RenameCharacter(Character character, string newName, ReaderWriterLoc } // Character name might be in use or some other fault - log.Error($"[DATABASE] RenameCharacter 0x{character.Id:X8}:{character.Name} failed first attempt with exception: {firstException.GetFullMessage()}"); - log.Error($"[DATABASE] RenameCharacter 0x{character.Id:X8}:{character.Name} failed second attempt with exception: {ex.GetFullMessage()}"); + log.LogError("[DATABASE] RenameCharacter 0x{Id:X8}:{Name} failed first attempt with exception: {FullMessage}", character.Id, character.Name, firstException.GetFullMessage()); + log.LogError("[DATABASE] RenameCharacter 0x{Id:X8}:{Name} failed second attempt with exception: {FullMessage}", character.Id, character.Name, ex.GetFullMessage()); return false; } } diff --git a/Source/ACE.Database/ShardDatabaseOfflineTools.cs b/Source/ACE.Database/ShardDatabaseOfflineTools.cs index 073c21b180..332e472dbe 100644 --- a/Source/ACE.Database/ShardDatabaseOfflineTools.cs +++ b/Source/ACE.Database/ShardDatabaseOfflineTools.cs @@ -131,7 +131,7 @@ public static void PurgeCharacter(ShardDbContext context, uint characterId, out if (!string.IsNullOrWhiteSpace(reason)) message += $" Reason: {reason}."; - log.Info(message); + log.LogInformation("{Message:l}", message); try { @@ -139,7 +139,7 @@ public static void PurgeCharacter(ShardDbContext context, uint characterId, out } catch (Exception ex) { - log.ErrorFormat("[DATABASE][PURGE] PurgeCharacter 0x{0:X8} failed with exception: {1}", characterId, ex); + log.LogError("[DATABASE][PURGE] PurgeCharacter 0x{CharacterId:X8} failed with exception: {Ex}", characterId, ex); } } @@ -246,7 +246,7 @@ public static void PurgePlayer(ShardDbContext context, uint playerId, out int ch if (!string.IsNullOrWhiteSpace(reason)) message += $" Reason: {reason}."; - log.Info(message); + log.LogInformation("{Message:l}", message); try { @@ -254,7 +254,7 @@ public static void PurgePlayer(ShardDbContext context, uint playerId, out int ch } catch (Exception ex) { - log.ErrorFormat("[DATABASE][PURGE] PurgePlayer 0x{0:X8} failed with exception: {1}", playerId, ex); + log.LogError("[DATABASE][PURGE] PurgePlayer 0x{PlayerId:X8} failed with exception: {Ex}", playerId, ex); } } @@ -302,7 +302,7 @@ public static bool PurgeBiota(ShardDbContext context, uint id, string reason = n if (!string.IsNullOrWhiteSpace(reason)) message += $" Reason: {reason}."; - log.Info(message); + log.LogInformation("{Message:l}", message); context.Biota.Remove(biota); @@ -312,7 +312,7 @@ public static bool PurgeBiota(ShardDbContext context, uint id, string reason = n } catch (Exception ex) { - log.ErrorFormat("[DATABASE][PURGE] PurgeBiota 0x{0:X8} failed with exception: {1}", id, ex); + log.LogError("[DATABASE][PURGE] PurgeBiota 0x{Id:X8} failed with exception: {Ex}", id, ex); } return true; @@ -371,10 +371,10 @@ from b in combined.DefaultIfEmpty() PurgeCharacter(result, out var charactersPurged, out var playerBiotasPurged, out var possessionPurged, "No Player biota counterpart found"); if (charactersPurged != 1) - log.Error("[DATABASE][PURGE] PurgeOrphanedBiotasInParallel failed to purge exactly 1 character. This should not happen!"); + log.LogError("[DATABASE][PURGE] PurgeOrphanedBiotasInParallel failed to purge exactly 1 character. This should not happen!"); if (playerBiotasPurged != 0) - log.Error("[DATABASE][PURGE] PurgeOrphanedBiotasInParallel purged a player biota and character record. This should not happen!"); + log.LogError("[DATABASE][PURGE] PurgeOrphanedBiotasInParallel purged a player biota and character record. This should not happen!"); Interlocked.Add(ref totalNumberOfBiotasPurged, charactersPurged); Interlocked.Add(ref totalNumberOfBiotasPurged, playerBiotasPurged); @@ -417,10 +417,10 @@ from c in combined.DefaultIfEmpty() PurgePlayer(result, out var charactersPurged, out var playerBiotasPurged, out var possessionPurged, "No Character record counterpart found"); if (charactersPurged != 0) - log.Error("[DATABASE][PURGE] PurgeOrphanedBiotasInParallel purged a character record and a player biota. This should not happen!"); + log.LogError("[DATABASE][PURGE] PurgeOrphanedBiotasInParallel purged a character record and a player biota. This should not happen!"); if (playerBiotasPurged != 1) - log.Error("[DATABASE][PURGE] PurgeOrphanedBiotasInParallel failed to purge exactly 1 player biota. This should not happen!"); + log.LogError("[DATABASE][PURGE] PurgeOrphanedBiotasInParallel failed to purge exactly 1 player biota. This should not happen!"); Interlocked.Add(ref totalNumberOfBiotasPurged, charactersPurged); Interlocked.Add(ref totalNumberOfBiotasPurged, playerBiotasPurged); @@ -958,7 +958,7 @@ public static void FixAnimPartAndTextureMapFromPR2731(out int numberOfRecordsFix /// public static void CheckForPR2918Script() { - log.Info($"Checking for 2020-04-11-00-Update-Character-SpellBars.sql patch"); + log.LogInformation("Checking for 2020-04-11-00-Update-Character-SpellBars.sql patch"); using (var context = new ShardDbContext()) { @@ -966,14 +966,14 @@ public static void CheckForPR2918Script() if (characterSpellBarsNotFixed.Count > 0) { - log.Warn("2020-04-11-00-Update-Character-SpellBars.sql patch not yet applied. Please apply this patch ASAP! Skipping FixSpellBarsPR2918 for now..."); - log.Fatal("2020-04-11-00-Update-Character-SpellBars.sql patch not yet applied. You must apply this patch before proceeding further..."); + log.LogWarning("2020-04-11-00-Update-Character-SpellBars.sql patch not yet applied. Please apply this patch ASAP! Skipping FixSpellBarsPR2918 for now..."); + log.LogCritical("2020-04-11-00-Update-Character-SpellBars.sql patch not yet applied. You must apply this patch before proceeding further..."); Environment.Exit(1); return; } } - log.Info($"2020-04-11-00-Update-Character-SpellBars.sql patch has been successfully installed. Before opening world to players, make sure you've run fix-spell-bars command from console"); + log.LogInformation("2020-04-11-00-Update-Character-SpellBars.sql patch has been successfully installed. Before opening world to players, make sure you've run fix-spell-bars command from console"); } /// @@ -992,7 +992,7 @@ public static void CheckForBiotaPropertiesPaletteOrderColumnInShard() } catch (MySqlConnector.MySqlException) { - log.Warn("order column in biota_properties_palette table in shard database is missing! Attempting to fix..."); + log.LogWarning("order column in biota_properties_palette table in shard database is missing! Attempting to fix..."); try { context.Database.ExecuteSqlRaw("ALTER TABLE `biota_properties_palette` ADD COLUMN `order` TINYINT(3) UNSIGNED NULL DEFAULT NULL AFTER `length`;"); @@ -1001,7 +1001,7 @@ public static void CheckForBiotaPropertiesPaletteOrderColumnInShard() } catch (Exception ex) { - log.FatalFormat("Unable to restore order column in biota_properties_palette table in shard database due to following error: {0}", ex.GetFullMessage()); + log.LogCritical("Unable to restore order column in biota_properties_palette table in shard database due to following error: {FullMessage}", ex.GetFullMessage()); Environment.Exit(1); return; } @@ -1040,7 +1040,7 @@ public static void PruneDeletedCharactersFromFriendLists(out int numberOfRecords foreach (var invalidFriend in invalidFriends) { - log.InfoFormat("[PRUNE] Character 0x{0:X8} had 0x{1:X8} for a friend, which is not found in database, and has been removed from their friends list.", invalidFriend.CharacterId, invalidFriend.FriendId); + log.LogInformation("[PRUNE] Character 0x{CharacterId:X8} had 0x{FriendId:X8} for a friend, which is not found in database, and has been removed from their friends list.", invalidFriend.CharacterId, invalidFriend.FriendId); context.CharacterPropertiesFriendList.Remove(invalidFriend); numberOfRecordsFixed++; } @@ -1076,7 +1076,7 @@ public static void PruneDeletedObjectsFromShortcutBars(out int numberOfRecordsFi foreach (var invalidShortcut in invalidShortcuts) { - log.InfoFormat("[PRUNE] Character 0x{0:X8} had 0x{1:X8} as a shortcut (in position {2}), which is not found in database, and has been removed from their shortcut bar.", invalidShortcut.CharacterId, invalidShortcut.ShortcutObjectId, invalidShortcut.ShortcutBarIndex); + log.LogInformation("[PRUNE] Character 0x{CharacterId:X8} had 0x{ShortcutObjectId:X8} as a shortcut (in position {ShortcutBarIndex}), which is not found in database, and has been removed from their shortcut bar.", invalidShortcut.CharacterId, invalidShortcut.ShortcutObjectId, invalidShortcut.ShortcutBarIndex); context.CharacterPropertiesShortcutBar.Remove(invalidShortcut); numberOfRecordsFixed++; } @@ -1115,7 +1115,7 @@ public static void PruneDeletedCharactersFromSquelchLists(out int numberOfRecord foreach (var invalidSquelchCharacter in invalidSquelchCharacters) { - log.InfoFormat("[PRUNE] Character 0x{0:X8} had 0x{1:X8} squelched, which is not found in database, and has been removed from their squelch list.", invalidSquelchCharacter.CharacterId, invalidSquelchCharacter.SquelchCharacterId); + log.LogInformation("[PRUNE] Character 0x{CharacterId:X8} had 0x{SquelchCharacterId:X8} squelched, which is not found in database, and has been removed from their squelch list.", invalidSquelchCharacter.CharacterId, invalidSquelchCharacter.SquelchCharacterId); context.CharacterPropertiesSquelch.Remove(invalidSquelchCharacter); numberOfRecordsFixed++; } diff --git a/Source/ACE.Database/WorldDatabase.cs b/Source/ACE.Database/WorldDatabase.cs index 88c09d08ec..b94d0d509e 100644 --- a/Source/ACE.Database/WorldDatabase.cs +++ b/Source/ACE.Database/WorldDatabase.cs @@ -30,12 +30,12 @@ public bool Exists(bool retryUntilFound) { if (((RelationalDatabaseCreator)context.Database.GetService()).Exists()) { - log.InfoFormat("[DATABASE] Successfully connected to {0} database on {1}:{2}.", config.Database, config.Host, config.Port); + log.LogInformation("[DATABASE] Successfully connected to {Database} database on {Host}:{Port}.", config.Database, config.Host, config.Port); return true; } } - log.Error($"[DATABASE] Attempting to reconnect to {config.Database} database on {config.Host}:{config.Port} in 5 seconds..."); + log.LogError("[DATABASE] Attempting to reconnect to {Database} database on {Host}:{Port} in 5 seconds...", config.Database, config.Host, config.Port); if (retryUntilFound) Thread.Sleep(5000); diff --git a/Source/ACE.Server.Tests/Logging/LogBridgeTests.cs b/Source/ACE.Server.Tests/Logging/LogBridgeTests.cs index 2b5eb7c93d..a366540962 100644 --- a/Source/ACE.Server.Tests/Logging/LogBridgeTests.cs +++ b/Source/ACE.Server.Tests/Logging/LogBridgeTests.cs @@ -7,15 +7,15 @@ using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; -using ACE.Common.Logging; using ACE.Server.Logging; namespace ACE.Server.Tests.Logging { /// - /// Proves the log4net-shaped shim over ILogger, routed back into log4net by the bridge, behaves like - /// the ILog calls it replaces: literal text, correct levels, exception idiom, format tolerance, and - /// level checks that follow configuration. Each test uses an isolated log4net repository. + /// Proves standard ILogger calls, routed into log4net by the bridge, render the same text the log4net + /// calls they replaced did: template values, escaped and literal braces, correct levels, exceptions, + /// no formatting at a disabled level, and level checks that follow configuration. Each test uses an + /// isolated log4net repository. /// [TestClass] public class LogBridgeTests @@ -34,40 +34,51 @@ private static (ILoggerFactory factory, MemoryAppender appender, log4net.Reposit } [TestMethod] - public void Message_is_rendered_literally_with_braces_and_quotes_intact() + public void Template_values_are_rendered_and_escaped_braces_survive() { var (factory, appender, _) = Setup(log4net.Core.Level.All); var log = factory.CreateLogger(typeof(LogBridgeTests)); - log.Info("hello {world} {0} \"quoted\" }{"); + log.LogInformation("hello {World} {{literal}} \"quoted\" 0x{Guid:X8}", "earth", 0xABCu); var e = appender.GetEvents().Single(); - Assert.AreEqual("hello {world} {0} \"quoted\" }{", e.RenderedMessage); + Assert.AreEqual("hello earth {literal} \"quoted\" 0x00000ABC", e.RenderedMessage); Assert.AreEqual(log4net.Core.Level.Info, e.Level); Assert.AreEqual(typeof(LogBridgeTests).FullName, e.LoggerName, "category must match log4net's logger naming so config entries still apply"); } + [TestMethod] + public void Prebuilt_text_passed_as_a_value_is_rendered_literally() + { + var (factory, appender, _) = Setup(log4net.Core.Level.All); + var log = factory.CreateLogger("literal"); + + log.LogInformation("{Message:l}", "hello {world} {0} }{"); + + Assert.AreEqual("hello {world} {0} }{", appender.GetEvents().Single().RenderedMessage); + } + [TestMethod] public void Every_level_maps_to_its_log4net_counterpart() { var (factory, appender, _) = Setup(log4net.Core.Level.All); var log = factory.CreateLogger("levels"); - log.Debug("d"); log.Info("i"); log.Warn("w"); log.Error("e"); log.Fatal("f"); + log.LogDebug("d"); log.LogInformation("i"); log.LogWarning("w"); log.LogError("e"); log.LogCritical("f"); var levels = appender.GetEvents().Select(e => e.Level).ToArray(); CollectionAssert.AreEqual(new[] { log4net.Core.Level.Debug, log4net.Core.Level.Info, log4net.Core.Level.Warn, log4net.Core.Level.Error, log4net.Core.Level.Fatal }, levels); } [TestMethod] - public void Exception_passed_as_the_message_is_carried_as_the_exception() + public void Exception_is_carried_as_the_exception() { var (factory, appender, _) = Setup(log4net.Core.Level.All); var log = factory.CreateLogger("ex"); var ex = new InvalidOperationException("boom"); - log.Error(ex); // log4net idiom: the exception IS the message - log.Warn("context", ex); // explicit (message, exception) overload + log.LogError(ex, "{Message:l}", ex.Message); + log.LogWarning(ex, "context"); var events = appender.GetEvents(); Assert.AreSame(ex, events[0].ExceptionObject); Assert.AreEqual("boom", events[0].RenderedMessage); @@ -75,29 +86,27 @@ public void Exception_passed_as_the_message_is_carried_as_the_exception() } [TestMethod] - public void Format_calls_are_deferred_when_disabled_and_never_throw_on_a_bad_format() + public void Values_are_not_formatted_when_the_level_is_disabled() { var (factory, appender, _) = Setup(log4net.Core.Level.Info); - var log = factory.CreateLogger("fmt"); + var log = factory.CreateLogger("disabled"); - log.DebugFormat("{0}", new ThrowsOnToString()); // disabled level: argument must never be formatted - log.InfoFormat("{0} and {1}", "only-one-arg"); // bad format: must not throw + log.LogDebug("{Value}", new ThrowsOnToString()); - var e = appender.GetEvents().Single(); - Assert.AreEqual("{0} and {1}", e.RenderedMessage, "a bad format string surfaces raw rather than crashing"); + Assert.AreEqual(0, appender.GetEvents().Length); } [TestMethod] - public void IsDebugEnabled_follows_the_configured_level() + public void IsEnabled_follows_the_configured_level() { var (factory, _, repo) = Setup(log4net.Core.Level.All); var log = factory.CreateLogger("enabled"); - Assert.IsTrue(log.IsDebugEnabled); + Assert.IsTrue(log.IsEnabled(LogLevel.Debug)); repo.Root.Level = log4net.Core.Level.Info; repo.RaiseConfigurationChanged(EventArgs.Empty); - Assert.IsFalse(log.IsDebugEnabled); - Assert.IsTrue(log.IsInfoEnabled); + Assert.IsFalse(log.IsEnabled(LogLevel.Debug)); + Assert.IsTrue(log.IsEnabled(LogLevel.Information)); } [TestMethod] @@ -111,11 +120,11 @@ public void Loggers_created_before_the_provider_is_added_still_receive_it() var factory = new LoggerFactory(); var early = factory.CreateLogger("early"); - early.Info("dropped - no provider yet"); + early.LogInformation("dropped - no provider yet"); Assert.AreEqual(0, appender.GetEvents().Length); factory.AddProvider(new Log4NetBridgeProvider(repo)); - early.Info("delivered"); + early.LogInformation("delivered"); Assert.AreEqual("delivered", appender.GetEvents().Single().RenderedMessage); } diff --git a/Source/ACE.Server/Command/CommandManager.cs b/Source/ACE.Server/Command/CommandManager.cs index d3c872a857..9056e46eaa 100644 --- a/Source/ACE.Server/Command/CommandManager.cs +++ b/Source/ACE.Server/Command/CommandManager.cs @@ -72,17 +72,17 @@ public static bool TryAddCommand(CommandHandlerInfo commandHandler, bool overrid if (!commandHandlers.ContainsKey(command)) { commandHandlers.Add(command, commandHandler); - log.Info($"Command created: {command}"); + log.LogInformation("Command created: {Command}", command); return true; } //Update if overriding and the command exists else if (overrides) { - log.Info($"Command updated: {command}"); + log.LogInformation("Command updated: {Command}", command); commandHandlers[command] = commandHandler; return true; } - log.Warn($"Failed to add command: {command}"); + log.LogWarning("Failed to add command: {Command}", command); return false; } @@ -91,7 +91,7 @@ public static bool TryRemoveCommand(string command) if (!commandHandlers.ContainsKey(command)) return false; - log.Info($"Removed command: {command}"); + log.LogInformation("Removed command: {Command}", command); commandHandlers.Remove(command); return true; } @@ -117,7 +117,7 @@ public static void Initialize() if (NonInteractiveConsole) { - log.Info("ACEmulator command prompt disabled - Environment.GetEnvironmentVariable(ACE_NONINTERACTIVE_CONSOLE) was true"); + log.LogInformation("ACEmulator command prompt disabled - Environment.GetEnvironmentVariable(ACE_NONINTERACTIVE_CONSOLE) was true"); return; } @@ -143,7 +143,7 @@ private static void CommandThread() if (commandLine == null) { - log.Info("ACEmulator command prompt disabled - console input stream was closed"); + log.LogInformation("ACEmulator command prompt disabled - console input stream was closed"); return; } @@ -158,7 +158,7 @@ private static void CommandThread() } catch (Exception ex) { - log.Error($"Exception while parsing command: {commandLine}", ex); + log.LogError(ex, "Exception while parsing command: {CommandLine}", commandLine); return; } try @@ -176,13 +176,13 @@ private static void CommandThread() } catch (Exception ex) { - log.Error($"Exception while invoking command handler for: {commandLine}", ex); + log.LogError(ex, "Exception while invoking command handler for: {CommandLine}", commandLine); } } } catch (Exception ex) { - log.Error($"Exception while getting command handler for: {commandLine}", ex); + log.LogError(ex, "Exception while getting command handler for: {CommandLine}", commandLine); } } } diff --git a/Source/ACE.Server/Command/Handlers/AccountCommands.cs b/Source/ACE.Server/Command/Handlers/AccountCommands.cs index a8e342dbbc..c659139372 100644 --- a/Source/ACE.Server/Command/Handlers/AccountCommands.cs +++ b/Source/ACE.Server/Command/Handlers/AccountCommands.cs @@ -174,7 +174,7 @@ public static void HandlePasswd(Session session, params string[] parameters) return; } - log.DebugFormat("{0} is changing their password", session.Player.Name); + log.LogDebug("{Name} is changing their password", session.Player.Name); var currentTime = DateTime.UtcNow; diff --git a/Source/ACE.Server/Command/Handlers/AdminCommands.cs b/Source/ACE.Server/Command/Handlers/AdminCommands.cs index 7e695a33ac..eca37a1e9a 100644 --- a/Source/ACE.Server/Command/Handlers/AdminCommands.cs +++ b/Source/ACE.Server/Command/Handlers/AdminCommands.cs @@ -2884,7 +2884,7 @@ public static void HandleFumble(Session session, params string[] parameters) item.SaveBiotaToDatabase(); } else - log.Warn($"0x{item.Guid}:{item.Name} for player {player.Name} lost from fumble failure."); + log.LogWarning("0x{Guid}:{ItemName} for player {PlayerName} lost from fumble failure.", item.Guid, item.Name, player.Name); } } else diff --git a/Source/ACE.Server/Command/Handlers/AdminShardCommands.cs b/Source/ACE.Server/Command/Handlers/AdminShardCommands.cs index 5d0dc58dd0..a5325db23b 100644 --- a/Source/ACE.Server/Command/Handlers/AdminShardCommands.cs +++ b/Source/ACE.Server/Command/Handlers/AdminShardCommands.cs @@ -32,7 +32,7 @@ public static void HandleCancelShutdown(Session session, params string[] paramet { var adminName = (session == null) ? "CONSOLE" : session.Player.Name; var msg = $"{adminName} has requested the pending shut down @ {ServerManager.ShutdownTime.ToLocalTime().ToCommonString()} ({ServerManager.ShutdownTime.ToCommonString()} UTC) be cancelled."; - log.Info(msg); + log.LogInformation("{Message:l}", msg); PlayerManager.BroadcastToAuditChannel(session?.Player, msg); ServerManager.CancelShutdown(); @@ -115,13 +115,13 @@ public static void ShutdownServer(Session session, params string[] parameters) var timeTillShutdown = TimeSpan.FromSeconds(ServerManager.ShutdownInterval); var timeRemaining = "The server will shut down in " + (timeTillShutdown.TotalSeconds > 120 ? $"{(int)timeTillShutdown.TotalMinutes} minutes." : $"{timeTillShutdown.TotalSeconds} seconds."); - log.Info($"{adminName} initiated a complete server shutdown @ {DateTime.Now.ToCommonString()} ({DateTime.UtcNow.ToCommonString()} UTC)"); - log.Info(timeRemaining); + log.LogInformation("{AdminName} initiated a complete server shutdown @ {Now} ({UtcNow} UTC)", adminName, DateTime.Now.ToCommonString(), DateTime.UtcNow.ToCommonString()); + log.LogInformation("{Message:l}", timeRemaining); PlayerManager.BroadcastToAuditChannel(session?.Player, $"{adminName} initiated a complete server shutdown @ {DateTime.Now.ToCommonString()} ({DateTime.UtcNow.ToCommonString()} UTC)"); if (adminText.Length > 0) { - log.Info("Admin message: " + adminText); + log.LogInformation("Admin message: {AdminText}", adminText); PlayerManager.BroadcastToAuditChannel(session?.Player, $"{adminName} sent the following message for the shutdown: {adminText}"); } diff --git a/Source/ACE.Server/Command/Handlers/CommandHandlerHelper.cs b/Source/ACE.Server/Command/Handlers/CommandHandlerHelper.cs index d18a53fae4..2980ae4a9f 100644 --- a/Source/ACE.Server/Command/Handlers/CommandHandlerHelper.cs +++ b/Source/ACE.Server/Command/Handlers/CommandHandlerHelper.cs @@ -25,7 +25,7 @@ public static void WriteOutputInfo(Session session, string output, ChatMessageTy ChatPacket.SendServerMessage(session, output, chatMessageType); } else - log.Info(output); + log.LogInformation("{Message:l}", output); } /// @@ -41,7 +41,7 @@ public static void WriteOutputDebug(Session session, string output, ChatMessageT ChatPacket.SendServerMessage(session, output, chatMessageType); } else - log.Debug(output); + log.LogDebug("{Message:l}", output); } /// @@ -57,7 +57,7 @@ public static void WriteOutputError(Session session, string output, ChatMessageT ChatPacket.SendServerMessage(session, output, chatMessageType); } else - log.Error(output); + log.LogError("{Message:l}", output); } /// diff --git a/Source/ACE.Server/Command/Handlers/DeveloperCommands.cs b/Source/ACE.Server/Command/Handlers/DeveloperCommands.cs index 3a76bf5e3c..aae5843d15 100644 --- a/Source/ACE.Server/Command/Handlers/DeveloperCommands.cs +++ b/Source/ACE.Server/Command/Handlers/DeveloperCommands.cs @@ -2247,8 +2247,8 @@ public static void HandleAuditObjectMaint(Session session, params string[] param { if (value.ObjMaint.RemoveKnownObject(kvp.Value, false)) { - if (log.IsDebugEnabled) - log.Debug($"AuditObjectMaint removed 0x{kvp.Value.ID:X8}:{kvp.Value.Name} (IsDestroyed:{kvp.Value.WeenieObj?.WorldObject?.IsDestroyed}, Position:{kvp.Value.Position}) from 0x{value.ID:X8}:{value.Name} (IsDestroyed:{value.WeenieObj?.WorldObject?.IsDestroyed}, Position:{value.Position}) [ObjectTable]"); + if (log.IsEnabled(LogLevel.Debug)) + log.LogDebug("AuditObjectMaint removed 0x{KvpID:X8}:{KvpName} (IsDestroyed:{WeenieObjIsDestroyed}, Position:{KvpPosition}) from 0x{ValueID:X8}:{ValueName} (IsDestroyed:{WeenieObjIsDestroyed2}, Position:{ValuePosition}) [ObjectTable]", kvp.Value.ID, kvp.Value.Name, kvp.Value.WeenieObj?.WorldObject?.IsDestroyed, kvp.Value.Position, value.ID, value.Name, value.WeenieObj?.WorldObject?.IsDestroyed, value.Position); objectTableErrors++; } } @@ -2260,8 +2260,8 @@ public static void HandleAuditObjectMaint(Session session, params string[] param { if (value.ObjMaint.RemoveVisibleObject(kvp.Value, false)) { - if (log.IsDebugEnabled) - log.Debug($"AuditObjectMaint removed 0x{kvp.Value.ID:X8}:{kvp.Value.Name} (IsDestroyed:{kvp.Value.WeenieObj?.WorldObject?.IsDestroyed}, Position:{kvp.Value.Position}) from 0x{value.ID:X8}:{value.Name} (IsDestroyed:{value.WeenieObj?.WorldObject?.IsDestroyed}, Position:{value.Position}) [VisibleObjectTable]"); + if (log.IsEnabled(LogLevel.Debug)) + log.LogDebug("AuditObjectMaint removed 0x{KvpID:X8}:{KvpName} (IsDestroyed:{WeenieObjIsDestroyed}, Position:{KvpPosition}) from 0x{ValueID:X8}:{ValueName} (IsDestroyed:{WeenieObjIsDestroyed2}, Position:{ValuePosition}) [VisibleObjectTable]", kvp.Value.ID, kvp.Value.Name, kvp.Value.WeenieObj?.WorldObject?.IsDestroyed, kvp.Value.Position, value.ID, value.Name, value.WeenieObj?.WorldObject?.IsDestroyed, value.Position); visibleObjectTableErrors++; } } @@ -2273,8 +2273,8 @@ public static void HandleAuditObjectMaint(Session session, params string[] param { if (value.ObjMaint.RemoveKnownPlayer(kvp.Value)) { - if (log.IsDebugEnabled) - log.Debug($"AuditObjectMaint removed 0x{kvp.Value.ID:X8}:{kvp.Value.Name} (IsDestroyed:{kvp.Value.WeenieObj?.WorldObject?.IsDestroyed}, Position:{kvp.Value.Position}) from 0x{value.ID:X8}:{value.Name} (IsDestroyed:{value.WeenieObj?.WorldObject?.IsDestroyed}, Position:{value.Position}) [VoyeurTable]"); + if (log.IsEnabled(LogLevel.Debug)) + log.LogDebug("AuditObjectMaint removed 0x{KvpID:X8}:{KvpName} (IsDestroyed:{WeenieObjIsDestroyed}, Position:{KvpPosition}) from 0x{ValueID:X8}:{ValueName} (IsDestroyed:{WeenieObjIsDestroyed2}, Position:{ValuePosition}) [VoyeurTable]", kvp.Value.ID, kvp.Value.Name, kvp.Value.WeenieObj?.WorldObject?.IsDestroyed, kvp.Value.Position, value.ID, value.Name, value.WeenieObj?.WorldObject?.IsDestroyed, value.Position); voyeurTableErrors++; } } @@ -2283,7 +2283,7 @@ public static void HandleAuditObjectMaint(Session session, params string[] param if (session != null) CommandHandlerHelper.WriteOutputInfo(session, $"Physics ObjMaint Audit Completed. Errors - objectTable: {objectTableErrors}, visibleObjectTable: {visibleObjectTableErrors}, voyeurTable: {voyeurTableErrors}"); - log.Info($"Physics ObjMaint Audit Completed. Errors - objectTable: {objectTableErrors}, visibleObjectTable: {visibleObjectTableErrors}, voyeurTable: {voyeurTableErrors}"); + log.LogInformation("Physics ObjMaint Audit Completed. Errors - objectTable: {ObjectTableErrors}, visibleObjectTable: {VisibleObjectTableErrors}, voyeurTable: {VoyeurTableErrors}", objectTableErrors, visibleObjectTableErrors, voyeurTableErrors); } [CommandHandler("lootgen", AccessLevel.Developer, CommandHandlerFlag.RequiresWorld, 1, "Generate a piece of loot from the LootGenerationFactory.", " ")] @@ -2356,7 +2356,7 @@ public static void HandleCILoot(Session session, params string[] parameters) if (wo != null) session.Player.TryCreateInInventoryWithNetworking(wo); else - log.Error($"{session.Player.Name}.HandleCILoot: LootGenerationFactory.CreateRandomLootObjects({tier}) returned null"); + log.LogError("{Name}.HandleCILoot: LootGenerationFactory.CreateRandomLootObjects({Tier}) returned null", session.Player.Name, tier); } } diff --git a/Source/ACE.Server/Command/Handlers/DeveloperDatabaseCommands.cs b/Source/ACE.Server/Command/Handlers/DeveloperDatabaseCommands.cs index 83694091ff..a1c2c93233 100644 --- a/Source/ACE.Server/Command/Handlers/DeveloperDatabaseCommands.cs +++ b/Source/ACE.Server/Command/Handlers/DeveloperDatabaseCommands.cs @@ -233,7 +233,7 @@ public static void HandleFixSpellBars(Session session, params string[] parameter var numberOfRecordsFixed = 0; - log.Info($"Starting FixSpellBarsPR2918 process. This could take a while..."); + log.LogInformation("Starting FixSpellBarsPR2918 process. This could take a while..."); using (var context = new ShardDbContext()) { @@ -241,8 +241,8 @@ public static void HandleFixSpellBars(Session session, params string[] parameter if (characterSpellBarsNotFixed.Count > 0) { - log.Warn("2020-04-11-00-Update-Character-SpellBars.sql patch not yet applied. Please apply this patch ASAP! Skipping FixSpellBarsPR2918 for now..."); - log.Fatal("2020-04-11-00-Update-Character-SpellBars.sql patch not yet applied. You must apply this patch before proceeding further..."); + log.LogWarning("2020-04-11-00-Update-Character-SpellBars.sql patch not yet applied. Please apply this patch ASAP! Skipping FixSpellBarsPR2918 for now..."); + log.LogCritical("2020-04-11-00-Update-Character-SpellBars.sql patch not yet applied. You must apply this patch before proceeding further..."); return; } @@ -285,7 +285,7 @@ public static void HandleFixSpellBars(Session session, params string[] parameter { Console.WriteLine("Saving changes..."); context.SaveChanges(); - log.Info($"Fixed {numberOfRecordsFixed:N0} CharacterPropertiesSpellBar records."); + log.LogInformation("Fixed {NumberOfRecordsFixed:N0} CharacterPropertiesSpellBar records.", numberOfRecordsFixed); } else { diff --git a/Source/ACE.Server/Command/Handlers/PlayerCommands.cs b/Source/ACE.Server/Command/Handlers/PlayerCommands.cs index 5ec4250bf1..b269326a0d 100644 --- a/Source/ACE.Server/Command/Handlers/PlayerCommands.cs +++ b/Source/ACE.Server/Command/Handlers/PlayerCommands.cs @@ -88,7 +88,7 @@ public static void HandleHouseSelect(Session session, bool confirmed, params str // ensure current multihouse owner if (!session.Player.IsMultiHouseOwner(false)) { - log.Warn($"{session.Player.Name} tried to /house-select {houseIdx}, but they are not currently a multi-house owner!"); + log.LogWarning("{Name} tried to /house-select {HouseIdx}, but they are not currently a multi-house owner!", session.Player.Name, houseIdx); return; } @@ -130,7 +130,7 @@ public static void HandleHouseSelect(Session session, bool confirmed, params str var player = PlayerManager.FindByGuid(keepHouse.HouseOwner ?? 0, out bool isOnline); if (player == null) { - log.Error($"{session.Player.Name}.HandleHouseSelect({houseIdx}) - couldn't find HouseOwner {keepHouse.HouseOwner} for {keepHouse.Name} ({keepHouse.Guid})"); + log.LogError("{PlayerName}.HandleHouseSelect({HouseIdx}) - couldn't find HouseOwner {HouseOwner} for {KeepHouseName} ({Guid})", session.Player.Name, houseIdx, keepHouse.HouseOwner, keepHouse.Name, keepHouse.Guid); return; } diff --git a/Source/ACE.Server/Entity/Actions/ActionQueue.cs b/Source/ACE.Server/Entity/Actions/ActionQueue.cs index 9433a6fdde..bee6185549 100644 --- a/Source/ACE.Server/Entity/Actions/ActionQueue.cs +++ b/Source/ACE.Server/Entity/Actions/ActionQueue.cs @@ -4,6 +4,8 @@ using System; using System.Collections.Concurrent; +using Microsoft.Extensions.Logging; + using ACE.Common.Logging; namespace ACE.Server.Entity.Actions @@ -42,12 +44,12 @@ public void RunActions() if (result is ActionEventDelegate actionEventDelegate) { if (actionEventDelegate.Action.Target is WorldObjects.WorldObject worldObject) - log.Warn($"ActionQueue Act() took {sw.Elapsed.TotalSeconds:N0}s. Method.Name: {actionEventDelegate.Action.Method.Name}, Target: {actionEventDelegate.Action.Target} 0x{worldObject.Guid}:{worldObject.Name}"); + log.LogWarning("ActionQueue Act() took {TotalSeconds:N0}s. Method.Name: {MethodName}, Target: {Target} 0x{Guid}:{WorldObjectName}", sw.Elapsed.TotalSeconds, actionEventDelegate.Action.Method.Name, actionEventDelegate.Action.Target, worldObject.Guid, worldObject.Name); else - log.Warn($"ActionQueue Act() took {sw.Elapsed.TotalSeconds:N0}s. Method.Name: {actionEventDelegate.Action.Method.Name}, Target: {actionEventDelegate.Action.Target}"); + log.LogWarning("ActionQueue Act() took {TotalSeconds:N0}s. Method.Name: {Name}, Target: {Target}", sw.Elapsed.TotalSeconds, actionEventDelegate.Action.Method.Name, actionEventDelegate.Action.Target); } else - log.Warn($"ActionQueue Act() took {sw.Elapsed.TotalSeconds:N0}s."); + log.LogWarning("ActionQueue Act() took {TotalSeconds:N0}s.", sw.Elapsed.TotalSeconds); } #endif diff --git a/Source/ACE.Server/Entity/Actions/DelayManager.cs b/Source/ACE.Server/Entity/Actions/DelayManager.cs index e409a69770..89e9a26343 100644 --- a/Source/ACE.Server/Entity/Actions/DelayManager.cs +++ b/Source/ACE.Server/Entity/Actions/DelayManager.cs @@ -62,7 +62,7 @@ public void EnqueueAction(IAction action) if (delayAction == null) { - log.Error("Non DelayAction IAction added to DelayManager"); + log.LogError("Non DelayAction IAction added to DelayManager"); return; } diff --git a/Source/ACE.Server/Entity/Aetheria.cs b/Source/ACE.Server/Entity/Aetheria.cs index 3ce2551f61..7010d721d7 100644 --- a/Source/ACE.Server/Entity/Aetheria.cs +++ b/Source/ACE.Server/Entity/Aetheria.cs @@ -246,7 +246,7 @@ public static void ActivateSigil(Player player, WorldObject source, WorldObject player.SendUseDoneEvent(); - log.DebugFormat("[CRAFTING] {0} revealed a {1} {2} with a surge of {3} on {4}:0x{5}", player.Name, color, randSigil, surgeSpell, target.Name, target.Guid); + log.LogDebug("[CRAFTING] {PlayerName} revealed a {Color} {RandSigil} with a surge of {SurgeSpell} on {TargetName}:0x{Guid}", player.Name, color, randSigil, surgeSpell, target.Name, target.Guid); } public static Dictionary SigilToEquipmentSet = new Dictionary() diff --git a/Source/ACE.Server/Entity/BodyPartTable.cs b/Source/ACE.Server/Entity/BodyPartTable.cs index 2e5a466c14..0933822084 100644 --- a/Source/ACE.Server/Entity/BodyPartTable.cs +++ b/Source/ACE.Server/Entity/BodyPartTable.cs @@ -27,7 +27,7 @@ public BodyPartTable(Weenie weenie) if (Weenie.PropertiesBodyPart == null) { - log.Error($"BodyPartTable is null for {weenie.WeenieClassId} - {weenie.ClassName}!"); + log.LogError("BodyPartTable is null for {WeenieClassId} - {ClassName}!", weenie.WeenieClassId, weenie.ClassName); return; } diff --git a/Source/ACE.Server/Entity/DamageEvent.cs b/Source/ACE.Server/Entity/DamageEvent.cs index e9bdfb5894..5fe979daa5 100644 --- a/Source/ACE.Server/Entity/DamageEvent.cs +++ b/Source/ACE.Server/Entity/DamageEvent.cs @@ -217,7 +217,7 @@ private float DoCalculateDamage(Creature attacker, Creature defender, WorldObjec { if ((attacker?.Guid.IsPlayer() ?? false) || (damageSource?.Guid.IsPlayer() ?? false)) { - log.Error($"DamageEvent.DoCalculateDamage({attacker?.Name} ({attacker?.Guid}), {defender?.Name} ({defender?.Guid}), {damageSource?.Name} ({damageSource?.Guid})) - DamageType == DamageType.Undef"); + log.LogError("DamageEvent.DoCalculateDamage({AttackerName} ({AttackerGuid}), {DefenderName} ({DefenderGuid}), {DamageSourceName} ({DamageSourceGuid})) - DamageType == DamageType.Undef", attacker?.Name, attacker?.Guid, defender?.Name, defender?.Guid, damageSource?.Name, damageSource?.Guid); GeneralFailure = true; } } @@ -481,7 +481,7 @@ public void GetBodyPart(Creature defender, Quadrant quadrant) if (bodyPart == CombatBodyPart.Undefined) { - log.DebugFormat("DamageEvent.GetBodyPart({0} ({1}) ) - couldn't find body part for wcid {2}, Quadrant {3}", defender?.Name, defender?.Guid, defender.WeenieClassId, quadrant); + log.LogDebug("DamageEvent.GetBodyPart({Name} ({Guid}) ) - couldn't find body part for wcid {WeenieClassId}, Quadrant {Quadrant}", defender?.Name, defender?.Guid, defender.WeenieClassId, quadrant); Evaded = true; return; } diff --git a/Source/ACE.Server/Entity/Fellowship.cs b/Source/ACE.Server/Entity/Fellowship.cs index 82174c0dfd..8b497c7322 100644 --- a/Source/ACE.Server/Entity/Fellowship.cs +++ b/Source/ACE.Server/Entity/Fellowship.cs @@ -191,7 +191,7 @@ public void RemoveFellowshipMember(Player player, Player leader) if (!fellowshipMembers.ContainsKey(player.Guid.Full)) { - log.Warn($"{leader.Name} tried to dismiss {player.Name} from the fellowship, but {player.Name} was not found in the fellowship"); + log.LogWarning("{LeaderName} tried to dismiss {PlayerName} from the fellowship, but {PlayerName} was not found in the fellowship", leader.Name, player.Name, player.Name); var done = true; @@ -199,11 +199,11 @@ public void RemoveFellowshipMember(Player player, Player leader) { if (player.Fellowship == this) { - log.Warn($"{player.Name} still has a reference to this fellowship somehow. This shouldn't happen"); + log.LogWarning("{Name} still has a reference to this fellowship somehow. This shouldn't happen", player.Name); done = false; } else - log.Warn($"{player.Name} has a reference to a different fellowship. {leader.Name} is possibly sending crafted data!"); + log.LogWarning("{PlayerName} has a reference to a different fellowship. {LeaderName} is possibly sending crafted data!", player.Name, leader.Name); } if (done) return; @@ -768,7 +768,7 @@ public void ProcessDropList(Dictionary> fellowshipMe var offlinePlayer = PlayerManager.FindByGuid(fellowGuid); var offlineName = offlinePlayer != null ? offlinePlayer.Name : "NULL"; - log.Warn($"Dropped fellow: {offlineName}"); + log.LogWarning("Dropped fellow: {OfflineName}", offlineName); fellowshipMembers.Remove(fellowGuid); } if (fellowGuids.Contains(FellowshipLeaderGuid)) diff --git a/Source/ACE.Server/Entity/GeneratorProfile.cs b/Source/ACE.Server/Entity/GeneratorProfile.cs index d73ac66420..bbbe04cea3 100644 --- a/Source/ACE.Server/Entity/GeneratorProfile.cs +++ b/Source/ACE.Server/Entity/GeneratorProfile.cs @@ -220,7 +220,7 @@ public void ProcessQueue() else { // this shouldn't happen (hopefully) - log.Warn($"[GENERATOR] 0x{Generator.Guid}:{Generator.WeenieClassId} ProcessQueue(): {LinkId}:{Biota.WeenieClassId} object(s) enqueued for {Generator.Name}, but MaxCreate({MaxCreate}) already reached!"); + log.LogWarning("[GENERATOR] 0x{Guid}:{GeneratorWeenieClassId} ProcessQueue(): {LinkId}:{BiotaWeenieClassId} object(s) enqueued for {Name}, but MaxCreate({MaxCreate}) already reached!", Generator.Guid, Generator.WeenieClassId, LinkId, Biota.WeenieClassId, Generator.Name, MaxCreate); } SpawnQueue.RemoveAt(index); @@ -253,7 +253,7 @@ public List Spawn() var wo = WorldObjectFactory.CreateNewWorldObject(Biota.WeenieClassId); if (wo == null) { - log.Warn($"[GENERATOR] 0x{Generator.Guid}:{Generator.WeenieClassId} {Generator.Name}.Spawn(): failed to create wcid {Biota.WeenieClassId}"); + log.LogWarning("[GENERATOR] 0x{Guid}:{GeneratorWeenieClassId} {Name}.Spawn(): failed to create wcid {BiotaWeenieClassId}", Generator.Guid, Generator.WeenieClassId, Generator.Name, Biota.WeenieClassId); return null; } @@ -306,8 +306,8 @@ public List Spawn() // This object still may be returned in the spawned collection if FirstSpawn is true. This is to prevent retry spam. if (!success) { - if (log.IsDebugEnabled) - log.Debug($"[GENERATOR] 0x{Generator.Guid}:{Generator.WeenieClassId} {Generator.Name}.Spawn(): failed to spawn {obj.Name} (0x{obj.Guid}:{obj.WeenieClassId}) from profile {LinkId} at {RegenLocationType}{(obj.Location != null ? $"\n Gen LOC: {Generator.Location?.ToLOCString()}\n Obj LOC: {obj.Location.ToLOCString()}" : "")}"); + if (log.IsEnabled(LogLevel.Debug)) + log.LogDebug("[GENERATOR] 0x{GeneratorGuid}:{GeneratorWeenieClassId} {GeneratorName}.Spawn(): failed to spawn {ObjName} (0x{ObjGuid}:{ObjWeenieClassId}) from profile {LinkId} at {RegenLocationType}{Locations}", Generator.Guid, Generator.WeenieClassId, Generator.Name, obj.Name, obj.Guid, obj.WeenieClassId, LinkId, RegenLocationType, (obj.Location != null ? $"\n Gen LOC: {Generator.Location?.ToLOCString()}\n Obj LOC: {obj.Location.ToLOCString()}" : "")); obj.Destroy(); } } @@ -398,7 +398,7 @@ public bool Spawn_Container(WorldObject obj) var success = Generator is Container container && container.TryAddToInventory(obj); if (!success) - log.Warn($"[GENERATOR] 0x{Generator.Guid}:{Generator.WeenieClassId} {Generator.Name}.Spawn_Container({obj.Name}) - failed to add to container inventory"); + log.LogWarning("[GENERATOR] 0x{Guid}:{WeenieClassId} {GeneratorName}.Spawn_Container({ObjName}) - failed to add to container inventory", Generator.Guid, Generator.WeenieClassId, Generator.Name, obj.Name); return success; } @@ -408,7 +408,7 @@ public bool Spawn_Shop(WorldObject obj) // spawn item in vendor shop inventory if (!(Generator is Vendor vendor)) { - log.Warn($"[GENERATOR] 0x{Generator.Guid}:{Generator.WeenieClassId} {Generator.Name}.Spawn_Shop({obj.Name}) - generator is not a vendor type"); + log.LogWarning("[GENERATOR] 0x{Guid}:{WeenieClassId} {GeneratorName}.Spawn_Shop({ObjName}) - generator is not a vendor type", Generator.Guid, Generator.WeenieClassId, Generator.Name, obj.Name); return false; } @@ -488,7 +488,7 @@ public List TreasureGenerator() } else { - log.DebugFormat("[GENERATOR] 0x{0}:{1} {2}.TreasureGenerator(): couldn't find death treasure or wielded treasure for ID {3}", Generator.Guid, Generator.WeenieClassId, Generator.Name, Biota.WeenieClassId); + log.LogDebug("[GENERATOR] 0x{Guid}:{GeneratorWeenieClassId} {Name}.TreasureGenerator(): couldn't find death treasure or wielded treasure for ID {BiotaWeenieClassId}", Generator.Guid, Generator.WeenieClassId, Generator.Name, Biota.WeenieClassId); return null; } } @@ -502,7 +502,7 @@ public void RemoveTreasure() var container = Generator as Container; if (container == null) { - log.WarnFormat("[GENERATOR] 0x{0}:{1} {2}.RemoveTreasure(): container not found", Generator.Guid, Generator.WeenieClassId, Generator.Name); + log.LogWarning("[GENERATOR] 0x{Guid}:{WeenieClassId} {Name}.RemoveTreasure(): container not found", Generator.Guid, Generator.WeenieClassId, Generator.Name); return; } foreach (var spawned in Spawned.Keys) @@ -510,7 +510,7 @@ public void RemoveTreasure() var inventoryObjGuid = new ObjectGuid(spawned); if (!container.Inventory.TryGetValue(inventoryObjGuid, out var inventoryObj)) { - log.WarnFormat("[GENERATOR] 0x{0}:{1} {2}.RemoveTreasure(): couldn't find {3}", Generator.Guid, Generator.WeenieClassId, Generator.Name, inventoryObjGuid); + log.LogWarning("[GENERATOR] 0x{Guid}:{WeenieClassId} {Name}.RemoveTreasure(): couldn't find {InventoryObjGuid}", Generator.Guid, Generator.WeenieClassId, Generator.Name, inventoryObjGuid); continue; } container.TryRemoveFromInventory(inventoryObjGuid); @@ -554,7 +554,7 @@ public void NotifyGenerator(ObjectGuid target, RegenerationType eventType) // log.Warn($"0x{Generator.Guid}:{Generator.Name}({Generator.WeenieClassId}).GeneratorProfile[{LinkId}].NotifyGenerator: RegenerationType = {eventType.ToString()}, WhenCreate = {whenCreate.ToString()}, Using {adjEventType.ToString()} as RegenerationType instead"); if (whenCreate != adjWhenCreate) - log.Warn($"[GENERATOR] 0x{Generator.Guid}:{Generator.Name}({Generator.WeenieClassId}).GeneratorProfile[{LinkId}].NotifyGenerator: RegenerationType = {eventType.ToString()}, WhenCreate = {whenCreate.ToString()}, Using {adjWhenCreate.ToString()} as WhenCreate instead"); + log.LogWarning("[GENERATOR] 0x{Guid}:{Name}({WeenieClassId}).GeneratorProfile[{LinkId}].NotifyGenerator: RegenerationType = {EventType}, WhenCreate = {WhenCreate}, Using {AdjWhenCreate} as WhenCreate instead", Generator.Guid, Generator.Name, Generator.WeenieClassId, LinkId, eventType.ToString(), whenCreate.ToString(), adjWhenCreate.ToString()); if (adjWhenCreate != adjEventType) return; diff --git a/Source/ACE.Server/Entity/Landblock.cs b/Source/ACE.Server/Entity/Landblock.cs index 6f4f063df6..c88ad77abe 100644 --- a/Source/ACE.Server/Entity/Landblock.cs +++ b/Source/ACE.Server/Entity/Landblock.cs @@ -806,7 +806,7 @@ public bool AddWorldObject(WorldObject wo) { if (wo.Location == null) { - log.DebugFormat("Landblock 0x{0} failed to add 0x{1:X8} {2}. Invalid Location", Id, wo.Biota.Id, wo.Name); + log.LogDebug("Landblock 0x{Id} failed to add 0x{BiotaId:X8} {Name}. Invalid Location", Id, wo.Biota.Id, wo.Name); return false; } @@ -833,28 +833,28 @@ private bool AddWorldObjectInternal(WorldObject wo) // Because this happens so rarely, and, it only seems to affect cloak projectiles, and, cloak projectiles are pretty benign, we simply don't add the object, and only log it as a warning. if (wo.WeenieType == WeenieType.ProjectileSpell) { - log.Warn($"Landblock 0x{Id} entered AddWorldObjectInternal in a cross-thread operation for a ProjectileSpell. This is normally not an issue unless it's happening more than once an hour."); + log.LogWarning("Landblock 0x{Id} entered AddWorldObjectInternal in a cross-thread operation for a ProjectileSpell. This is normally not an issue unless it's happening more than once an hour.", Id); return false; } - log.Error($"Landblock 0x{Id} entered AddWorldObjectInternal in a cross-thread operation."); - log.Error($"Landblock 0x{Id} CurrentLandblockGroup: {CurrentLandblockGroup}"); - log.Error($"LandblockManager.CurrentMultiThreadedTickingLandblockGroup.Value: {LandblockManager.CurrentMultiThreadedTickingLandblockGroup.Value}"); + log.LogError("Landblock 0x{Id} entered AddWorldObjectInternal in a cross-thread operation.", Id); + log.LogError("Landblock 0x{Id} CurrentLandblockGroup: {CurrentLandblockGroup}", Id, CurrentLandblockGroup); + log.LogError("LandblockManager.CurrentMultiThreadedTickingLandblockGroup.Value: {CurrentMultiThreadedTickingLandblockGroup}", LandblockManager.CurrentMultiThreadedTickingLandblockGroup.Value); - log.Error($"wo: 0x{wo.Guid}:{wo.Name} [{wo.WeenieClassId} - {wo.WeenieType}], previous landblock 0x{wo.CurrentLandblock?.Id}"); + log.LogError("wo: 0x{Guid}:{Name} [{WeenieClassId} - {WeenieType}], previous landblock 0x{Id}", wo.Guid, wo.Name, wo.WeenieClassId, wo.WeenieType, wo.CurrentLandblock?.Id); if (wo.WeenieType == WeenieType.ProjectileSpell) { if (wo.ProjectileSource != null) - log.Error($"wo.ProjectileSource: 0x{wo.ProjectileSource?.Guid}:{wo.ProjectileSource?.Name}, position: {wo.ProjectileSource?.Location}"); + log.LogError("wo.ProjectileSource: 0x{Guid}:{Name}, position: {Location}", wo.ProjectileSource?.Guid, wo.ProjectileSource?.Name, wo.ProjectileSource?.Location); if (wo.ProjectileTarget != null) - log.Error($"wo.ProjectileTarget: 0x{wo.ProjectileTarget?.Guid}:{wo.ProjectileTarget?.Name}, position: {wo.ProjectileTarget?.Location}"); + log.LogError("wo.ProjectileTarget: 0x{Guid}:{Name}, position: {Location}", wo.ProjectileTarget?.Guid, wo.ProjectileTarget?.Name, wo.ProjectileTarget?.Location); } - log.Error(System.Environment.StackTrace); + log.LogError("{Message:l}", System.Environment.StackTrace); - log.Error("PLEASE REPORT THIS TO THE ACE DEV TEAM !!!"); + log.LogError("PLEASE REPORT THIS TO THE ACE DEV TEAM !!!"); // This may still crash... } @@ -876,17 +876,17 @@ private bool AddWorldObjectInternal(WorldObject wo) if (wo.Generator != null) { - if (log.IsDebugEnabled) - log.Debug($"AddWorldObjectInternal: couldn't spawn 0x{wo.Guid}:{wo.Name} [{wo.WeenieClassId} - {wo.WeenieType}] at {wo.Location.ToLOCString()} from generator {wo.Generator.WeenieClassId} - 0x{wo.Generator.Guid}:{wo.Generator.Name}"); + if (log.IsEnabled(LogLevel.Debug)) + log.LogDebug("AddWorldObjectInternal: couldn't spawn 0x{WoGuid}:{WoName} [{WoWeenieClassId} - {WeenieType}] at {Location} from generator {GeneratorWeenieClassId} - 0x{GeneratorGuid}:{GeneratorName}", wo.Guid, wo.Name, wo.WeenieClassId, wo.WeenieType, wo.Location.ToLOCString(), wo.Generator.WeenieClassId, wo.Generator.Guid, wo.Generator.Name); wo.NotifyOfEvent(RegenerationType.PickUp); // Notify generator the generated object is effectively destroyed, use Pickup to catch both cases. } else if (wo.IsGenerator) // Some generators will fail random spawns if they're circumference spans over water or cliff edges { - if (log.IsDebugEnabled) - log.Debug($"AddWorldObjectInternal: couldn't spawn generator 0x{wo.Guid}:{wo.Name} [{wo.WeenieClassId} - {wo.WeenieType}] at {wo.Location.ToLOCString()}"); + if (log.IsEnabled(LogLevel.Debug)) + log.LogDebug("AddWorldObjectInternal: couldn't spawn generator 0x{Guid}:{Name} [{WeenieClassId} - {WeenieType}] at {Location}", wo.Guid, wo.Name, wo.WeenieClassId, wo.WeenieType, wo.Location.ToLOCString()); } else if (wo.ProjectileTarget == null && !(wo is SpellProjectile)) - log.Warn($"AddWorldObjectInternal: couldn't spawn 0x{wo.Guid}:{wo.Name} [{wo.WeenieClassId} - {wo.WeenieType}] at {wo.Location.ToLOCString()}"); + log.LogWarning("AddWorldObjectInternal: couldn't spawn 0x{Guid}:{Name} [{WeenieClassId} - {WeenieType}] at {Location}", wo.Guid, wo.Name, wo.WeenieClassId, wo.WeenieType, wo.Location.ToLOCString()); return false; } @@ -914,7 +914,7 @@ private bool AddWorldObjectInternal(WorldObject wo) if (corpse != null) { - log.Warn($"[CORPSE] Landblock.AddWorldObjectInternal(): {wo.Name} (0x{wo.Guid}) exceeds the per player limit of {corpseLimit} corpses for 0x{Id.Landblock:X4}. Adjusting TimeToRot for oldest {corpse.Name} (0x{corpse.Guid}), CreationTimestamp: {corpse.CreationTimestamp} ({Common.Time.GetDateTimeFromTimestamp(corpse.CreationTimestamp ?? 0).ToLocalTime():yyyy-MM-dd HH:mm:ss}), to Corpse.EmptyDecayTime({Corpse.EmptyDecayTime})."); + log.LogWarning("[CORPSE] Landblock.AddWorldObjectInternal(): {WoName} (0x{WoGuid}) exceeds the per player limit of {CorpseLimit} corpses for 0x{Landblock:X4}. Adjusting TimeToRot for oldest {CorpseName} (0x{CorpseGuid}), CreationTimestamp: {CreationTimestamp} ({DateTimeFromTimestamp:yyyy-MM-dd HH:mm:ss}), to Corpse.EmptyDecayTime({EmptyDecayTime}).", wo.Name, wo.Guid, corpseLimit, Id.Landblock, corpse.Name, corpse.Guid, corpse.CreationTimestamp, Common.Time.GetDateTimeFromTimestamp(corpse.CreationTimestamp ?? 0).ToLocalTime(), Corpse.EmptyDecayTime); corpse.TimeToRot = Corpse.EmptyDecayTime; } } @@ -944,15 +944,15 @@ private void RemoveWorldObjectInternal(ObjectGuid objectId, bool adjacencyMove = { if (CurrentLandblockGroup != null && CurrentLandblockGroup != LandblockManager.CurrentMultiThreadedTickingLandblockGroup.Value) { - log.Error($"Landblock 0x{Id} entered RemoveWorldObjectInternal in a cross-thread operation."); - log.Error($"Landblock 0x{Id} CurrentLandblockGroup: {CurrentLandblockGroup}"); - log.Error($"LandblockManager.CurrentMultiThreadedTickingLandblockGroup.Value: {LandblockManager.CurrentMultiThreadedTickingLandblockGroup.Value}"); + log.LogError("Landblock 0x{Id} entered RemoveWorldObjectInternal in a cross-thread operation.", Id); + log.LogError("Landblock 0x{Id} CurrentLandblockGroup: {CurrentLandblockGroup}", Id, CurrentLandblockGroup); + log.LogError("LandblockManager.CurrentMultiThreadedTickingLandblockGroup.Value: {CurrentMultiThreadedTickingLandblockGroup}", LandblockManager.CurrentMultiThreadedTickingLandblockGroup.Value); - log.Error($"objectId: 0x{objectId}"); + log.LogError("objectId: 0x{ObjectId}", objectId); - log.Error(System.Environment.StackTrace); + log.LogError("{Message:l}", System.Environment.StackTrace); - log.Error("PLEASE REPORT THIS TO THE ACE DEV TEAM !!!"); + log.LogError("PLEASE REPORT THIS TO THE ACE DEV TEAM !!!"); // This may still crash... } @@ -963,7 +963,7 @@ private void RemoveWorldObjectInternal(ObjectGuid objectId, bool adjacencyMove = else if (!pendingAdditions.Remove(objectId, out wo)) { if (showError) - log.Warn($"RemoveWorldObjectInternal: Couldn't find {objectId.Full:X8}"); + log.LogWarning("RemoveWorldObjectInternal: Couldn't find {ObjectId:X8}", objectId.Full); return; } diff --git a/Source/ACE.Server/Entity/LandblockGroup.cs b/Source/ACE.Server/Entity/LandblockGroup.cs index b478063290..6ea6600a20 100644 --- a/Source/ACE.Server/Entity/LandblockGroup.cs +++ b/Source/ACE.Server/Entity/LandblockGroup.cs @@ -89,13 +89,13 @@ public bool Add(Landblock landblock) { if (IsDungeon) { - log.Error($"[LANDBLOCK GROUP] You cannot add a landblock ({landblock.Id}) to a LandblockGroup that represents a single Dungeon Landblock"); + log.LogError("[LANDBLOCK GROUP] You cannot add a landblock ({Id}) to a LandblockGroup that represents a single Dungeon Landblock", landblock.Id); return false; } if (landblock.IsDungeon) { - log.Error($"[LANDBLOCK GROUP] You cannot add a dungeon landblock ({landblock.Id}) to an existing LandblockGroup"); + log.LogError("[LANDBLOCK GROUP] You cannot add a dungeon landblock ({Id}) to an existing LandblockGroup", landblock.Id); return false; } } diff --git a/Source/ACE.Server/Entity/Motion.cs b/Source/ACE.Server/Entity/Motion.cs index f40e975d13..9fb3134ab8 100644 --- a/Source/ACE.Server/Entity/Motion.cs +++ b/Source/ACE.Server/Entity/Motion.cs @@ -62,7 +62,7 @@ public Motion(WorldObject wo, WorldObject target, MovementType type) else { Stance = new Motion(MotionStance.NonCombat).Stance; - log.Warn($"{wo.Name} (0x{wo.Guid}) has a null CurrentMotionState, subbing in new Motion(MotionStance.NonCombat) for it."); + log.LogWarning("{Name} (0x{Guid}) has a null CurrentMotionState, subbing in new Motion(MotionStance.NonCombat) for it.", wo.Name, wo.Guid); } MovementType = type; Position = new Position(target.Location); @@ -79,7 +79,7 @@ public Motion(WorldObject wo, Position position) else { Stance = new Motion(MotionStance.NonCombat).Stance; - log.Warn($"{wo.Name} (0x{wo.Guid}) has a null CurrentMotionState, subbing in new Motion(MotionStance.NonCombat) for it."); + log.LogWarning("{Name} (0x{Guid}) has a null CurrentMotionState, subbing in new Motion(MotionStance.NonCombat) for it.", wo.Name, wo.Guid); } MovementType = MovementType.MoveToPosition; Position = new Position(position); @@ -95,7 +95,7 @@ public Motion(WorldObject wo, Position position, float heading) else { Stance = new Motion(MotionStance.NonCombat).Stance; - log.Warn($"{wo.Name} (0x{wo.Guid}) has a null CurrentMotionState, subbing in new Motion(MotionStance.NonCombat) for it."); + log.LogWarning("{Name} (0x{Guid}) has a null CurrentMotionState, subbing in new Motion(MotionStance.NonCombat) for it.", wo.Name, wo.Guid); } MovementType = MovementType.TurnToHeading; Position = new Position(position); @@ -115,7 +115,7 @@ public Motion(WorldObject wo, MotionCommand motion, float speed = 1.0f) else { Stance = new Motion(MotionStance.NonCombat).Stance; - log.Warn($"{wo.Name} (0x{wo.Guid}) has a null CurrentMotionState, subbing in new Motion(MotionStance.NonCombat) for it."); + log.LogWarning("{Name} (0x{Guid}) has a null CurrentMotionState, subbing in new Motion(MotionStance.NonCombat) for it.", wo.Name, wo.Guid); } SetForwardCommand(motion, speed); } diff --git a/Source/ACE.Server/Entity/Mutations/Effect.cs b/Source/ACE.Server/Entity/Mutations/Effect.cs index b0380fffd1..ffbead3c89 100644 --- a/Source/ACE.Server/Entity/Mutations/Effect.cs +++ b/Source/ACE.Server/Entity/Mutations/Effect.cs @@ -126,7 +126,7 @@ public bool Validate(WorldObject wo, EffectArgument result, EffectArgument arg1, if (!arg1.IsValid) { - log.Error($"{wo.Name} ({wo.Guid}).TryMutate({type}) - argument 1 invalid"); + log.LogError("{Name} ({Guid}).TryMutate({Type}) - argument 1 invalid", wo.Name, wo.Guid, type); return false; } @@ -145,7 +145,7 @@ public bool Validate(WorldObject wo, EffectArgument result, EffectArgument arg1, if (!arg2.IsValid) { - log.Error($"{wo.Name} ({wo.Guid}).TryMutate({type}) - argument 2 invalid"); + log.LogError("{Name} ({Guid}).TryMutate({Type}) - argument 2 invalid", wo.Name, wo.Guid, type); return false; } break; diff --git a/Source/ACE.Server/Entity/Mutations/EffectArgument.cs b/Source/ACE.Server/Entity/Mutations/EffectArgument.cs index ba128ac2b4..e9a8f79b36 100644 --- a/Source/ACE.Server/Entity/Mutations/EffectArgument.cs +++ b/Source/ACE.Server/Entity/Mutations/EffectArgument.cs @@ -1,7 +1,8 @@ using System; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.Entity.Enum; using ACE.Entity.Enum.Properties; using ACE.Server.Factories.Enum; @@ -113,7 +114,7 @@ public double ToDouble() case EffectArgumentType.Double: return DoubleVal; } - log.Error($"EffectArgument.ToDouble() - invalid type {Type}"); + log.LogError("EffectArgument.ToDouble() - invalid type {Type}", Type); return 0.0; } @@ -128,7 +129,7 @@ public int ToInt() case EffectArgumentType.Double: return (int)DoubleVal; } - log.Error($"EffectArgument.ToInt() - invalid type {Type}"); + log.LogError("EffectArgument.ToInt() - invalid type {Type}", Type); return 0; } @@ -143,7 +144,7 @@ public long ToLong() case EffectArgumentType.Double: return (long)DoubleVal; } - log.Error($"EffectArgument.ToLong() - invalid type {Type}"); + log.LogError("EffectArgument.ToLong() - invalid type {Type}", Type); return 0; } @@ -231,7 +232,7 @@ public bool ResolveValue(WorldObject item) this = GTVariables[IntVal]; IsValid = true;*/ - log.Error($"TODO: EffectArgumentType.Variable"); + log.LogError("TODO: EffectArgumentType.Variable"); break; } diff --git a/Source/ACE.Server/Entity/Mutations/EffectArgumentOp.cs b/Source/ACE.Server/Entity/Mutations/EffectArgumentOp.cs index 4bb1a0f076..b8302fd2e2 100644 --- a/Source/ACE.Server/Entity/Mutations/EffectArgumentOp.cs +++ b/Source/ACE.Server/Entity/Mutations/EffectArgumentOp.cs @@ -53,7 +53,7 @@ public partial class EffectArgument break; } - log.Error($"EffectArgument.Add() - invalid type {a.Type}, {b.Type}"); + log.LogError("EffectArgument.Add() - invalid type {AType}, {BType}", a.Type, b.Type); return null; } @@ -102,7 +102,7 @@ public partial class EffectArgument break; } - log.Error($"EffectArgument.Subtract() - invalid type {a.Type}, {b.Type}"); + log.LogError("EffectArgument.Subtract() - invalid type {AType}, {BType}", a.Type, b.Type); return null; } @@ -151,7 +151,7 @@ public partial class EffectArgument break; } - log.Error($"EffectArgument.Multiply() - invalid type {a.Type}, {b.Type}"); + log.LogError("EffectArgument.Multiply() - invalid type {AType}, {BType}", a.Type, b.Type); return null; } @@ -200,7 +200,7 @@ public partial class EffectArgument break; } - log.Error($"EffectArgument.Divide() - invalid type {a.Type}, {b.Type}"); + log.LogError("EffectArgument.Divide() - invalid type {AType}, {BType}", a.Type, b.Type); return null; } @@ -209,7 +209,7 @@ public partial class EffectArgument { if (a.Type != b.Type) { - log.Error($"EffectArgument.LessThan() - type mismatch {a.Type} {b.Type}"); + log.LogError("EffectArgument.LessThan() - type mismatch {AType} {BType}", a.Type, b.Type); return false; } @@ -231,7 +231,7 @@ public partial class EffectArgument { if (a.Type != b.Type) { - log.Error($"EffectArgument.GreaterThan() - type mismatch {a.Type} {b.Type}"); + log.LogError("EffectArgument.GreaterThan() - type mismatch {AType} {BType}", a.Type, b.Type); return false; } diff --git a/Source/ACE.Server/Entity/Mutations/MutationCache.cs b/Source/ACE.Server/Entity/Mutations/MutationCache.cs index 0e1e7e421e..d126150e2d 100644 --- a/Source/ACE.Server/Entity/Mutations/MutationCache.cs +++ b/Source/ACE.Server/Entity/Mutations/MutationCache.cs @@ -63,7 +63,7 @@ private static MutationFilter BuildMutation(uint mutationId) { if (!mutationIdToFilename.TryGetValue(mutationId, out var filename)) { - log.Error($"MutationCache.BuildMutation({mutationId:X8}) - embedded resource not found"); + log.LogError("MutationCache.BuildMutation({MutationId:X8}) - embedded resource not found", mutationId); return null; } @@ -76,7 +76,7 @@ private static MutationFilter BuildMutation(string filename) if (lines == null) { - log.Error($"MutationCache.BuildMutation({filename}) - embedded resource not found"); + log.LogError("MutationCache.BuildMutation({Filename}) - embedded resource not found", filename); return null; } @@ -111,7 +111,7 @@ private static MutationFilter BuildMutation(string filename) if (line.Contains("Tier chances", StringComparison.OrdinalIgnoreCase)) { if (outcome != null && outcome.EffectLists.Last().Chance != 1.0f) - log.Error($"MutationCache.BuildMutation({filename}) - {prevMutationLine} total {outcome.EffectLists.Last().Chance}, expected 1.0"); + log.LogError("MutationCache.BuildMutation({Filename}) - {PrevMutationLine} total {Chance}, expected 1.0", filename, prevMutationLine, outcome.EffectLists.Last().Chance); mutation = new Mutation(); mutationFilter.Mutations.Add(mutation); @@ -127,7 +127,7 @@ private static MutationFilter BuildMutation(string filename) } else { - log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse tier chances for {mutationLine}: {tierPiece}"); + log.LogError("MutationCache.BuildMutation({Filename}) - couldn't parse tier chances for {MutationLine}: {TierPiece}", filename, mutationLine, tierPiece); mutation.Chances.Add(0.0f); } } @@ -145,7 +145,7 @@ private static MutationFilter BuildMutation(string filename) if (totalChance >= 1.0M) { if (totalChance > 1.0M) - log.Error($"MutationCache.BuildMutation({filename}) - {mutationLine} total {totalChance}, expected 1.0"); + log.LogError("MutationCache.BuildMutation({Filename}) - {MutationLine} total {TotalChance}, expected 1.0", filename, mutationLine, totalChance); outcome = new MutationOutcome(); mutation.Outcomes.Add(outcome); @@ -165,7 +165,7 @@ private static MutationFilter BuildMutation(string filename) } else { - log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {line} for {mutationLine}"); + log.LogError("MutationCache.BuildMutation({Filename}) - couldn't parse {Line} for {MutationLine}", filename, line, mutationLine); } continue; } @@ -183,7 +183,7 @@ private static MutationFilter BuildMutation(string filename) if (pieces.Length != 2) { - log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {line}"); + log.LogError("MutationCache.BuildMutation({Filename}) - couldn't parse {Line}", filename, line); continue; } @@ -214,7 +214,7 @@ private static MutationFilter BuildMutation(string filename) if (subpieces.Length != 2) { - log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {line}"); + log.LogError("MutationCache.BuildMutation({Filename}) - couldn't parse {Line}", filename, line); continue; } @@ -229,7 +229,7 @@ private static MutationFilter BuildMutation(string filename) } if (outcome != null && outcome.EffectLists.Last().Chance != 1.0f) - log.Error($"MutationCache.BuildMutation({filename}) - {mutationLine} total {outcome.EffectLists.Last().Chance}, expected 1.0"); + log.LogError("MutationCache.BuildMutation({Filename}) - {MutationLine} total {Chance}, expected 1.0", filename, mutationLine, outcome.EffectLists.Last().Chance); timer.Stop(); @@ -258,7 +258,7 @@ private static EffectArgument ParseEffectArgument(string filename, Effect effect else if (Enum.TryParse(operand, out Skill skill)) effectArgument.IntVal = (int)skill; else - log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse IntVal {operand}"); + log.LogError("MutationCache.BuildMutation({Filename}) - couldn't parse IntVal {Operand}", filename, operand); } break; @@ -266,7 +266,7 @@ private static EffectArgument ParseEffectArgument(string filename, Effect effect if (!long.TryParse(operand, out effectArgument.LongVal)) { - log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse Int64Val {operand}"); + log.LogError("MutationCache.BuildMutation({Filename}) - couldn't parse Int64Val {Operand}", filename, operand); } break; @@ -274,7 +274,7 @@ private static EffectArgument ParseEffectArgument(string filename, Effect effect if (!double.TryParse(operand, out effectArgument.DoubleVal)) { - log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse DoubleVal {operand}"); + log.LogError("MutationCache.BuildMutation({Filename}) - couldn't parse DoubleVal {Operand}", filename, operand); } break; @@ -289,7 +289,7 @@ private static EffectArgument ParseEffectArgument(string filename, Effect effect if (Enum.TryParse(operand, out PropertyInt propInt)) effectArgument.StatIdx = (int)propInt; else - log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyInt.{operand}"); + log.LogError("MutationCache.BuildMutation({Filename}) - couldn't parse PropertyInt.{Operand}", filename, operand); break; case StatType.Int64: @@ -297,7 +297,7 @@ private static EffectArgument ParseEffectArgument(string filename, Effect effect if (Enum.TryParse(operand, out PropertyInt64 propInt64)) effectArgument.StatIdx = (int)propInt64; else - log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyInt64.{operand}"); + log.LogError("MutationCache.BuildMutation({Filename}) - couldn't parse PropertyInt64.{Operand}", filename, operand); break; case StatType.Float: @@ -305,7 +305,7 @@ private static EffectArgument ParseEffectArgument(string filename, Effect effect if (Enum.TryParse(operand, out PropertyFloat propFloat)) effectArgument.StatIdx = (int)propFloat; else - log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyFloat.{operand}"); + log.LogError("MutationCache.BuildMutation({Filename}) - couldn't parse PropertyFloat.{Operand}", filename, operand); break; case StatType.Bool: @@ -313,7 +313,7 @@ private static EffectArgument ParseEffectArgument(string filename, Effect effect if (Enum.TryParse(operand, out PropertyBool propBool)) effectArgument.StatIdx = (int)propBool; else - log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyBool.{operand}"); + log.LogError("MutationCache.BuildMutation({Filename}) - couldn't parse PropertyBool.{Operand}", filename, operand); break; case StatType.DataID: @@ -321,11 +321,11 @@ private static EffectArgument ParseEffectArgument(string filename, Effect effect if (Enum.TryParse(operand, out PropertyDataId propDID)) effectArgument.StatIdx = (int)propDID; else - log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyBool.{operand}"); + log.LogError("MutationCache.BuildMutation({Filename}) - couldn't parse PropertyBool.{Operand}", filename, operand); break; default: - log.Error($"MutationCache.BuildMutation({filename}) - unknown PropertyType.{operand}"); + log.LogError("MutationCache.BuildMutation({Filename}) - unknown PropertyType.{Operand}", filename, operand); break; } break; @@ -335,7 +335,7 @@ private static EffectArgument ParseEffectArgument(string filename, Effect effect var match = Regex.Match(operand, @"Random\(([\d.-]+), ([\d.-]+)\)"); if (!match.Success || !float.TryParse(match.Groups[1].Value, out effectArgument.MinVal) || !float.TryParse(match.Groups[2].Value, out effectArgument.MaxVal)) - log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {operand}"); + log.LogError("MutationCache.BuildMutation({Filename}) - couldn't parse {Operand}", filename, operand); break; @@ -344,12 +344,12 @@ private static EffectArgument ParseEffectArgument(string filename, Effect effect match = Regex.Match(operand, @"\[(\d+)\]"); if (!match.Success || !int.TryParse(match.Groups[1].Value, out effectArgument.IntVal)) - log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {operand}"); + log.LogError("MutationCache.BuildMutation({Filename}) - couldn't parse {Operand}", filename, operand); break; default: - log.Error($"MutationCache.BuildMutation({filename}) - unknown EffectArgumentType from {operand}"); + log.LogError("MutationCache.BuildMutation({Filename}) - unknown EffectArgumentType from {Operand}", filename, operand); break; } return effectArgument; @@ -549,7 +549,7 @@ private static void CacheResourceNames() if (pieces.Length < 2) { - log.Error($"MutationCache.CacheResourceNames() - unknown resource format {resourceName}"); + log.LogError("MutationCache.CacheResourceNames() - unknown resource format {ResourceName}", resourceName); continue; } var shortName = pieces[pieces.Length - 2]; diff --git a/Source/ACE.Server/Entity/PositionExtensions.cs b/Source/ACE.Server/Entity/PositionExtensions.cs index 2d633600df..07c3d8a1ed 100644 --- a/Source/ACE.Server/Entity/PositionExtensions.cs +++ b/Source/ACE.Server/Entity/PositionExtensions.cs @@ -129,8 +129,8 @@ public static uint GetCell(this Position p) } catch (Exception e) { - log.ErrorFormat("GetCell() threw an exception: {0}\nposition as LOC => {1}", e.ToString(), p.ToLOCString()); - log.Error(e); + log.LogError("GetCell() threw an exception: {E}\nposition as LOC => {P}", e.ToString(), p.ToLOCString()); + log.LogError(e, "{Message:l}", e.Message); return 0; } @@ -361,8 +361,8 @@ public static bool IsRotationValid(this Quaternion q) public static bool AttemptToFixRotation(this Position pos, WorldObject wo, PositionType positionType) { - log.Warn($"detected bad quaternion x y z w for {wo.Name} (0x{wo.Guid}) | WCID: {wo.WeenieClassId} | WeenieType: {wo.WeenieType} | PositionType: {positionType}"); - log.Warn($"before fix: {pos.ToLOCString()}"); + log.LogWarning("detected bad quaternion x y z w for {Name} (0x{Guid}) | WCID: {WeenieClassId} | WeenieType: {WeenieType} | PositionType: {PositionType}", wo.Name, wo.Guid, wo.WeenieClassId, wo.WeenieType, positionType); + log.LogWarning("before fix: {Pos}", pos.ToLOCString()); var normalized = Quaternion.Normalize(pos.Rotation); @@ -371,7 +371,7 @@ public static bool AttemptToFixRotation(this Position pos, WorldObject wo, Posit if (success) pos.Rotation = normalized; - log.Warn($" after fix: {pos.ToLOCString()}"); + log.LogWarning(" after fix: {Pos}", pos.ToLOCString()); return success; } diff --git a/Source/ACE.Server/Entity/Proficiency.cs b/Source/ACE.Server/Entity/Proficiency.cs index d4c271bcd2..095e7aff49 100644 --- a/Source/ACE.Server/Entity/Proficiency.cs +++ b/Source/ACE.Server/Entity/Proficiency.cs @@ -43,7 +43,7 @@ public static void OnSuccessUse(Player player, CreatureSkill skill, uint difficu if (timeDiff < 0) { // can happen if server clock is rewound back in time - log.Warn($"Proficiency.OnSuccessUse({player.Name}, {skill.Skill}, {difficulty}) - timeDiff: {timeDiff}"); + log.LogWarning("Proficiency.OnSuccessUse({Name}, {Skill}, {Difficulty}) - timeDiff: {TimeDiff}", player.Name, skill.Skill, difficulty, timeDiff); skill.PropertiesSkill.LastUsedTime = currentTime; // update to prevent log spam return; } @@ -77,7 +77,7 @@ public static void OnSuccessUse(Player player, CreatureSkill skill, uint difficu if (totalXPGranted > 10000) { - log.Warn($"Proficiency.OnSuccessUse({player.Name}, {skill.Skill}, {difficulty}) - totalXPGranted: {totalXPGranted:N0}"); + log.LogWarning("Proficiency.OnSuccessUse({Name}, {Skill}, {Difficulty}) - totalXPGranted: {TotalXPGranted:N0}", player.Name, skill.Skill, difficulty, totalXPGranted); } var maxLevel = Player.GetMaxLevel(); @@ -117,7 +117,7 @@ public static void OnSuccessUse(Player player, CreatureSkill skill, int difficul { if (difficulty < 0) { - log.Error($"Proficiency.OnSuccessUse({player.Name}, {skill.Skill}, {difficulty}) - difficulty cannot be negative"); + log.LogError("Proficiency.OnSuccessUse({Name}, {Skill}, {Difficulty}) - difficulty cannot be negative", player.Name, skill.Skill, difficulty); return; } OnSuccessUse(player, skill, (uint)difficulty); diff --git a/Source/ACE.Server/Entity/Spell.cs b/Source/ACE.Server/Entity/Spell.cs index 042e1e3b83..1a2d5c337d 100644 --- a/Source/ACE.Server/Entity/Spell.cs +++ b/Source/ACE.Server/Entity/Spell.cs @@ -82,7 +82,7 @@ public void Init(uint spellID, bool loadDB = true) Formula = new SpellFormula(this, _formula); if (loadDB && (_spell == null || _spellBase == null)) - log.DebugFormat("Spell.Init(spellID = {0}, loadDB = {1}) failed! {2} {3}", spellID, loadDB, (_spell == null ? "_spell was null" : ""), (_spellBase == null ? "_spellBase was null" : "")); + log.LogDebug("Spell.Init(spellID = {SpellID}, loadDB = {LoadDB}) failed! {SpellNote} {SpellBaseNote}", spellID, loadDB, (_spell == null ? "_spell was null" : ""), (_spellBase == null ? "_spellBase was null" : "")); } /// diff --git a/Source/ACE.Server/Entity/Tailoring.cs b/Source/ACE.Server/Entity/Tailoring.cs index 70f86d5a76..e59e87ec49 100644 --- a/Source/ACE.Server/Entity/Tailoring.cs +++ b/Source/ACE.Server/Entity/Tailoring.cs @@ -333,7 +333,7 @@ public static void Finalize(Player player, WorldObject source, WorldObject targe // errors shouldn't be possible here, since the items were pre-validated, but just in case... if (!player.TryCreateInInventoryWithNetworking(result)) { - log.Error($"[TAILORING] Tailoring.Finalize({player.Name} (0x{player.Guid}), {source.Name} (0x{source.Guid}), {target.Name} (0x{target.Guid}), {result.Name}) - couldn't add {result.Name} ({result.Guid}) to player inventory after validation, this shouldn't happen!"); + log.LogError("[TAILORING] Tailoring.Finalize({PlayerName} (0x{PlayerGuid}), {SourceName} (0x{SourceGuid}), {TargetName} (0x{TargetGuid}), {ResultName}) - couldn't add {ResultName} ({ResultGuid}) to player inventory after validation, this shouldn't happen!", player.Name, player.Guid, source.Name, source.Guid, target.Name, target.Guid, result.Name, result.Name, result.Guid); result.Destroy(); // cleanup for guid manager } diff --git a/Source/ACE.Server/Factories/Entity/ChanceTable.cs b/Source/ACE.Server/Factories/Entity/ChanceTable.cs index 182f206731..c0d35576e9 100644 --- a/Source/ACE.Server/Factories/Entity/ChanceTable.cs +++ b/Source/ACE.Server/Factories/Entity/ChanceTable.cs @@ -24,7 +24,7 @@ private void VerifyTable() total += (decimal)entry.chance; if (Math.Abs(1.0M - total) > threshold) - log.Error($"Chance table adds up to {total}, expected 1.0: {string.Join(", ", this)}"); + log.LogError("Chance table adds up to {Total}, expected 1.0: {Join}", total, string.Join(", ", this)); verified = true; } diff --git a/Source/ACE.Server/Factories/LootGenerationFactory.cs b/Source/ACE.Server/Factories/LootGenerationFactory.cs index 88742cbc49..6250ff4d38 100644 --- a/Source/ACE.Server/Factories/LootGenerationFactory.cs +++ b/Source/ACE.Server/Factories/LootGenerationFactory.cs @@ -122,7 +122,7 @@ private static TreasureRoll RollWcid(TreasureDeath treasureDeath, TreasureItemCa if (treasureItemType == TreasureItemType.Undef) { - log.Error($"LootGenerationFactory.RollWcid({treasureDeath.TreasureType}, {category}): treasureItemType == Undef"); + log.LogError("LootGenerationFactory.RollWcid({TreasureType}, {Category}): treasureItemType == Undef", treasureDeath.TreasureType, category); return null; } @@ -272,7 +272,7 @@ private static WorldObject CreateAndMutateWcid(TreasureDeath treasureDeath, Trea if (wo == null) { - log.Error($"CreateAndMutateWcid({treasureDeath.TreasureType}, {(int)treasureRoll.Wcid} - {treasureRoll.Wcid}, {treasureRoll.GetItemType()}, {isMagical}) - failed to create item"); + log.LogError("CreateAndMutateWcid({TreasureType}, {TreasureRollWcid} - {TreasureRollWcid2}, {ItemType}, {IsMagical}) - failed to create item", treasureDeath.TreasureType, (int)treasureRoll.Wcid, treasureRoll.Wcid, treasureRoll.GetItemType(), isMagical); return null; } @@ -337,7 +337,7 @@ private static WorldObject CreateAndMutateWcid(TreasureDeath treasureDeath, Trea break; default: - log.Error($"CreateAndMutateWcid({treasureDeath.TreasureType}, {(int)treasureRoll.Wcid} - {treasureRoll.Wcid}, {treasureRoll.GetItemType()}, {isMagical}) - unknown weapon type"); + log.LogError("CreateAndMutateWcid({TreasureType}, {TreasureRollWcid} - {TreasureRollWcid2}, {ItemType}, {IsMagical}) - unknown weapon type", treasureDeath.TreasureType, (int)treasureRoll.Wcid, treasureRoll.Wcid, treasureRoll.GetItemType(), isMagical); break; } break; @@ -425,7 +425,7 @@ private static MaterialType GetMaterialType(WorldObject wo, int tier) { if (wo.TsysMutationData == null) { - log.Warn($"[LOOT] Missing PropertyInt.TsysMutationData on loot item {wo.WeenieClassId} - {wo.Name}"); + log.LogWarning("[LOOT] Missing PropertyInt.TsysMutationData on loot item {WeenieClassId} - {Name}", wo.WeenieClassId, wo.Name); return GetDefaultMaterialType(wo); } @@ -611,7 +611,7 @@ private static void MutateColor(WorldObject wo) } else { - log.Warn($"[LOOT] Color looked failed for {wo.MaterialType} ({(int)wo.MaterialType}) - {wo.WeenieClassId} - {wo.Name}."); + log.LogWarning("[LOOT] Color looked failed for {WoMaterialType} ({WoMaterialType2}) - {WeenieClassId} - {Name}.", wo.MaterialType, (int)wo.MaterialType, wo.WeenieClassId, wo.Name); } } } diff --git a/Source/ACE.Server/Factories/LootGenerationFactory_Caster.cs b/Source/ACE.Server/Factories/LootGenerationFactory_Caster.cs index 68ccacc09e..9a617be05e 100644 --- a/Source/ACE.Server/Factories/LootGenerationFactory_Caster.cs +++ b/Source/ACE.Server/Factories/LootGenerationFactory_Caster.cs @@ -1,5 +1,6 @@ +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.Database.Models.World; using ACE.Entity.Enum; using ACE.Server.Entity.Mutations; @@ -110,13 +111,13 @@ private static void MutateCaster_SpellDID(WorldObject wo, TreasureDeath profile) if (spellLevels == null) { - log.Error($"MutateCaster_SpellDID: couldn't find {firstSpell}"); + log.LogError("MutateCaster_SpellDID: couldn't find {FirstSpell}", firstSpell); return; } if (spellLevels.Count != 8) { - log.Error($"MutateCaster_SpellDID: found {spellLevels.Count} spell levels for {firstSpell}, expected 8"); + log.LogError("MutateCaster_SpellDID: found {Count} spell levels for {FirstSpell}, expected 8", spellLevels.Count, firstSpell); return; } diff --git a/Source/ACE.Server/Factories/LootGenerationFactory_Clothing.cs b/Source/ACE.Server/Factories/LootGenerationFactory_Clothing.cs index 3ec2c2fca2..9353989e00 100644 --- a/Source/ACE.Server/Factories/LootGenerationFactory_Clothing.cs +++ b/Source/ACE.Server/Factories/LootGenerationFactory_Clothing.cs @@ -1,7 +1,8 @@ using System; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.Database.Models.World; using ACE.Entity.Enum; using ACE.Entity.Enum.Properties; @@ -122,7 +123,7 @@ private static bool AssignArmorLevel(WorldObject wo, TreasureDeath profile, Trea if (scriptName == null) { - log.Error($"AssignArmorLevel({wo.Name}, {profile.TreasureType}, {roll.ItemType}) - unknown item type"); + log.LogError("AssignArmorLevel({Name}, {TreasureType}, {ItemType}) - unknown item type", wo.Name, profile.TreasureType, roll.ItemType); return false; } @@ -285,7 +286,7 @@ private static bool TryMutateGearRating(WorldObject wo, TreasureDeath profile, T } else { - log.Error($"TryMutateGearRating({wo.Name}, {profile.TreasureType}, {roll.ItemType}): unknown item type"); + log.LogError("TryMutateGearRating({Name}, {TreasureType}, {ItemType}): unknown item type", wo.Name, profile.TreasureType, roll.ItemType); return false; } diff --git a/Source/ACE.Server/Factories/LootGenerationFactory_Gem.cs b/Source/ACE.Server/Factories/LootGenerationFactory_Gem.cs index 98fe2d94ef..29230aa899 100644 --- a/Source/ACE.Server/Factories/LootGenerationFactory_Gem.cs +++ b/Source/ACE.Server/Factories/LootGenerationFactory_Gem.cs @@ -1,6 +1,7 @@ using System; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Database.Models.World; using ACE.Entity.Enum; using ACE.Server.Entity; @@ -82,7 +83,7 @@ private static bool AssignMagic_Gem(WorldObject wo, TreasureDeath profile, Treas if (spellLevels == null || spellLevels.Count != 8) { - log.Error($"AssignMagic_Gem({wo.Name}, {profile.TreasureType}, {roll.ItemType}) - unknown spell {spell}"); + log.LogError("AssignMagic_Gem({Name}, {TreasureType}, {ItemType}) - unknown spell {Spell}", wo.Name, profile.TreasureType, roll.ItemType, spell); return false; } diff --git a/Source/ACE.Server/Factories/LootGenerationFactory_Magic.cs b/Source/ACE.Server/Factories/LootGenerationFactory_Magic.cs index 8b0bce0c83..61ca06bd36 100644 --- a/Source/ACE.Server/Factories/LootGenerationFactory_Magic.cs +++ b/Source/ACE.Server/Factories/LootGenerationFactory_Magic.cs @@ -1,7 +1,8 @@ using System; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.Database.Models.World; using ACE.Entity.Enum; using ACE.Server.Factories.Entity; @@ -91,7 +92,7 @@ private static int RollItemMaxMana(WorldObject wo, TreasureRoll roll, int maxSpe } else { - log.Error($"RollItemMaxMana({wo.Name}, {roll.ItemType}, {maxSpellMana}) - unknown item type"); + log.LogError("RollItemMaxMana({Name}, {ItemType}, {MaxSpellMana}) - unknown item type", wo.Name, roll.ItemType, maxSpellMana); return 1; } @@ -125,7 +126,7 @@ private static int RollSpellcraft(WorldObject wo, TreasureRoll roll) } else if (!roll.IsGem) { - log.Error($"RollSpellcraft({wo.Name}, {roll.ItemType}) - unknown item type"); + log.LogError("RollSpellcraft({Name}, {ItemType}) - unknown item type", wo.Name, roll.ItemType); } var rng = ThreadSafeRandom.Next(range.min, range.max); @@ -204,7 +205,7 @@ private static bool TryMutate_ItemSkillLimit(WorldObject wo, TreasureRoll roll) } else { - log.Error($"RollItemSkillLimit({wo.Name}, {roll.ItemType}) - unknown item type"); + log.LogError("RollItemSkillLimit({Name}, {ItemType}) - unknown item type", wo.Name, roll.ItemType); return false; } diff --git a/Source/ACE.Server/Factories/LootGenerationFactory_Rare.cs b/Source/ACE.Server/Factories/LootGenerationFactory_Rare.cs index f4f4e62e79..c1a4133465 100644 --- a/Source/ACE.Server/Factories/LootGenerationFactory_Rare.cs +++ b/Source/ACE.Server/Factories/LootGenerationFactory_Rare.cs @@ -2,8 +2,9 @@ using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.Server.WorldObjects; namespace ACE.Server.Factories @@ -93,7 +94,7 @@ public static WorldObject TryCreateRare(int luck = 0) var wo = WorldObjectFactory.CreateNewWorldObject((uint)rareWCID); if (wo == null) - log.Error($"LootGenerationFactory_Rare.CreateRare(): failed to generate rare wcid {rareWCID}"); + log.LogError("LootGenerationFactory_Rare.CreateRare(): failed to generate rare wcid {RareWCID}", rareWCID); return wo; } diff --git a/Source/ACE.Server/Factories/LootGenerationFactory_Scroll.cs b/Source/ACE.Server/Factories/LootGenerationFactory_Scroll.cs index bb6269bdc2..43f939c328 100644 --- a/Source/ACE.Server/Factories/LootGenerationFactory_Scroll.cs +++ b/Source/ACE.Server/Factories/LootGenerationFactory_Scroll.cs @@ -1,5 +1,6 @@ +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.Database.Models.World; using ACE.Database; using ACE.Entity.Enum; @@ -29,7 +30,7 @@ private static WorldObject CreateRandomScroll(TreasureDeath profile, TreasureRol if (weenie == null) { - log.DebugFormat("CreateRandomScroll for tier {0} and spellID of {1} returned null from the database.", profile.Tier, spellId); + log.LogDebug("CreateRandomScroll for tier {Tier} and spellID of {SpellId} returned null from the database.", profile.Tier, spellId); return null; } diff --git a/Source/ACE.Server/Factories/LootGenerationFactory_Spells.cs b/Source/ACE.Server/Factories/LootGenerationFactory_Spells.cs index c00967ab89..6478a33e24 100644 --- a/Source/ACE.Server/Factories/LootGenerationFactory_Spells.cs +++ b/Source/ACE.Server/Factories/LootGenerationFactory_Spells.cs @@ -2,8 +2,9 @@ using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.Database.Models.World; using ACE.Entity.Enum; using ACE.Entity.Models; @@ -83,7 +84,7 @@ private static List RollItemSpells(WorldObject wo, TreasureDeath profil } else { - log.Error($"RollItemSpells({wo.Name}) - item is not clothing / armor / weapon"); + log.LogError("RollItemSpells({Name}) - item is not clothing / armor / weapon", wo.Name); return null; } @@ -102,7 +103,7 @@ private static List RollSpellLevels(WorldObject wo, TreasureDeath profi if (spellLevels.Count != 8) { - log.Error($"RollSpellLevels({wo.Name}, {spell}) - spell level progression returned {spellLevels.Count}, expected 8"); + log.LogError("RollSpellLevels({Name}, {Spell}) - spell level progression returned {Count}, expected 8", wo.Name, spell, spellLevels.Count); continue; } @@ -163,7 +164,7 @@ private static int RollNumEnchantments(WorldObject wo, TreasureDeath profile, Tr } else { - log.Warn($"RollNumEnchantments({wo.Name}, {profile.TreasureType}, {roll.ItemType}) - unknown item type"); + log.LogWarning("RollNumEnchantments({Name}, {TreasureType}, {ItemType}) - unknown item type", wo.Name, profile.TreasureType, roll.ItemType); return 1; // gems? } } @@ -288,7 +289,7 @@ private static List RollCantrips(WorldObject wo, TreasureDeath profile, if (cantripLevels.Count != 4) { - log.Error($"RollCantrips({wo.Name}, {profile.TreasureType}, {roll.ItemType}) - {cantrip} has {cantripLevels.Count} cantrip levels, expected 4"); + log.LogError("RollCantrips({Name}, {TreasureType}, {ItemType}) - {Cantrip} has {Count} cantrip levels, expected 4", wo.Name, profile.TreasureType, roll.ItemType, cantrip, cantripLevels.Count); continue; } @@ -355,7 +356,7 @@ private static SpellId RollCantrip(WorldObject wo, TreasureDeath profile, Treasu } else { - log.Error($"RollCantrip({wo.Name}, {profile.TreasureType}, {roll.ItemType}) - unknown item type"); + log.LogError("RollCantrip({Name}, {TreasureType}, {ItemType}) - unknown item type", wo.Name, profile.TreasureType, roll.ItemType); return SpellId.Undef; } } @@ -370,7 +371,7 @@ private static float RollCantripDifficulty(List cantripIds) if (cantripLevels == null || cantripLevels.Count != 4) { - log.Error($"RollCantripDifficulty({cantripId}) - unknown cantrip"); + log.LogError("RollCantripDifficulty({CantripId}) - unknown cantrip", cantripId); continue; } @@ -478,7 +479,7 @@ private static int GetSpellSelectionCode_Dynamic(WorldObject wo, TreasureRoll ro return 19; } - log.Error($"GetSpellCode_Dynamic({wo.Name}) - couldn't determine spell selection code"); + log.LogError("GetSpellCode_Dynamic({Name}) - couldn't determine spell selection code", wo.Name); return 0; } @@ -533,7 +534,7 @@ private static int GetSpellCode_Dynamic_ClothingArmor(WorldObject wo, TreasureRo if (coverageMask == CoverageMask.Feet) return 18; - log.Error($"GetSpellCode_Dynamic_ClothingArmor({wo.Name}) - couldn't determine spell selection code for {coverageMask}, {isArmor}"); + log.LogError("GetSpellCode_Dynamic_ClothingArmor({Name}) - couldn't determine spell selection code for {CoverageMask}, {IsArmor}", wo.Name, coverageMask, isArmor); return 0; } } diff --git a/Source/ACE.Server/Factories/PlayerFactory.cs b/Source/ACE.Server/Factories/PlayerFactory.cs index 7628735d7b..b9262ca59a 100644 --- a/Source/ACE.Server/Factories/PlayerFactory.cs +++ b/Source/ACE.Server/Factories/PlayerFactory.cs @@ -211,7 +211,7 @@ public static CreateResult Create(CharacterCreateInfo characterCreateInfo, Weeni if (!DatManager.PortalDat.SkillTable.SkillBaseHash.ContainsKey((uint)i)) { - log.ErrorFormat("Character {0} tried to create with skill {1} that was not found in Portal dat.", characterCreateInfo.Name, i); + log.LogError("Character {Name} tried to create with skill {I} that was not found in Portal dat.", characterCreateInfo.Name, i); return CreateResult.InvalidSkillRequested; } @@ -462,7 +462,7 @@ public static CreateResult Create(CharacterCreateInfo characterCreateInfo, Weeni /// private static CreateResult InvalidCharacterCreateData(CharacterCreateInfo characterCreateInfo, uint accountId, string field, long value) { - log.Warn($"Character creation of {characterCreateInfo.Name} for account {accountId} rejected: {field} {value} is not valid for heritage {characterCreateInfo.Heritage}, gender {characterCreateInfo.Gender}"); + log.LogWarning("Character creation of {Name} for account {AccountId} rejected: {Field} {Value} is not valid for heritage {Heritage}, gender {Gender}", characterCreateInfo.Name, accountId, field, value, characterCreateInfo.Heritage, characterCreateInfo.Gender); return CreateResult.InvalidCharacterCreateData; } @@ -632,7 +632,7 @@ public static WorldObject CreateIOU(uint missingWeenieId) { if (!PropertyManager.GetBool("iou_trades").Item) { - log.Warn($"CreateIOU: Skipping creation of IOU for missing weenie {missingWeenieId} because IOU system is disabled."); + log.LogWarning("CreateIOU: Skipping creation of IOU for missing weenie {MissingWeenieId} because IOU system is disabled.", missingWeenieId); return null; } diff --git a/Source/ACE.Server/Factories/StarterGearFactory.cs b/Source/ACE.Server/Factories/StarterGearFactory.cs index 16831689d9..b4fd3dea27 100644 --- a/Source/ACE.Server/Factories/StarterGearFactory.cs +++ b/Source/ACE.Server/Factories/StarterGearFactory.cs @@ -43,7 +43,7 @@ private static StarterGearConfiguration LoadConfigFromResource() } catch (Exception ex) { - log.Error($"StarterGearFactory.LoadConfigFromResource() - {ex}: {ex.Message}; {ex.InnerException}: {ex.InnerException.Message}"); + log.LogError("StarterGearFactory.LoadConfigFromResource() - {Ex}: {ExMessage}; {InnerException}: {InnerExceptionMessage}", ex, ex.Message, ex.InnerException, ex.InnerException.Message); } return null; diff --git a/Source/ACE.Server/Factories/Tables/Cantrips/ArmorCantrips.cs b/Source/ACE.Server/Factories/Tables/Cantrips/ArmorCantrips.cs index 3295e924d8..bc8ca441e0 100644 --- a/Source/ACE.Server/Factories/Tables/Cantrips/ArmorCantrips.cs +++ b/Source/ACE.Server/Factories/Tables/Cantrips/ArmorCantrips.cs @@ -120,13 +120,13 @@ private static void BuildSpells() if (spellLevels == null) { - log.Error($"ArmorCantrips - couldn't find {spell}"); + log.LogError("ArmorCantrips - couldn't find {Spell}", spell); continue; } if (spellLevels.Count != NumLevels) { - log.Error($"ArmorCantrips - expected {NumLevels} levels for {spell}, found {spellLevels.Count}"); + log.LogError("ArmorCantrips - expected {NumLevels} levels for {Spell}, found {Count}", NumLevels, spell, spellLevels.Count); continue; } diff --git a/Source/ACE.Server/Factories/Tables/Cantrips/CantripChance.cs b/Source/ACE.Server/Factories/Tables/Cantrips/CantripChance.cs index 2872490e05..ff9c6df70e 100644 --- a/Source/ACE.Server/Factories/Tables/Cantrips/CantripChance.cs +++ b/Source/ACE.Server/Factories/Tables/Cantrips/CantripChance.cs @@ -172,8 +172,8 @@ public static void ApplyNumCantripsMod(bool showResults = true) if (showResults) { - log.Info($"ApplyNumCantripsMod({cantrip_drop_rate})"); - log.Info(""); + log.LogInformation("ApplyNumCantripsMod({Cantrip_drop_rate})", cantrip_drop_rate); + log.LogInformation(""); ShowTables(numCantrips); } @@ -230,8 +230,8 @@ public static void ApplyCantripLevelsMod(bool showResults = true) if (showResults) { - log.Info($"ApplyCantripLevelsMod({minor_cantrip_drop_rate}, {major_cantrip_drop_rate}, {epic_cantrip_drop_rate}, {legendary_cantrip_drop_rate})"); - log.Info(""); + log.LogInformation("ApplyCantripLevelsMod({Minor_cantrip_drop_rate}, {Major_cantrip_drop_rate}, {Epic_cantrip_drop_rate}, {Legendary_cantrip_drop_rate})", minor_cantrip_drop_rate, major_cantrip_drop_rate, epic_cantrip_drop_rate, legendary_cantrip_drop_rate); + log.LogInformation(""); ShowTables(cantripLevels); } @@ -296,13 +296,13 @@ private static void ShowTables(List> tables) { var table = tables[i]; - log.Info($"Tier {i + 1}:"); - log.Info(""); + log.LogInformation("Tier {Number}:", i + 1); + log.LogInformation(""); foreach (var entry in table) - log.Info($"{entry.result}: {GetPercent(entry.chance)}"); + log.LogInformation("{Result}: {Percent}", entry.result, GetPercent(entry.chance)); - log.Info(""); + log.LogInformation(""); } } diff --git a/Source/ACE.Server/Factories/Tables/Cantrips/JewelryCantrips.cs b/Source/ACE.Server/Factories/Tables/Cantrips/JewelryCantrips.cs index 2fe21add64..3125135f8a 100644 --- a/Source/ACE.Server/Factories/Tables/Cantrips/JewelryCantrips.cs +++ b/Source/ACE.Server/Factories/Tables/Cantrips/JewelryCantrips.cs @@ -98,13 +98,13 @@ private static void BuildSpells() if (spellLevels == null) { - log.Error($"JewelryCantrips - couldn't find {spell}"); + log.LogError("JewelryCantrips - couldn't find {Spell}", spell); continue; } if (spellLevels.Count != NumLevels) { - log.Error($"JewelryCantrips - expected {NumLevels} levels for {spell}, found {spellLevels.Count}"); + log.LogError("JewelryCantrips - expected {NumLevels} levels for {Spell}, found {Count}", NumLevels, spell, spellLevels.Count); continue; } diff --git a/Source/ACE.Server/Factories/Tables/Cantrips/MeleeCantrips.cs b/Source/ACE.Server/Factories/Tables/Cantrips/MeleeCantrips.cs index 02a6dfb70f..eec97ec530 100644 --- a/Source/ACE.Server/Factories/Tables/Cantrips/MeleeCantrips.cs +++ b/Source/ACE.Server/Factories/Tables/Cantrips/MeleeCantrips.cs @@ -54,13 +54,13 @@ private static void BuildSpells() if (spellLevels == null) { - log.Error($"MeleeCantrips - couldn't find {spell}"); + log.LogError("MeleeCantrips - couldn't find {Spell}", spell); continue; } if (spellLevels.Count != NumLevels) { - log.Error($"MeleeCantrips - expected {NumLevels} levels for {spell}, found {spellLevels.Count}"); + log.LogError("MeleeCantrips - expected {NumLevels} levels for {Spell}, found {Count}", NumLevels, spell, spellLevels.Count); continue; } diff --git a/Source/ACE.Server/Factories/Tables/Cantrips/MissileCantrips.cs b/Source/ACE.Server/Factories/Tables/Cantrips/MissileCantrips.cs index 69db6790f2..8396f2eb24 100644 --- a/Source/ACE.Server/Factories/Tables/Cantrips/MissileCantrips.cs +++ b/Source/ACE.Server/Factories/Tables/Cantrips/MissileCantrips.cs @@ -53,13 +53,13 @@ private static void BuildSpells() if (spellLevels == null) { - log.Error($"MissileCantrips - couldn't find {spell}"); + log.LogError("MissileCantrips - couldn't find {Spell}", spell); continue; } if (spellLevels.Count != NumLevels) { - log.Error($"MissileCantrips - expected {NumLevels} levels for {spell}, found {spellLevels.Count}"); + log.LogError("MissileCantrips - expected {NumLevels} levels for {Spell}, found {Count}", NumLevels, spell, spellLevels.Count); continue; } diff --git a/Source/ACE.Server/Factories/Tables/Cantrips/WandCantrips.cs b/Source/ACE.Server/Factories/Tables/Cantrips/WandCantrips.cs index c08f7cfab6..097953b7b3 100644 --- a/Source/ACE.Server/Factories/Tables/Cantrips/WandCantrips.cs +++ b/Source/ACE.Server/Factories/Tables/Cantrips/WandCantrips.cs @@ -57,13 +57,13 @@ private static void BuildSpells() if (spellLevels == null) { - log.Error($"WandCantrips - couldn't find {spell}"); + log.LogError("WandCantrips - couldn't find {Spell}", spell); continue; } if (spellLevels.Count != NumLevels) { - log.Error($"WandCantrips - expected {NumLevels} levels for {spell}, found {spellLevels.Count}"); + log.LogError("WandCantrips - expected {NumLevels} levels for {Spell}, found {Count}", NumLevels, spell, spellLevels.Count); continue; } diff --git a/Source/ACE.Server/Factories/Tables/GearRatingChance.cs b/Source/ACE.Server/Factories/Tables/GearRatingChance.cs index efad55c8c7..fa75ea3e7a 100644 --- a/Source/ACE.Server/Factories/Tables/GearRatingChance.cs +++ b/Source/ACE.Server/Factories/Tables/GearRatingChance.cs @@ -50,7 +50,7 @@ public static int Roll(WorldObject wo, TreasureDeath profile, TreasureRoll roll) } else { - log.Error($"GearRatingChance.Roll({wo.Name}, {profile.TreasureType}, {roll.ItemType}): unknown item type"); + log.LogError("GearRatingChance.Roll({Name}, {TreasureType}, {ItemType}): unknown item type", wo.Name, profile.TreasureType, roll.ItemType); return 0; } diff --git a/Source/ACE.Server/Factories/Tables/QualityChance.cs b/Source/ACE.Server/Factories/Tables/QualityChance.cs index 59490005d9..0f6b629ae6 100644 --- a/Source/ACE.Server/Factories/Tables/QualityChance.cs +++ b/Source/ACE.Server/Factories/Tables/QualityChance.cs @@ -215,7 +215,7 @@ public static int Roll(TreasureDeath treasureDeath) if (rng < curChance && curChance >= treasureDeath.LootQualityMod) return i + 1; } - log.Error($"QualityTables.Roll({treasureDeath.Tier}, {treasureDeath.LootQualityMod}) - this shouldn't happen"); + log.LogError("QualityTables.Roll({Tier}, {LootQualityMod}) - this shouldn't happen", treasureDeath.Tier, treasureDeath.LootQualityMod); return 0; } @@ -252,7 +252,7 @@ public static float RollInterval(TreasureDeath treasureDeath) return (float)(dy * (interval + i)); } } - log.Error($"QualityTables.RollInterval({treasureDeath.Tier}, {treasureDeath.LootQualityMod}) - this shouldn't happen"); + log.LogError("QualityTables.RollInterval({Tier}, {LootQualityMod}) - this shouldn't happen", treasureDeath.Tier, treasureDeath.LootQualityMod); return 0.0f; } } diff --git a/Source/ACE.Server/Factories/Tables/Spells/ArmorSpells.cs b/Source/ACE.Server/Factories/Tables/Spells/ArmorSpells.cs index 355c662a36..22e8a71e89 100644 --- a/Source/ACE.Server/Factories/Tables/Spells/ArmorSpells.cs +++ b/Source/ACE.Server/Factories/Tables/Spells/ArmorSpells.cs @@ -129,13 +129,13 @@ private static void BuildSpells() if (spellLevels == null) { - log.Error($"ArmorSpells - couldn't find {spell}"); + log.LogError("ArmorSpells - couldn't find {Spell}", spell); continue; } if (spellLevels.Count != NumTiers) { - log.Error($"ArmorSpells - expected {NumTiers} levels for {spell}, found {spellLevels.Count}"); + log.LogError("ArmorSpells - expected {NumTiers} levels for {Spell}, found {Count}", NumTiers, spell, spellLevels.Count); continue; } diff --git a/Source/ACE.Server/Factories/Tables/Spells/GemSpells.cs b/Source/ACE.Server/Factories/Tables/Spells/GemSpells.cs index 00618023e9..bb48e98497 100644 --- a/Source/ACE.Server/Factories/Tables/Spells/GemSpells.cs +++ b/Source/ACE.Server/Factories/Tables/Spells/GemSpells.cs @@ -114,13 +114,13 @@ private static void BuildSpells(List spells, SpellId[][] matrix) if (spellLevels == null) { - log.Error($"GemSpells - couldn't find {spell}"); + log.LogError("GemSpells - couldn't find {Spell}", spell); continue; } if (spellLevels.Count != NumTiers) { - log.Error($"GemSpells - expected {NumTiers} levels for {spell}, found {spellLevels.Count}"); + log.LogError("GemSpells - expected {NumTiers} levels for {Spell}, found {Count}", NumTiers, spell, spellLevels.Count); continue; } diff --git a/Source/ACE.Server/Factories/Tables/Spells/JewelrySpells.cs b/Source/ACE.Server/Factories/Tables/Spells/JewelrySpells.cs index fbc029ad4b..5d398c12f4 100644 --- a/Source/ACE.Server/Factories/Tables/Spells/JewelrySpells.cs +++ b/Source/ACE.Server/Factories/Tables/Spells/JewelrySpells.cs @@ -110,13 +110,13 @@ private static void BuildSpells() if (spellLevels == null) { - log.Error($"JewelrySpells - couldn't find {spell}"); + log.LogError("JewelrySpells - couldn't find {Spell}", spell); continue; } if (spellLevels.Count != NumTiers) { - log.Error($"JewelrySpells - expected {NumTiers} levels for {spell}, found {spellLevels.Count}"); + log.LogError("JewelrySpells - expected {NumTiers} levels for {Spell}, found {Count}", NumTiers, spell, spellLevels.Count); continue; } diff --git a/Source/ACE.Server/Factories/Tables/Spells/MeleeSpells.cs b/Source/ACE.Server/Factories/Tables/Spells/MeleeSpells.cs index aadb23b978..11edeb351d 100644 --- a/Source/ACE.Server/Factories/Tables/Spells/MeleeSpells.cs +++ b/Source/ACE.Server/Factories/Tables/Spells/MeleeSpells.cs @@ -56,13 +56,13 @@ private static void BuildSpells() if (spellLevels == null) { - log.Error($"MeleeSpells - couldn't find {spell}"); + log.LogError("MeleeSpells - couldn't find {Spell}", spell); continue; } if (spellLevels.Count != NumTiers) { - log.Error($"MeleeSpells - expected {NumTiers} levels for {spell}, found {spellLevels.Count}"); + log.LogError("MeleeSpells - expected {NumTiers} levels for {Spell}, found {Count}", NumTiers, spell, spellLevels.Count); continue; } diff --git a/Source/ACE.Server/Factories/Tables/Spells/MissileSpells.cs b/Source/ACE.Server/Factories/Tables/Spells/MissileSpells.cs index 2b2eb35d7b..b9410f1abb 100644 --- a/Source/ACE.Server/Factories/Tables/Spells/MissileSpells.cs +++ b/Source/ACE.Server/Factories/Tables/Spells/MissileSpells.cs @@ -55,13 +55,13 @@ private static void BuildSpells() if (spellLevels == null) { - log.Error($"MissileSpells - couldn't find {spell}"); + log.LogError("MissileSpells - couldn't find {Spell}", spell); continue; } if (spellLevels.Count != NumTiers) { - log.Error($"MissileSpells - expected {NumTiers} levels for {spell}, found {spellLevels.Count}"); + log.LogError("MissileSpells - expected {NumTiers} levels for {Spell}, found {Count}", NumTiers, spell, spellLevels.Count); continue; } diff --git a/Source/ACE.Server/Factories/Tables/Spells/ScrollSpells.cs b/Source/ACE.Server/Factories/Tables/Spells/ScrollSpells.cs index f6a9358d78..cd70acb492 100644 --- a/Source/ACE.Server/Factories/Tables/Spells/ScrollSpells.cs +++ b/Source/ACE.Server/Factories/Tables/Spells/ScrollSpells.cs @@ -377,7 +377,7 @@ private static void BuildSpells() if (startIdx != NumSpells) { - log.Error($"ScrollSpells - startIdx {startIdx}, expected {NumSpells}"); + log.LogError("ScrollSpells - startIdx {StartIdx}, expected {NumSpells}", startIdx, NumSpells); } } @@ -391,13 +391,13 @@ private static int AddSpells(List spells, int startIdx) if (spellLevels == null) { - log.Error($"ScrollSpells - couldn't find {spell}"); + log.LogError("ScrollSpells - couldn't find {Spell}", spell); continue; } if (spellLevels.Count != MaxLevels) { - log.Error($"ScrollSpells - expected {MaxLevels} levels for {spell}, found {spellLevels.Count}"); + log.LogError("ScrollSpells - expected {MaxLevels} levels for {Spell}, found {Count}", MaxLevels, spell, spellLevels.Count); continue; } diff --git a/Source/ACE.Server/Factories/Tables/Spells/WandSpells.cs b/Source/ACE.Server/Factories/Tables/Spells/WandSpells.cs index 314fe28e48..631b93b472 100644 --- a/Source/ACE.Server/Factories/Tables/Spells/WandSpells.cs +++ b/Source/ACE.Server/Factories/Tables/Spells/WandSpells.cs @@ -60,13 +60,13 @@ private static void BuildSpells() if (spellLevels == null) { - log.Error($"WandSpells - couldn't find {spell}"); + log.LogError("WandSpells - couldn't find {Spell}", spell); continue; } if (spellLevels.Count != NumTiers) { - log.Error($"WandSpells - expected {NumTiers} levels for {spell}, found {spellLevels.Count}"); + log.LogError("WandSpells - expected {NumTiers} levels for {Spell}, found {Count}", NumTiers, spell, spellLevels.Count); continue; } diff --git a/Source/ACE.Server/Factories/WorldObjectFactory.cs b/Source/ACE.Server/Factories/WorldObjectFactory.cs index dc6e6a4d98..509be69d2b 100644 --- a/Source/ACE.Server/Factories/WorldObjectFactory.cs +++ b/Source/ACE.Server/Factories/WorldObjectFactory.cs @@ -35,7 +35,7 @@ public static WorldObject CreateWorldObject(Weenie weenie, ObjectGuid guid) switch (objWeenieType) { case WeenieType.Undef: - log.Warn($"CreateWorldObject: {weenie.GetName()} (0x{guid}:{weenie.WeenieClassId}) - WeenieType is Undef, Object cannot be created."); + log.LogWarning("CreateWorldObject: {Name} (0x{Guid}:{WeenieClassId}) - WeenieType is Undef, Object cannot be created.", weenie.GetName(), guid, weenie.WeenieClassId); return null; case WeenieType.LifeStone: return new Lifestone(weenie, guid); @@ -284,7 +284,7 @@ public static List CreateNewWorldObjects(List so if (weenie == null) { - log.Warn($"CreateNewWorldObjects: Database does not contain weenie {instance.WeenieClassId} for instance 0x{instance.Guid:X8} at {new Position(instance.ObjCellId, instance.OriginX, instance.OriginY, instance.OriginZ, instance.AnglesX, instance.AnglesY, instance.AnglesZ, instance.AnglesW).ToLOCString()}"); + log.LogWarning("CreateNewWorldObjects: Database does not contain weenie {WeenieClassId} for instance 0x{Guid:X8} at {ToLOCString}", instance.WeenieClassId, instance.Guid, new Position(instance.ObjCellId, instance.OriginX, instance.OriginY, instance.OriginZ, instance.AnglesX, instance.AnglesY, instance.AnglesZ, instance.AnglesW).ToLOCString()); continue; } @@ -308,7 +308,7 @@ public static List CreateNewWorldObjects(List so if (worldObject.Location == null) { - log.Warn($"CreateNewWorldObjects: {worldObject.Name} (0x{worldObject.Guid}) Location was null. CreationTimestamp = {worldObject.CreationTimestamp} ({Common.Time.GetDateTimeFromTimestamp(worldObject.CreationTimestamp ?? 0).ToLocalTime().ToCommonString()}) | Location restored from world db instance."); + log.LogWarning("CreateNewWorldObjects: {Name} (0x{Guid}) Location was null. CreationTimestamp = {CreationTimestamp} ({DateTimeFromTimestamp}) | Location restored from world db instance.", worldObject.Name, worldObject.Guid, worldObject.CreationTimestamp, Common.Time.GetDateTimeFromTimestamp(worldObject.CreationTimestamp ?? 0).ToLocalTime().ToCommonString()); worldObject.Location = new Position(instance.ObjCellId, instance.OriginX, instance.OriginY, instance.OriginZ, instance.AnglesX, instance.AnglesY, instance.AnglesZ, instance.AnglesW); } } diff --git a/Source/ACE.Server/Managers/DDDManager.cs b/Source/ACE.Server/Managers/DDDManager.cs index 17b8d53b79..6cd988fb33 100644 --- a/Source/ACE.Server/Managers/DDDManager.cs +++ b/Source/ACE.Server/Managers/DDDManager.cs @@ -59,7 +59,7 @@ public static void Initialize() if (DatManager.HighResDat != null) InitIterations(DatDatabaseType.HighRes, DatManager.HighResDat); - log.DebugFormat("DDDManager Initialized."); + log.LogDebug("DDDManager Initialized."); } private static void InitIterations(DatDatabaseType datDatabaseType, DatDatabase datDatabase) @@ -95,7 +95,7 @@ private static void InitIterations(DatDatabaseType datDatabaseType, DatDatabase if (useCompressedFile && precacheCompressedDATFiles) CompressedDatFilesCache[datDatabaseType].TryAdd(fileName, PrependUncompressedFileSize(compressedDatFile, (uint)uncompressedFileSize)); }); - log.Info($"Iterations for {datDatabaseType} initialized. Iterations.Count={Iterations[datDatabaseType].Count} | FileCount={fileCount} | DatFileSizes.Count={DatFileSizes[datDatabaseType].Count}{(precacheCompressedDATFiles ? " | precached Compressed files" : "")}"); + log.LogInformation("Iterations for {DatDatabaseType} initialized. Iterations.Count={IterationsCount} | FileCount={FileCount} | DatFileSizes.Count={DatFileSizesCount}{PrecacheNote}", datDatabaseType, Iterations[datDatabaseType].Count, fileCount, DatFileSizes[datDatabaseType].Count, (precacheCompressedDATFiles ? " | precached Compressed files" : "")); } /// diff --git a/Source/ACE.Server/Managers/EventManager.cs b/Source/ACE.Server/Managers/EventManager.cs index 48a3eb2dc1..efe4064700 100644 --- a/Source/ACE.Server/Managers/EventManager.cs +++ b/Source/ACE.Server/Managers/EventManager.cs @@ -36,7 +36,7 @@ public static void Initialize() StartEvent(evnt.Name, null, null); } - log.DebugFormat("EventManager Initalized."); + log.LogDebug("EventManager Initalized."); } public static bool StartEvent(string e, WorldObject source, WorldObject target) @@ -62,8 +62,8 @@ public static bool StartEvent(string e, WorldObject source, WorldObject target) Console.WriteLine($"Starting event {evnt.Name}"); } - if (log.IsDebugEnabled) - log.Debug($"[EVENT] {(source == null ? "SYSTEM" : $"{source.Name} (0x{source.Guid}|{source.WeenieClassId})")}{(target == null ? "" : $", triggered by {target.Name} (0x{target.Guid}|{target.WeenieClassId}),")} started an event: {evnt.Name}{((int)state == evnt.State ? (source == null ? ", which is the default state for this event." : ", which had already been started.") : "")}"); + if (log.IsEnabled(LogLevel.Debug)) + log.LogDebug("[EVENT] {Source}{TriggeredBy} started an event: {Name}{StateNote}", (source == null ? "SYSTEM" : $"{source.Name} (0x{source.Guid}|{source.WeenieClassId})"), (target == null ? "" : $", triggered by {target.Name} (0x{target.Guid}|{target.WeenieClassId}),"), evnt.Name, ((int)state == evnt.State ? (source == null ? ", which is the default state for this event." : ", which had already been started.") : "")); return true; } @@ -91,8 +91,8 @@ public static bool StopEvent(string e, WorldObject source, WorldObject target) Console.WriteLine($"Stopping event {evnt.Name}"); } - if (log.IsDebugEnabled) - log.Debug($"[EVENT] {(source == null ? "SYSTEM" : $"{source.Name} (0x{source.Guid}|{source.WeenieClassId})")}{(target == null ? "" : $", triggered by {target.Name} (0x{target.Guid}|{target.WeenieClassId}),")} stopped an event: {evnt.Name}{((int)state == evnt.State ? (source == null ? ", which is the default state for this event." : ", which had already been stopped.") : "")}"); + if (log.IsEnabled(LogLevel.Debug)) + log.LogDebug("[EVENT] {Source}{TriggeredBy} stopped an event: {Name}{StateNote}", (source == null ? "SYSTEM" : $"{source.Name} (0x{source.Guid}|{source.WeenieClassId})"), (target == null ? "" : $", triggered by {target.Name} (0x{target.Guid}|{target.WeenieClassId}),"), evnt.Name, ((int)state == evnt.State ? (source == null ? ", which is the default state for this event." : ", which had already been stopped.") : "")); return true; } diff --git a/Source/ACE.Server/Managers/GuidManager.cs b/Source/ACE.Server/Managers/GuidManager.cs index 70f3aa716b..3e3a03a689 100644 --- a/Source/ACE.Server/Managers/GuidManager.cs +++ b/Source/ACE.Server/Managers/GuidManager.cs @@ -65,10 +65,10 @@ public PlayerGuidAllocator(uint min, uint max, string name) // Need to start allocating at current value in db +1 current++; - log.DebugFormat("{0} GUID Allocator current is now {1:X8} of {2:X8}", name, current, max); + log.LogDebug("{Name} GUID Allocator current is now {Current:X8} of {Max:X8}", name, current, max); if ((max - current) < LowIdLimit) - log.WarnFormat("Dangerously low on {0} GUIDs: {1:X8} of {2:X8}", name, current, max); + log.LogWarning("Dangerously low on {Name} GUIDs: {Current:X8} of {Max:X8}", name, current, max); } this.name = name; @@ -80,12 +80,12 @@ public uint Alloc() { if (current == max) { - log.FatalFormat("Out of {0} GUIDs!", name); + log.LogCritical("Out of {Name} GUIDs!", name); return InvalidGuid; } if (current == max - LowIdLimit) - log.WarnFormat("Running dangerously low on {0} GUIDs, need to defrag", name); + log.LogWarning("Running dangerously low on {Name} GUIDs, need to defrag", name); uint ret = current; current += 1; @@ -169,10 +169,10 @@ public DynamicGuidAllocator(uint min, uint max, string name, bool unlimitedGaps) // Need to start allocating at current value in db +1 current++; - log.DebugFormat("{0} GUID Allocator current is now {1:X8} of {2:X8}", name, current, max); + log.LogDebug("{Name} GUID Allocator current is now {Current:X8} of {Max:X8}", name, current, max); if ((max - current) < LowIdLimit) - log.WarnFormat("Dangerously low on {0} GUIDs: {1:X8} of {2:X8}", name, current, max); + log.LogWarning("Dangerously low on {Name} GUIDs: {Current:X8} of {Max:X8}", name, current, max); } // Get available ids in the form of sequence gaps @@ -187,7 +187,7 @@ public DynamicGuidAllocator(uint min, uint max, string name, bool unlimitedGaps) uint total = 0; foreach (var pair in availableIDs) total += (pair.end - pair.start) + 1; - log.DebugFormat("{0} GUID Sequence gaps initialized with total availableIDs of {1:N0}", name, total); + log.LogDebug("{Name} GUID Sequence gaps initialized with total availableIDs of {Total:N0}", name, total); done = true; Monitor.Pulse(this); } @@ -232,7 +232,7 @@ public uint Alloc() { if (!useSequenceGapExhaustedMessageDisplayed) { - log.DebugFormat("{0} GUID Sequence gaps exhausted. Any new, non-recycled GUID will be current + 1. current is now {1:X8}", name, current); + log.LogDebug("{Name} GUID Sequence gaps exhausted. Any new, non-recycled GUID will be current + 1. current is now {Current:X8}", name, current); useSequenceGapExhaustedMessageDisplayed = true; } } @@ -240,12 +240,12 @@ public uint Alloc() // Lastly, use an id that increments our max if (current == max) { - log.FatalFormat("Out of {0} GUIDs!", name); + log.LogCritical("Out of {Name} GUIDs!", name); return InvalidGuid; } if (current == max - LowIdLimit) - log.WarnFormat("Running dangerously low on {0} GUIDs, need to defrag", name); + log.LogWarning("Running dangerously low on {Name} GUIDs, need to defrag", name); uint ret = current; current += 1; diff --git a/Source/ACE.Server/Managers/HouseManager.cs b/Source/ACE.Server/Managers/HouseManager.cs index 6d5d5f8535..9ceb0f63e0 100644 --- a/Source/ACE.Server/Managers/HouseManager.cs +++ b/Source/ACE.Server/Managers/HouseManager.cs @@ -86,7 +86,7 @@ join inst in ctx.LandblockInstance on weenie.ClassId equals inst.WeenieClassId if (!uint.TryParse(Regex.Match(classname, @"\d+").Value, out var houseId)) { - log.Error($"[HOUSE] HouseManager.BuildHouseIdToGuid(): couldn't parse {classname}"); + log.LogError("[HOUSE] HouseManager.BuildHouseIdToGuid(): couldn't parse {Classname}", classname); continue; } @@ -138,29 +138,29 @@ private static void AddRentQueue(Biota slumlord) var owner = PlayerManager.FindByGuid(biotaOwner.Value); if (owner == null) { - log.Error($"[HOUSE] HouseManager.AddRentQueue(): couldn't find owner {biotaOwner.Value:X8}"); + log.LogError("[HOUSE] HouseManager.AddRentQueue(): couldn't find owner {BiotaOwner:X8}", biotaOwner.Value); return; } var houseId = slumlord.BiotaPropertiesDID.FirstOrDefault(i => i.Type == (ushort)PropertyDataId.HouseId); if (houseId == null) { - log.Error($"[HOUSE] HouseManager.AddRentQueue(): couldn't find house id for {slumlord.Id:X8}"); + log.LogError("[HOUSE] HouseManager.AddRentQueue(): couldn't find house id for {Id:X8}", slumlord.Id); return; } if (!HouseIdToGuid.TryGetValue(houseId.Value, out var houseGuids)) { - log.Error($"[HOUSE] HouseManager.AddRentQueue(): couldn't find house instance for {slumlord.Id:X8}"); + log.LogError("[HOUSE] HouseManager.AddRentQueue(): couldn't find house instance for {Id:X8}", slumlord.Id); return; } var houseInstance = GetHouseGuid(slumlord.Id, houseGuids); if (houseInstance == 0) { - log.Error($"[HOUSE] HouseManager.AddRentQueue(): couldn't find house guid for {slumlord.Id:X8}"); + log.LogError("[HOUSE] HouseManager.AddRentQueue(): couldn't find house guid for {Id:X8}", slumlord.Id); return; } if (RentQueueContainsHouse(houseInstance)) { - log.Error($"[HOUSE] HouseManager.AddRentQueue(): rent queue already contains house {houseInstance}"); + log.LogError("[HOUSE] HouseManager.AddRentQueue(): rent queue already contains house {HouseInstance}", houseInstance); return; } AddRentQueue(owner, houseInstance); @@ -189,7 +189,7 @@ public static void AddRentQueue(IPlayer player, uint houseGuid) if (player.HouseRentTimestamp == null) { - log.WarnFormat("[HOUSE] HouseManager.AddRentQueue({0}, {1:X8}): player has null HouseRentTimestamp", player.Name, houseGuid); + log.LogWarning("[HOUSE] HouseManager.AddRentQueue({Name}, {HouseGuid:X8}): player has null HouseRentTimestamp", player.Name, houseGuid); player.HouseRentTimestamp = (int)house.GetRentDue(purchaseTime); //return; } @@ -315,7 +315,7 @@ public static string GetCoords(Position position) if (ApartmentBlocks.TryGetValue(position.Landblock, out var apartmentBlock)) coords = $"{apartmentBlock} - "; else - log.Error($"[HOUSE] HouseManager.GetCoords({position}) - couldn't find apartment block"); + log.LogError("[HOUSE] HouseManager.GetCoords({Position}) - couldn't find apartment block", position); coords += position; } @@ -372,7 +372,7 @@ private static void ProcessRent(PlayerHouse playerHouse) var isInActiveOrDisabled = playerHouse.House.HouseStatus <= HouseStatus.InActive; var isPaid = IsRentPaid(playerHouse); var hasRequirements = HasRequirements(playerHouse); - log.InfoFormat("[HOUSE] {0}.ProcessRent(): isPaid = {1} | HasRequirements = {2} | MaintenanceFree = {3}", playerHouse.PlayerName, isPaid, hasRequirements, (house.HouseStatus == HouseStatus.InActive)); + log.LogInformation("[HOUSE] {PlayerName}.ProcessRent(): isPaid = {IsPaid} | HasRequirements = {HasRequirements} | MaintenanceFree = {IsInactive}", playerHouse.PlayerName, isPaid, hasRequirements, (house.HouseStatus == HouseStatus.InActive)); if (isInActiveOrDisabled || (isPaid && hasRequirements)) HandleRentPaid(playerHouse); @@ -390,7 +390,7 @@ private static void HandleRentPaid(PlayerHouse playerHouse) var player = PlayerManager.FindByGuid(playerHouse.PlayerGuid); if (player == null) { - log.WarnFormat("[HOUSE] HouseManager.HandleRentPaid({0}): couldn't find player", playerHouse.PlayerName); + log.LogWarning("[HOUSE] HouseManager.HandleRentPaid({PlayerName}): couldn't find player", playerHouse.PlayerName); return; } @@ -401,7 +401,7 @@ private static void HandleRentPaid(PlayerHouse playerHouse) if (nextRentTime <= rentTime) { - log.WarnFormat("[HOUSE] HouseManager.HandleRentPaid({0}): nextRentTime {1} <= rentTime {2}", playerHouse.PlayerName, nextRentTime, rentTime); + log.LogWarning("[HOUSE] HouseManager.HandleRentPaid({PlayerName}): nextRentTime {NextRentTime} <= rentTime {RentTime}", playerHouse.PlayerName, nextRentTime, rentTime); return; } @@ -420,7 +420,7 @@ private static void HandleRentPaid(PlayerHouse playerHouse) clearedInventoryStatus = "and cleared "; } - log.InfoFormat($"[HOUSE] HouseManager.HandleRentPaid({0}): rent payment successfully collected {clearedInventoryStatus}from SlumLord!", playerHouse.PlayerName); + log.LogInformation("[HOUSE] HouseManager.HandleRentPaid({PlayerName}): rent payment successfully collected {ClearedInventoryStatus}from SlumLord!", playerHouse.PlayerName, clearedInventoryStatus); // re-add item to queue AddRentQueue(player, playerHouse.House); @@ -461,7 +461,7 @@ public static void HandleEviction(House house, uint playerGuid, bool multihouse var nextRentTime = house.GetRentDue(purchaseTime); player.HouseRentTimestamp = (int)nextRentTime; - log.InfoFormat("[HOUSE] HouseManager.HandleEviction({0}): house rent disabled via config", player.Name); + log.LogInformation("[HOUSE] HouseManager.HandleEviction({Name}): house rent disabled via config", player.Name); // re-add item to queue AddRentQueue(player, house); @@ -507,11 +507,11 @@ public static void HandleEviction(House house, uint playerGuid, bool multihouse player.HouseRentTimestamp = null; } else - log.WarnFormat("[HOUSE] HouseManager.HandleRentEviction({0}, {1}, {2}): house guids don't match {3}", house.Guid, player.Name, multihouse, player.HouseInstance); + log.LogWarning("[HOUSE] HouseManager.HandleRentEviction({Guid}, {Name}, {Multihouse}): house guids don't match {HouseInstance}", house.Guid, player.Name, multihouse, player.HouseInstance); house.ClearRestrictions(); - log.InfoFormat("[HOUSE] HouseManager.HandleRentEviction({0})", player.Name); + log.LogInformation("[HOUSE] HouseManager.HandleRentEviction({Name})", player.Name); if (multihouse) { @@ -529,7 +529,7 @@ public static void HandleEviction(House house, uint playerGuid, bool multihouse var offlinePlayer = PlayerManager.GetOfflinePlayer(playerGuid); if (offlinePlayer == null) { - log.WarnFormat("[HOUSE] {0}.HandleEviction(): couldn't find offline player", player.Name); + log.LogWarning("[HOUSE] {Name}.HandleEviction(): couldn't find offline player", player.Name); return; } offlinePlayer.SetProperty(PropertyBool.HouseEvicted, true); @@ -565,7 +565,7 @@ private static bool IsRentPaid(PlayerHouse playerHouse) { if (rentItem.Paid < rentItem.Num) { - log.Info($"[HOUSE] {playerHouse.PlayerName}.IsRentPaid() - required {rentItem.Num:N0}x {(rentItem.Num > 1 ? $"{rentItem.PluralName}" : $"{rentItem.Name}")} ({rentItem.WeenieID}), found {rentItem.Paid:N0}"); + log.LogInformation("[HOUSE] {PlayerName}.IsRentPaid() - required {Num:N0}x {RentItemName} ({WeenieID}), found {Paid:N0}", playerHouse.PlayerName, rentItem.Num, (rentItem.Num > 1 ? $"{rentItem.PluralName}" : $"{rentItem.Name}"), rentItem.WeenieID, rentItem.Paid); return false; } } @@ -592,7 +592,7 @@ private static bool HasRequirements(PlayerHouse playerHouse) if (player == null) { - log.WarnFormat("[HOUSE] {0}.HasRequirements() - couldn't find player", playerHouse.PlayerName); + log.LogWarning("[HOUSE] {PlayerName}.HasRequirements() - couldn't find player", playerHouse.PlayerName); return false; } @@ -607,7 +607,7 @@ private static bool HasRequirements(PlayerHouse playerHouse) if (allegianceMinLevel > 0 && (allegiance == null || rank < allegianceMinLevel)) { - log.InfoFormat("[HOUSE] {0}.HasRequirements() - allegiance rank {1} < {2}", playerHouse.PlayerName, rank, allegianceMinLevel); + log.LogInformation("[HOUSE] {PlayerName}.HasRequirements() - allegiance rank {Rank} < {AllegianceMinLevel}", playerHouse.PlayerName, rank, allegianceMinLevel); return false; } return true; @@ -750,7 +750,7 @@ public static void GetHouse(uint houseGuid, Action callback) RegisterCallback(houseBiota, callback); } else - log.ErrorFormat("[HOUSE] HouseManager.GetHouse({0:X8}): couldn't find house on loaded landblock", houseGuid); + log.LogError("[HOUSE] HouseManager.GetHouse({HouseGuid:X8}): couldn't find house on loaded landblock", houseGuid); } /// @@ -868,7 +868,7 @@ private static void PayRent(PlayerHouse playerHouse) if (payment == null) { - log.Error($"[HOUSE] HouseManager.PayRent({house.Guid}): couldn't create payment for WCID {rentItem.WeenieID}"); + log.LogError("[HOUSE] HouseManager.PayRent({Guid}): couldn't create payment for WCID {WeenieID}", house.Guid, rentItem.WeenieID); return; } @@ -876,7 +876,7 @@ private static void PayRent(PlayerHouse playerHouse) if (!house.SlumLord.TryAddToInventory(payment)) { - log.Error($"[HOUSE] HouseManager.PayRent({house.Guid}): couldn't place {payment.Name} (0x{payment.Guid}) in SlumLord's Inventory"); + log.LogError("[HOUSE] HouseManager.PayRent({HouseGuid}): couldn't place {Name} (0x{PaymentGuid}) in SlumLord's Inventory", house.Guid, payment.Name, payment.Guid); return; } @@ -901,7 +901,7 @@ private static void PayRent(PlayerHouse playerHouse) actionChain.EnqueueChain(); } - log.InfoFormat("[HOUSE] HouseManager.PayRent({0}): fully paid rent into SlumLord.", house.Guid); + log.LogInformation("[HOUSE] HouseManager.PayRent({Guid}): fully paid rent into SlumLord.", house.Guid); } }); } diff --git a/Source/ACE.Server/Managers/LandblockManager.cs b/Source/ACE.Server/Managers/LandblockManager.cs index 9161275dea..b7929ecce0 100644 --- a/Source/ACE.Server/Managers/LandblockManager.cs +++ b/Source/ACE.Server/Managers/LandblockManager.cs @@ -86,28 +86,28 @@ public static void PreloadConfigLandblocks() { if (!ConfigManager.Config.Server.LandblockPreloading) { - log.Info("Preloading Landblocks Disabled..."); - log.Warn("Events may not function correctly as Preloading of Landblocks has disabled."); + log.LogInformation("Preloading Landblocks Disabled..."); + log.LogWarning("Events may not function correctly as Preloading of Landblocks has disabled."); return; } - log.Info("Preloading Landblocks..."); + log.LogInformation("Preloading Landblocks..."); if (ConfigManager.Config.Server.PreloadedLandblocks == null) { - log.Info("No configuration found for PreloadedLandblocks, please refer to Config.js.example"); - log.Warn("Initializing PreloadedLandblocks with single default for Hebian-To (Global Events)"); - log.Warn("Add a PreloadedLandblocks section to your Config.js file and adjust to meet your needs"); + log.LogInformation("No configuration found for PreloadedLandblocks, please refer to Config.js.example"); + log.LogWarning("Initializing PreloadedLandblocks with single default for Hebian-To (Global Events)"); + log.LogWarning("Add a PreloadedLandblocks section to your Config.js file and adjust to meet your needs"); ConfigManager.Config.Server.PreloadedLandblocks = new List { new PreloadedLandblocks { Id = "E74EFFFF", Description = "Hebian-To (Global Events)", Permaload = true, IncludeAdjacents = true, Enabled = true } }; } - log.InfoFormat("Found {0} landblock entries in PreloadedLandblocks configuration, {1} are set to preload.", ConfigManager.Config.Server.PreloadedLandblocks.Count, ConfigManager.Config.Server.PreloadedLandblocks.Count(x => x.Enabled == true)); + log.LogInformation("Found {Count} landblock entries in PreloadedLandblocks configuration, {EnabledCount} are set to preload.", ConfigManager.Config.Server.PreloadedLandblocks.Count, ConfigManager.Config.Server.PreloadedLandblocks.Count(x => x.Enabled == true)); foreach (var preloadLandblock in ConfigManager.Config.Server.PreloadedLandblocks) { if (!preloadLandblock.Enabled) { - log.DebugFormat("Landblock {0:X4} specified but not enabled in config, skipping", preloadLandblock.Id); + log.LogDebug("Landblock {Id:X4} specified but not enabled in config, skipping", preloadLandblock.Id); continue; } @@ -118,7 +118,7 @@ public static void PreloadConfigLandblocks() switch (preloadLandblock.Description) { case "Apartment Landblocks": - log.InfoFormat("Preloading landblock group: {0}, IncludeAdjacents = {1}, Permaload = {2}", preloadLandblock.Description, preloadLandblock.IncludeAdjacents, preloadLandblock.Permaload); + log.LogInformation("Preloading landblock group: {Description}, IncludeAdjacents = {IncludeAdjacents}, Permaload = {Permaload}", preloadLandblock.Description, preloadLandblock.IncludeAdjacents, preloadLandblock.Permaload); foreach (var apt in apartmentLandblocks) PreloadLandblock(apt, preloadLandblock); break; @@ -134,7 +134,7 @@ private static void PreloadLandblock(uint landblock, PreloadedLandblocks preload { var landblockID = new LandblockId(landblock); GetLandblock(landblockID, preloadLandblock.IncludeAdjacents, preloadLandblock.Permaload); - log.DebugFormat("Landblock {0:X4}, ({1}) preloaded. IncludeAdjacents = {2}, Permaload = {3}", landblockID.Landblock, preloadLandblock.Description, preloadLandblock.IncludeAdjacents, preloadLandblock.Permaload); + log.LogDebug("Landblock {Landblock:X4}, ({Description}) preloaded. IncludeAdjacents = {IncludeAdjacents}, Permaload = {Permaload}", landblockID.Landblock, preloadLandblock.Description, preloadLandblock.IncludeAdjacents, preloadLandblock.Permaload); } private static readonly uint[] apartmentLandblocks = @@ -255,7 +255,7 @@ private static void ProcessPendingLandblockGroupAdditions() foreach (var group in landblockGroups) count += group.Count; if (count != loadedLandblocks.Count) - log.Error($"[LANDBLOCK GROUP] ProcessPendingAdditions count ({count}) != loadedLandblocks.Count ({loadedLandblocks.Count})"); + log.LogError("[LANDBLOCK GROUP] ProcessPendingAdditions count ({Count}) != loadedLandblocks.Count ({LoadedLandblocksCount})", count, loadedLandblocks.Count); } finally { @@ -496,7 +496,7 @@ public static Landblock GetLandblock(LandblockId landblockId, bool loadAdjacents if (!loadedLandblocks.Add(landblock)) { - log.Error($"LandblockManager: failed to add {landblock.Id.Raw:X8} to active landblocks!"); + log.LogError("LandblockManager: failed to add {Id:X8} to active landblocks!", landblock.Id.Raw); return landblock; } @@ -720,22 +720,22 @@ private static void UnloadLandblocks() swTrySplitEach.Stop(); if (swTrySplitEach.Elapsed.TotalMilliseconds > 3) - log.WarnFormat("[LANDBLOCK GROUP] TrySplit for {0} took: {1:N2} ms", landblockGroups[i], swTrySplitEach.Elapsed.TotalMilliseconds); + log.LogWarning("[LANDBLOCK GROUP] TrySplit for {LandblockGroups} took: {TotalMilliseconds:N2} ms", landblockGroups[i], swTrySplitEach.Elapsed.TotalMilliseconds); else if (swTrySplitEach.Elapsed.TotalMilliseconds > 1) - log.DebugFormat("[LANDBLOCK GROUP] TrySplit for {0} took: {1:N2} ms", landblockGroups[i], swTrySplitEach.Elapsed.TotalMilliseconds); + log.LogDebug("[LANDBLOCK GROUP] TrySplit for {LandblockGroups} took: {TotalMilliseconds:N2} ms", landblockGroups[i], swTrySplitEach.Elapsed.TotalMilliseconds); if (splits != null) { if (splits.Count > 0) { - log.DebugFormat("[LANDBLOCK GROUP] TrySplit resulted in {0} split(s) and took: {1:N2} ms", splits.Count, swTrySplitEach.Elapsed.TotalMilliseconds); - log.DebugFormat("[LANDBLOCK GROUP] split for old: {0}", landblockGroups[i]); + log.LogDebug("[LANDBLOCK GROUP] TrySplit resulted in {Count} split(s) and took: {TotalMilliseconds:N2} ms", splits.Count, swTrySplitEach.Elapsed.TotalMilliseconds); + log.LogDebug("[LANDBLOCK GROUP] split for old: {LandblockGroups}", landblockGroups[i]); } foreach (var split in splits) { landblockGroups.Add(split); - log.DebugFormat("[LANDBLOCK GROUP] split and new: {0}", split); + log.LogDebug("[LANDBLOCK GROUP] split and new: {Split}", split); } } } @@ -755,7 +755,7 @@ private static void UnloadLandblocks() } if (unloadFailed) - log.Error($"LandblockManager: failed to unload {landblock.Id.Raw:X8}"); + log.LogError("LandblockManager: failed to unload {Id:X8}", landblock.Id.Raw); } } } diff --git a/Source/ACE.Server/Managers/PlayerManager.cs b/Source/ACE.Server/Managers/PlayerManager.cs index 2f043f3042..7f1283281b 100644 --- a/Source/ACE.Server/Managers/PlayerManager.cs +++ b/Source/ACE.Server/Managers/PlayerManager.cs @@ -75,7 +75,7 @@ public static void Initialize() playerAccountsDict[offlinePlayer.Guid.Full] = offlinePlayer; } else - log.Error($"PlayerManager.Initialize: couldn't find account for player {offlinePlayer.Name} ({offlinePlayer.Guid})"); + log.LogError("PlayerManager.Initialize: couldn't find account for player {Name} ({Guid})", offlinePlayer.Name, offlinePlayer.Guid); } }); } @@ -758,9 +758,9 @@ public static void LogBroadcastChat(Channel channel, WorldObject sender, string } if (channel != Channel.AllBroadcast) - log.Info($"[CHAT][{channel.ToString().ToUpper()}] {(sender != null ? sender.Name : "[SYSTEM]")} says on the {channel} channel, \"{message}\""); + log.LogInformation("[CHAT][{ToUpper}] {Sender} says on the {Channel} channel, \"{Message}\"", channel.ToString().ToUpper(), (sender != null ? sender.Name : "[SYSTEM]"), channel, message); else - log.Info($"[CHAT][GLOBAL] {(sender != null ? sender.Name : "[SYSTEM]")} issued a world broadcast, \"{message}\""); + log.LogInformation("[CHAT][GLOBAL] {Sender} issued a world broadcast, \"{Message}\"", (sender != null ? sender.Name : "[SYSTEM]"), message); } public static void BroadcastToChannelFromConsole(Channel channel, string message) diff --git a/Source/ACE.Server/Managers/PropertyManager.cs b/Source/ACE.Server/Managers/PropertyManager.cs index 11b71040a9..9e984f5986 100644 --- a/Source/ACE.Server/Managers/PropertyManager.cs +++ b/Source/ACE.Server/Managers/PropertyManager.cs @@ -138,7 +138,7 @@ public static void ModifyBoolDescription(string key, string description) if (CachedBooleanSettings.ContainsKey(key)) CachedBooleanSettings[key].ModifyDescription(description); else - log.Warn($"Attempted to modify {key} which did not exist in the BOOL cache."); + log.LogWarning("Attempted to modify {Key} which did not exist in the BOOL cache.", key); } /// @@ -188,7 +188,7 @@ public static void ModifyLongDescription(string key, string description) if (CachedLongSettings.ContainsKey(key)) CachedLongSettings[key].ModifyDescription(description); else - log.Warn($"Attempted to modify {key} which did not exist in the LONG cache."); + log.LogWarning("Attempted to modify {Key} which did not exist in the LONG cache.", key); } /// @@ -252,7 +252,7 @@ public static void ModifyDoubleDescription(string key, string description) if (CachedDoubleSettings.ContainsKey(key)) CachedDoubleSettings[key].ModifyDescription(description); else - log.Warn($"Attempted to modify the description of {key} which did not exist in the DOUBLE cache."); + log.LogWarning("Attempted to modify the description of {Key} which did not exist in the DOUBLE cache.", key); } /// @@ -302,7 +302,7 @@ public static void ModifyStringDescription(string key, string description) if (CachedStringSettings.ContainsKey(key)) CachedStringSettings[key].ModifyDescription(description); else - log.Warn($"Attempted to modify {key} which did not exist in the STRING cache."); + log.LogWarning("Attempted to modify {Key} which did not exist in the STRING cache.", key); } @@ -382,7 +382,7 @@ private static void DoWork(Object source, ElapsedEventArgs e) // next, we need to fetch all of the variables from the DB and compare them quickly. LoadPropertiesFromDB(); - log.DebugFormat("PropertyManager DoWork took {0:N0} ms", (DateTime.UtcNow - startTime).TotalMilliseconds); + log.LogDebug("PropertyManager DoWork took {TotalMilliseconds:N0} ms", (DateTime.UtcNow - startTime).TotalMilliseconds); } public static string ListProperties() { diff --git a/Source/ACE.Server/Managers/QuestManager.cs b/Source/ACE.Server/Managers/QuestManager.cs index c862462c0e..7df3bd808a 100644 --- a/Source/ACE.Server/Managers/QuestManager.cs +++ b/Source/ACE.Server/Managers/QuestManager.cs @@ -590,7 +590,7 @@ public void HandleKillTask(string killQuestName, WorldObject killedCreature) if (killedCreature == null) { - log.ErrorFormat("{0}.QuestManager.HandleKillTask({1}): input object is null!", Name, killQuestName); + log.LogError("{Name}.QuestManager.HandleKillTask({KillQuestName}): input object is null!", Name, killQuestName); return; } @@ -599,7 +599,7 @@ public void HandleKillTask(string killQuestName, WorldObject killedCreature) if (quest == null) { - log.ErrorFormat("{0}.QuestManager.HandleKillTask({1}): couldn't find kill task {2} in database", Name, killQuestName, questName); + log.LogError("{Name}.QuestManager.HandleKillTask({KillQuestName}): couldn't find kill task {QuestName} in database", Name, killQuestName, questName); return; } @@ -613,7 +613,7 @@ public void HandleKillTask(string killQuestName, WorldObject killedCreature) if (playerQuest == null) { // this should be impossible - log.ErrorFormat("{0}.QuestManager.HandleKillTask({1}): couldn't find kill task {2} in player quests", Name, killQuestName, questName); + log.LogError("{Name}.QuestManager.HandleKillTask({KillQuestName}): couldn't find kill task {QuestName} in player quests", Name, killQuestName, questName); return; } diff --git a/Source/ACE.Server/Managers/RecipeManager.cs b/Source/ACE.Server/Managers/RecipeManager.cs index 965cacaccf..f4b3c903b3 100644 --- a/Source/ACE.Server/Managers/RecipeManager.cs +++ b/Source/ACE.Server/Managers/RecipeManager.cs @@ -82,7 +82,7 @@ public static void UseObjectOnTarget(Player player, WorldObject source, WorldObj } if (recipe.IsTinkering()) - log.InfoFormat("[TINKERING] {0}.UseObjectOnTarget({1}, {2}) | Status: {3}confirmed", player.Name, source.NameWithMaterial, target.NameWithMaterial, (confirmed ? "" : "un")); + log.LogInformation("[TINKERING] {Name}.UseObjectOnTarget({SourceNameWithMaterial}, {TargetNameWithMaterial}) | Status: {ConfirmedPrefix}confirmed", player.Name, source.NameWithMaterial, target.NameWithMaterial, (confirmed ? "" : "un")); var percentSuccess = GetRecipeChance(player, source, target, recipe); @@ -170,7 +170,7 @@ public static bool HasDifficulty(Recipe recipe) if (playerSkill == null) { // this shouldn't happen, but sanity check for unexpected nulls - log.Warn($"RecipeManager.GetRecipeChance({player.Name}, {source.Name}, {target.Name}): recipe {recipe.Id} missing skill"); + log.LogWarning("RecipeManager.GetRecipeChance({PlayerName}, {SourceName}, {TargetName}): recipe {Id} missing skill", player.Name, source.Name, target.Name, recipe.Id); return null; } @@ -667,7 +667,7 @@ public static bool TryMutateNative(Player player, WorldObject source, WorldObjec break; default: - log.Error($"{player.Name}.RecipeManager.Tinkering_ModifyItem({source.Name} ({source.Guid}), {target.Name} ({target.Guid})) - unknown mutation id: {dataId:X8}"); + log.LogError("{PlayerName}.RecipeManager.Tinkering_ModifyItem({SourceName} ({SourceGuid}), {TargetName} ({TargetGuid})) - unknown mutation id: {DataId:X8}", player.Name, source.Name, source.Guid, target.Name, target.Guid, dataId); return false; } @@ -787,7 +787,7 @@ public static bool VerifyUse(Player player, WorldObject source, WorldObject targ if (usable == Usable.Undef) { - log.Warn($"{player.Name}.RecipeManager.VerifyUse({source.Name} ({source.Guid}), {target.Name} ({target.Guid})) - source not usable, falling back on defaults"); + log.LogWarning("{PlayerName}.RecipeManager.VerifyUse({SourceName} ({SourceGuid}), {TargetName} ({TargetGuid})) - source not usable, falling back on defaults", player.Name, source.Name, source.Guid, target.Name, target.Guid); // re-verify if (player.FindObject(source.Guid.Full, Player.SearchLocations.MyInventory) == null) @@ -1034,7 +1034,7 @@ public static HashSet CreateDestroyItems(Player player, Recipe recipe, Wor if (createItem > 0 && DatabaseManager.World.GetCachedWeenie(createItem) == null) { - log.Error($"RecipeManager.CreateDestroyItems: Recipe.Id({recipe.Id}) couldn't find {(success ? "Success" : "Fail")}WCID {createItem} in database."); + log.LogError("RecipeManager.CreateDestroyItems: Recipe.Id({Id}) couldn't find {Result}WCID {CreateItem} in database.", recipe.Id, (success ? "Success" : "Fail"), createItem); player.Session.Network.EnqueueSend(new GameEventWeenieError(player.Session, WeenieError.CraftGeneralErrorUiMsg)); return null; } @@ -1069,7 +1069,7 @@ public static HashSet CreateDestroyItems(Player player, Recipe recipe, Wor player.Session.Network.EnqueueSend(new GameMessageSystemChat(message, ChatMessageType.Craft)); - log.Info($"[CRAFTING] {player.Name} used {source.NameWithMaterial} on {target.NameWithMaterial} {(success ? "" : "un")}successfully. {(destroySource ? $"| {source.NameWithMaterial} was destroyed " : "")}{(destroyTarget ? $"| {target.NameWithMaterial} was destroyed " : "")}| {message}"); + log.LogInformation("[CRAFTING] {Name} used {SourceNameWithMaterial} on {TargetNameWithMaterial} {SuccessPrefix}successfully. {SourceDestroyed}{TargetDestroyed}| {Message}", player.Name, source.NameWithMaterial, target.NameWithMaterial, (success ? "" : "un"), (destroySource ? $"| {source.NameWithMaterial} was destroyed " : ""), (destroyTarget ? $"| {target.NameWithMaterial} was destroyed " : ""), message); } else BroadcastTinkering(player, source, target, successChance, success); @@ -1098,7 +1098,7 @@ public static void BroadcastTinkering(Player player, WorldObject tool, WorldObje // send local broadcast player.EnqueueBroadcast(new GameMessageSystemChat(msg, ChatMessageType.Craft), WorldObject.LocalBroadcastRange, ChatMessageType.Craft); - log.Info($"[TINKERING] {msg} | Chance: {chance}"); + log.LogInformation("[TINKERING] {Msg} | Chance: {Chance}", msg, chance); } public static WorldObject CreateItem(Player player, uint wcid, uint amount) @@ -1107,7 +1107,7 @@ public static WorldObject CreateItem(Player player, uint wcid, uint amount) if (wo == null) { - log.Warn($"RecipeManager.CreateItem({player.Name}, {wcid}, {amount}): failed to create {wcid}"); + log.LogWarning("RecipeManager.CreateItem({Name}, {Wcid}, {Amount}): failed to create {Wcid}", player.Name, wcid, amount, wcid); return null; } @@ -1123,12 +1123,12 @@ public static void DestroyItem(Player player, Recipe recipe, WorldObject item, u if (item.OwnerId == player.Guid.Full || player.GetInventoryItem(item.Guid) != null) { if (!player.TryConsumeFromInventoryWithNetworking(item, (int)amount)) - log.Warn($"RecipeManager.DestroyItem({player.Name}, {item.Name}, {amount}, {msg}): failed to remove {item.Name}"); + log.LogWarning("RecipeManager.DestroyItem({PlayerName}, {ItemName}, {Amount}, {Msg}): failed to remove {ItemName}", player.Name, item.Name, amount, msg, item.Name); } else if (item.WielderId == player.Guid.Full) { if (!player.TryDequipObjectWithNetworking(item.Guid, out _, Player.DequipObjectAction.ConsumeItem)) - log.Warn($"RecipeManager.DestroyItem({player.Name}, {item.Name}, {amount}, {msg}): failed to remove {item.Name}"); + log.LogWarning("RecipeManager.DestroyItem({PlayerName}, {ItemName}, {Amount}, {Msg}): failed to remove {ItemName}", player.Name, item.Name, amount, msg, item.Name); } else { @@ -1150,7 +1150,7 @@ public static WorldObject GetSourceMod(RecipeSourceType sourceType, Player playe case RecipeSourceType.Source: return source; } - log.Warn($"RecipeManager.GetSourceMod({sourceType}, {player.Name}, {source.Name}) - unknown source type"); + log.LogWarning("RecipeManager.GetSourceMod({SourceType}, {PlayerName}, {SourceName}) - unknown source type", sourceType, player.Name, source.Name); return null; } @@ -1260,7 +1260,7 @@ public static void ModifyBool(Player player, RecipeModsBool boolMod, WorldObject // always SetValue? if (op != ModificationOperation.SetValue) { - log.Warn($"RecipeManager.ModifyBool({source.Name}, {target.Name}): unhandled operation {op}"); + log.LogWarning("RecipeManager.ModifyBool({SourceName}, {TargetName}): unhandled operation {Op}", source.Name, target.Name, op); return; } player.UpdateProperty(targetMod, prop, value); @@ -1323,7 +1323,7 @@ public static void ModifyInt(Player player, RecipeModsInt intMod, WorldObject so if (Debug) Console.WriteLine($"{targetMod.Name}.SetProperty({prop}, 0x{bits:X}) - {op}"); break; default: - log.Warn($"RecipeManager.ModifyInt({source.Name}, {target.Name}): unhandled operation {op}"); + log.LogWarning("RecipeManager.ModifyInt({SourceName}, {TargetName}): unhandled operation {Op}", source.Name, target.Name, op); break; } } @@ -1360,7 +1360,7 @@ public static void ModifyFloat(Player player, RecipeModsFloat floatMod, WorldObj if (Debug) Console.WriteLine($"{result.Name}.SetProperty({prop}, {player.GetProperty(prop) ?? 0}) - {op}"); break; default: - log.Warn($"RecipeManager.ModifyFloat({source.Name}, {target.Name}): unhandled operation {op}"); + log.LogWarning("RecipeManager.ModifyFloat({SourceName}, {TargetName}): unhandled operation {Op}", source.Name, target.Name, op); break; } } @@ -1392,7 +1392,7 @@ public static void ModifyString(Player player, RecipeModsString stringMod, World if (Debug) Console.WriteLine($"{result.Name}.SetProperty({prop}, {player.GetProperty(prop) ?? player.Name}) - {op}"); break; default: - log.Warn($"RecipeManager.ModifyString({source.Name}, {target.Name}): unhandled operation {op}"); + log.LogWarning("RecipeManager.ModifyString({SourceName}, {TargetName}): unhandled operation {Op}", source.Name, target.Name, op); break; } } @@ -1424,7 +1424,7 @@ public static void ModifyInstanceID(Player player, RecipeModsIID iidMod, WorldOb if (Debug) Console.WriteLine($"{result.Name}.SetProperty({prop}, {ModifyInstanceIDRuleSet(prop, player, targetMod)}) - {op}"); break; default: - log.Warn($"RecipeManager.ModifyInstanceID({source.Name}, {target.Name}): unhandled operation {op}"); + log.LogWarning("RecipeManager.ModifyInstanceID({SourceName}, {TargetName}): unhandled operation {Op}", source.Name, target.Name, op); break; } } @@ -1470,7 +1470,7 @@ public static void ModifyDataID(Player player, RecipeModsDID didMod, WorldObject if (Debug) Console.WriteLine($"{result.Name}.SetProperty({prop}, {player.GetProperty(prop) ?? 0}) - {op}"); break; default: - log.Warn($"RecipeManager.ModifyDataID({source.Name}, {target.Name}): unhandled operation {op}"); + log.LogWarning("RecipeManager.ModifyDataID({SourceName}, {TargetName}): unhandled operation {Op}", source.Name, target.Name, op); break; } } @@ -1491,7 +1491,7 @@ public static bool TryMutate(Player player, WorldObject source, WorldObject targ if (mutationScript == null) { - log.Error($"RecipeManager.TryApplyMutation({dataId:X8}, {target.Name}) - couldn't find mutation script"); + log.LogError("RecipeManager.TryApplyMutation({DataId:X8}, {Name}) - couldn't find mutation script", dataId, target.Name); return false; } @@ -1521,7 +1521,7 @@ public static string GetMaterialName(MaterialType materialType) if (!dualDIDs.ClientEnumToName.TryGetValue((uint)materialType, out var materialName)) { - log.Error($"RecipeManager.GetMaterialName({materialType}): couldn't find material name"); + log.LogError("RecipeManager.GetMaterialName({MaterialType}): couldn't find material name", materialType); return materialType.ToString(); } return materialName.Replace("_", " "); diff --git a/Source/ACE.Server/Managers/ServerManager.cs b/Source/ACE.Server/Managers/ServerManager.cs index ee8b90c28f..6f96e8a06b 100644 --- a/Source/ACE.Server/Managers/ServerManager.cs +++ b/Source/ACE.Server/Managers/ServerManager.cs @@ -52,7 +52,7 @@ public static class ServerManager /// postive value representing seconds public static void SetShutdownInterval(uint interval) { - log.Info($"Server shutdown interval reset: {interval}"); + log.LogInformation("Server shutdown interval reset: {Interval}", interval); ShutdownInterval = interval; } @@ -111,7 +111,7 @@ private static void ShutdownServer() { // reset shutdown details string shutdownText = $"The server shut down has been cancelled @ {DateTime.Now.ToCommonString()} ({DateTime.UtcNow.ToCommonString()} UTC)"; - log.Info(shutdownText); + log.LogInformation("{Message:l}", shutdownText); // special text foreach (var player in PlayerManager.GetAllOnline()) @@ -133,7 +133,7 @@ private static void ShutdownServer() WorldManager.EnqueueAction(new ActionEventDelegate(() => { - log.Debug("Logging off all players..."); + log.LogDebug("Logging off all players..."); // logout each player foreach (var player in PlayerManager.GetAllOnline()) @@ -151,10 +151,10 @@ private static void ShutdownServer() if (playerCount > 0 && DateTime.UtcNow - playerLogoffStart > TimeSpan.FromMinutes(5)) { playerLogoffStart = DateTime.UtcNow; - log.WarnFormat("5 minute log off failsafe reached and there are {0} player{1} still online.", playerCount, (playerCount > 1 ? "s" : "")); + log.LogWarning("5 minute log off failsafe reached and there are {PlayerCount} player{PlayerPlural} still online.", playerCount, (playerCount > 1 ? "s" : "")); foreach (var player in PlayerManager.GetAllOnline()) { - log.WarnFormat("Player {0} (0x{1}) appears to be stuck in world and unable to log off normally. Requesting Forced Logoff...", player.Name, player.Guid); + log.LogWarning("Player {Name} (0x{Guid}) appears to be stuck in world and unable to log off normally. Requesting Forced Logoff...", player.Name, player.Guid); player.ForcedLogOffRequested = true; player.ForceLogoff(); } @@ -163,7 +163,7 @@ private static void ShutdownServer() WorldManager.EnqueueAction(new ActionEventDelegate(() => { - log.Debug("Disconnecting all sessions..."); + log.LogDebug("Disconnecting all sessions..."); // disconnect each session NetworkManager.DisconnectAllSessionsForShutdown(); @@ -178,7 +178,7 @@ private static void ShutdownServer() Thread.Sleep(10); } - log.Debug("Adding all landblocks to destruction queue..."); + log.LogDebug("Adding all landblocks to destruction queue..."); // Queue unloading of all the landblocks // The actual unloading will happen in WorldManager.UpdateGameWorld @@ -193,7 +193,7 @@ private static void ShutdownServer() Thread.Sleep(10); } - log.Debug("Stopping world..."); + log.LogDebug("Stopping world..."); // Disabled thread update loop WorldManager.StopWorld(); @@ -209,7 +209,7 @@ private static void ShutdownServer() Thread.Sleep(10); } - log.Info("Saving OfflinePlayers that have unsaved changes..."); + log.LogInformation("Saving OfflinePlayers that have unsaved changes..."); PlayerManager.SaveOfflinePlayersWithChanges(); // Wait for the database queue to empty @@ -222,7 +222,7 @@ private static void ShutdownServer() } // Write exit to console/log - log.Info($"Exiting at {DateTime.UtcNow.ToCommonString()}"); + log.LogInformation("Exiting at {UtcNow}", DateTime.UtcNow.ToCommonString()); // System exit Environment.Exit(Environment.ExitCode); @@ -232,7 +232,7 @@ private static DateTime LogStatusUpdate(DateTime logUpdateTS, string logMessage) { if (logUpdateTS == DateTime.MinValue || DateTime.UtcNow > logUpdateTS.ToUniversalTime()) { - log.Info(logMessage); + log.LogInformation("{Message:l}", logMessage); logUpdateTS = DateTime.UtcNow.AddSeconds(10); } diff --git a/Source/ACE.Server/Managers/WorldManager.cs b/Source/ACE.Server/Managers/WorldManager.cs index c2808fca47..d9f64a4cbc 100644 --- a/Source/ACE.Server/Managers/WorldManager.cs +++ b/Source/ACE.Server/Managers/WorldManager.cs @@ -64,12 +64,12 @@ public static void Initialize() thread.Name = "World Manager"; thread.Priority = ThreadPriority.AboveNormal; thread.Start(); - log.DebugFormat("ServerTime initialized to {0}", Timers.WorldStartLoreTime); - log.DebugFormat("Current maximum allowed sessions: {0}", ConfigManager.Config.Server.Network.MaximumAllowedSessions); + log.LogDebug("ServerTime initialized to {WorldStartLoreTime}", Timers.WorldStartLoreTime); + log.LogDebug("Current maximum allowed sessions: {MaximumAllowedSessions}", ConfigManager.Config.Server.Network.MaximumAllowedSessions); - log.Info($"World started and is currently {WorldStatus.ToString()}{(PropertyManager.GetBool("world_closed", false).Item ? "" : " and will open automatically when server startup is complete.")}"); + log.LogInformation("World started and is currently {WorldStatus}{OpenNote}", WorldStatus.ToString(), (PropertyManager.GetBool("world_closed", false).Item ? "" : " and will open automatically when server startup is complete.")); if (WorldStatus == WorldStatusState.Closed) - log.Info($"To open world to players, use command: world open"); + log.LogInformation("To open world to players, use command: world open"); } internal static void Open(Player player) @@ -97,14 +97,14 @@ public static void PlayerEnterWorld(Session session, Character character) if (offlinePlayer == null) { - log.Error($"PlayerEnterWorld requested for character.Id 0x{character.Id:X8} not found in PlayerManager OfflinePlayers."); + log.LogError("PlayerEnterWorld requested for character.Id 0x{Id:X8} not found in PlayerManager OfflinePlayers.", character.Id); return; } var start = DateTime.UtcNow; DatabaseManager.Shard.GetPossessedBiotasInParallel(character.Id, biotas => { - log.DebugFormat("GetPossessedBiotasInParallel for {0} took {1:N0} ms", character.Name, (DateTime.UtcNow - start).TotalMilliseconds); + log.LogDebug("GetPossessedBiotasInParallel for {Name} took {TotalMilliseconds:N0} ms", character.Name, (DateTime.UtcNow - start).TotalMilliseconds); ActionQueue.EnqueueAction(new ActionEventDelegate(() => DoPlayerEnterWorld(session, character, offlinePlayer.Biota, biotas))); }); @@ -226,7 +226,7 @@ private static void DoPlayerEnterWorld(Session session, Character character, Bio // send to lifestone, or fallback location var fixLoc = session.Player.Sanctuary ?? new Position(0xA9B40019, 84, 7.1f, 94, 0, 0, -0.0784591f, 0.996917f); - log.Error($"WorldManager.DoPlayerEnterWorld: failed to spawn {session.Player.Name}, relocating to {fixLoc.ToLOCString()}"); + log.LogError("WorldManager.DoPlayerEnterWorld: failed to spawn {Name}, relocating to {FixLoc}", session.Player.Name, fixLoc.ToLOCString()); session.Player.Location = new Position(fixLoc); LandblockManager.AddObject(session.Player, true); @@ -322,7 +322,7 @@ public static void EnqueueAction(IAction action) /// private static void UpdateWorld() { - log.DebugFormat("Starting UpdateWorld thread"); + log.LogDebug("Starting UpdateWorld thread"); WorldActive = true; var worldTickTimer = new Stopwatch(); diff --git a/Source/ACE.Server/Mods/ModContainer.cs b/Source/ACE.Server/Mods/ModContainer.cs index 195cea323e..724252e8ef 100644 --- a/Source/ACE.Server/Mods/ModContainer.cs +++ b/Source/ACE.Server/Mods/ModContainer.cs @@ -50,7 +50,7 @@ public void Initialize() { if (Meta is null) { - log.Warn($"Unable to initialize. Check Meta.json..."); + log.LogWarning("Unable to initialize. Check Meta.json..."); return; } @@ -67,7 +67,7 @@ public void Initialize() ); Loader.Reloaded += Reload; - log.Info($"Set up {FolderName}"); + log.LogInformation("Set up {FolderName}", FolderName); } /// @@ -77,12 +77,12 @@ public void Enable() { if (Status == ModStatus.Active) { - log.Info($"Mod is already enabled: {Meta.Name}"); + log.LogInformation("Mod is already enabled: {Name}", Meta.Name); return; } if (Status == ModStatus.LoadFailure) { - log.Info($"Unable to activate mod that failed to load: {Meta.Name}"); + log.LogInformation("Unable to activate mod that failed to load: {Name}", Meta.Name); return; } @@ -100,7 +100,7 @@ public void Enable() //Only mods with loaded assemblies that aren't active can be enabled if (Status != ModStatus.Inactive) { - log.Info($"{Meta.Name} is not inactive."); + log.LogInformation("{Name} is not inactive.", Meta.Name); return; } @@ -113,11 +113,11 @@ public void Enable() if (Meta.RegisterCommands) this.RegisterUncategorizedCommands(); - log.Info($"Enabled mod `{Meta.Name} (v{Meta.Version})`."); + log.LogInformation("Enabled mod `{Name} (v{Version})`.", Meta.Name, Meta.Version); } catch (Exception ex) { - log.Error($"Error enabling {Meta.Name}: {ex}"); + log.LogError("Error enabling {Name}: {Ex}", Meta.Name, ex); Status = ModStatus.Inactive; //Todo: what status? Something to prevent reload attempts? } } @@ -137,7 +137,7 @@ public void Disable() if (Status != ModStatus.Active) return; - log.Info($"{FolderName} shutting down @ {DateTime.Now.ToCommonString()}"); + log.LogInformation("{FolderName} shutting down @ {Now}", FolderName, DateTime.Now.ToCommonString()); this.UnregisterAllCommands(); @@ -163,7 +163,7 @@ private bool TryLoadModAssembly() { if (!File.Exists(DllPath)) { - log.Warn($"Missing mod: {DllPath}"); + log.LogWarning("Missing mod: {DllPath}", DllPath); return false; } @@ -180,14 +180,14 @@ private bool TryLoadModAssembly() if (ModType is null) { Status = ModStatus.LoadFailure; - log.Warn($"Missing IHarmonyMod Type {TypeName} from {ModAssembly}"); + log.LogWarning("Missing IHarmonyMod Type {TypeName} from {ModAssembly}", TypeName, ModAssembly); return false; } } catch (Exception e) { Status = ModStatus.LoadFailure; - log.Error($"Failed to load mod file `{DllPath}`: {e}"); + log.LogError("Failed to load mod file `{DllPath}`: {E}", DllPath, e); return false; } @@ -200,12 +200,12 @@ private bool TryCreateModInstance() try { Instance = Activator.CreateInstance(ModType) as IHarmonyMod; - log.Info($"Created instance of {Meta.Name}"); + log.LogInformation("Created instance of {Name}", Meta.Name); } catch (Exception ex) { Status = ModStatus.LoadFailure; - log.Error($"Failed to create Mod instance: {Meta.Name}: {ex}"); + log.LogError("Failed to create Mod instance: {Name}: {Ex}", Meta.Name, ex); return false; } @@ -218,7 +218,7 @@ public void SaveMetadata() var info = new FileInfo(MetadataPath); if (!info.RetryWrite(json)) - log.Error($"Saving metadata failed: {MetadataPath}"); + log.LogError("Saving metadata failed: {MetadataPath}", MetadataPath); } #region Events @@ -228,13 +228,13 @@ private void Reload(object sender, PluginReloadedEventArgs eventArgs) var lapsed = DateTime.Now - _lastChange; if (lapsed < RELOAD_TIMEOUT) { - log.Info($"Not reloading {FolderName}: {lapsed.TotalSeconds}/{RELOAD_TIMEOUT.TotalSeconds}"); + log.LogInformation("Not reloading {FolderName}: {LapsedTotalSeconds}/{RELOAD_TIMEOUTTotalSeconds}", FolderName, lapsed.TotalSeconds, RELOAD_TIMEOUT.TotalSeconds); return; //Shutdown(); } Restart(); - log.Info($"Reloaded {FolderName} @ {DateTime.Now.ToCommonString()} after {lapsed.TotalSeconds}/{RELOAD_TIMEOUT.TotalSeconds} seconds"); + log.LogInformation("Reloaded {FolderName} @ {Now} after {LapsedTotalSeconds}/{RELOAD_TIMEOUTTotalSeconds} seconds", FolderName, DateTime.Now.ToCommonString(), lapsed.TotalSeconds, RELOAD_TIMEOUT.TotalSeconds); } @@ -248,7 +248,7 @@ private void ModDll_Changed(object sender, FileSystemEventArgs e) return; } - log.Info($"{FolderName} changed @ {DateTime.Now.ToCommonString()} after {lapsed.TotalMilliseconds}ms"); + log.LogInformation("{FolderName} changed @ {Now} after {TotalMilliseconds}ms", FolderName, DateTime.Now.ToCommonString(), lapsed.TotalMilliseconds); _lastChange = DateTime.Now; Disable(); diff --git a/Source/ACE.Server/Mods/ModManager.cs b/Source/ACE.Server/Mods/ModManager.cs index d81fff787a..4082dd4df0 100644 --- a/Source/ACE.Server/Mods/ModManager.cs +++ b/Source/ACE.Server/Mods/ModManager.cs @@ -52,11 +52,11 @@ public static void FindMods(bool registerCommands = false) try { Directory.CreateDirectory(ModPath); - log.Info($"Created mod folder at:\r\n{ModPath}"); + log.LogInformation("Created mod folder at:\r\n{ModPath}", ModPath); } catch (Exception ex) { - log.Error($"Failed to create mod folder:\r\n{ModPath}\n{ex}"); + log.LogError("Failed to create mod folder:\r\n{ModPath}\n{Ex}", ModPath, ex); return; } } @@ -139,7 +139,7 @@ private static bool TryLoadModContainer(string metadataPath, out ModContainer co if (!File.Exists(metadataPath)) { //Log missing metadata - log.WarnFormat("Metadata not found at: {0}", metadataPath); + log.LogWarning("Metadata not found at: {MetadataPath}", metadataPath); return false; } @@ -157,7 +157,7 @@ private static bool TryLoadModContainer(string metadataPath, out ModContainer co } catch (Exception ex) { - log.Error($"Unable to deserialize mod metadata from: {metadataPath}\n{ex}"); + log.LogError("Unable to deserialize mod metadata from: {MetadataPath}\n{Ex}", metadataPath, ex); return false; } } @@ -246,7 +246,7 @@ public static void ListMods(Player player = null) } } - log.Info(sb); + log.LogInformation("{Message:l}", sb); player?.SendMessage(sb.ToString()); } @@ -264,22 +264,22 @@ public static void Log(string message, LogLevel level = LogLevel.Info) switch (level) { case LogLevel.Debug: - log.Debug(message); + log.LogDebug("{Message:l}", message); break; case LogLevel.Error: - log.Error(message); + log.LogError("{Message:l}", message); break; case LogLevel.Fatal: - log.Fatal(message); + log.LogCritical("{Message:l}", message); break; case LogLevel.Info: - log.Info(message); + log.LogInformation("{Message:l}", message); break; case LogLevel.Warn: - log.Warn(message); + log.LogWarning("{Message:l}", message); break; default: - log.Info(message); + log.LogInformation("{Message:l}", message); break; }; } diff --git a/Source/ACE.Server/Network/ClientPacket.cs b/Source/ACE.Server/Network/ClientPacket.cs index 433120a914..1d43e95f6c 100644 --- a/Source/ACE.Server/Network/ClientPacket.cs +++ b/Source/ACE.Server/Network/ClientPacket.cs @@ -46,7 +46,7 @@ public bool Unpack(byte[] buffer, int bufferSize) } catch (Exception ex) { - packetLog.Error("Invalid packet data", ex); + packetLog.LogError(ex, "Invalid packet data"); return false; } @@ -151,13 +151,13 @@ public bool VerifyCRC(CryptoSystem fq) { if (headerChecksum + payloadChecksum == Header.Checksum) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("{0}", this); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("{Value}", this); return true; } - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("{0}, Checksum Failed", this); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("{Value}, Checksum Failed", this); } NetworkStatistics.C2S_CRCErrors_Aggregate_Increment(); diff --git a/Source/ACE.Server/Network/ConnectionListener.cs b/Source/ACE.Server/Network/ConnectionListener.cs index e889718e39..4ceafef5bd 100644 --- a/Source/ACE.Server/Network/ConnectionListener.cs +++ b/Source/ACE.Server/Network/ConnectionListener.cs @@ -30,7 +30,7 @@ public class ConnectionListener public ConnectionListener(IPAddress host, uint port) { - log.DebugFormat("ConnectionListener ctor, host {0} port {1}", host, port); + log.LogDebug("ConnectionListener ctor, host {Host} port {Port}", host, port); listeningHost = host; listeningPort = port; @@ -38,7 +38,7 @@ public ConnectionListener(IPAddress host, uint port) public void Start() { - log.DebugFormat("Starting ConnectionListener, host {0} port {1}", listeningHost, listeningPort); + log.LogDebug("Starting ConnectionListener, host {ListeningHost} port {ListeningPort}", listeningHost, listeningPort); try { @@ -59,13 +59,13 @@ public void Start() } catch (Exception exception) { - log.FatalFormat("Network Socket has thrown: {0}", exception.Message); + log.LogCritical("Network Socket has thrown: {Message}", exception.Message); } } public void Shutdown() { - log.DebugFormat("Shutting down ConnectionListener, host {0} port {1}", listeningHost, listeningPort); + log.LogDebug("Shutting down ConnectionListener, host {ListeningHost} port {ListeningPort}", listeningHost, listeningPort); if (Socket != null && Socket.IsBound) Socket.Close(); @@ -80,12 +80,12 @@ private void Listen() } catch (SocketException socketException) { - log.DebugFormat("ConnectionListener({2}, {3}).Listen() has thrown {0}: {1}", socketException.SocketErrorCode, socketException.Message, listeningHost, listeningPort); + log.LogDebug("ConnectionListener({ListeningHost}, {ListeningPort}).Listen() has thrown {SocketErrorCode}: {Message}", listeningHost, listeningPort, socketException.SocketErrorCode, socketException.Message); Listen(); } catch (Exception exception) { - log.FatalFormat("ConnectionListener({1}, {2}).Listen() has thrown: {0}", exception.Message, listeningHost, listeningPort); + log.LogCritical("ConnectionListener({ListeningHost}, {ListeningPort}).Listen() has thrown: {Message}", listeningHost, listeningPort, exception.Message); } } @@ -102,7 +102,7 @@ private void OnDataReceive(IAsyncResult result) // TO-DO: generate ban entries here based on packet rates of endPoint, IP Address, and IP Address Range - if (packetLog.IsDebugEnabled) + if (packetLog.IsEnabled(LogLevel.Debug)) { byte[] data = new byte[dataSize]; Buffer.BlockCopy(buffer, 0, data, 0, dataSize); @@ -110,7 +110,7 @@ private void OnDataReceive(IAsyncResult result) StringBuilder sb = new StringBuilder(); sb.AppendLine($"Received Packet (Len: {data.Length}) [{ipEndpoint.Address}:{ipEndpoint.Port}=>{ListenerEndpoint.Address}:{ListenerEndpoint.Port}]"); sb.AppendLine(data.BuildPacketString()); - packetLog.DebugFormat("{0}", sb); + packetLog.LogDebug("{Sb}", sb); } var packet = new ClientPacket(); @@ -129,11 +129,11 @@ private void OnDataReceive(IAsyncResult result) socketException.SocketErrorCode == SocketError.NetworkReset || socketException.SocketErrorCode == SocketError.ConnectionReset) { - log.DebugFormat("ConnectionListener({3}, {4}).OnDataReceieve() has thrown {0}: {1} from client {2}", socketException.SocketErrorCode, socketException.Message, clientEndPoint != null ? clientEndPoint.ToString() : "Unknown", listeningHost, listeningPort); + log.LogDebug("ConnectionListener({ListeningHost}, {ListeningPort}).OnDataReceieve() has thrown {SocketErrorCode}: {Message} from client {ClientEndPoint}", listeningHost, listeningPort, socketException.SocketErrorCode, socketException.Message, (clientEndPoint != null ? clientEndPoint.ToString() : "Unknown")); } else { - log.FatalFormat("ConnectionListener({3}, {4}).OnDataReceieve() has thrown {0}: {1} from client {2}", socketException.SocketErrorCode, socketException.Message, clientEndPoint != null ? clientEndPoint.ToString() : "Unknown", listeningHost, listeningPort); + log.LogCritical("ConnectionListener({ListeningHost}, {ListeningPort}).OnDataReceieve() has thrown {SocketErrorCode}: {Message} from client {ClientEndPoint}", listeningHost, listeningPort, socketException.SocketErrorCode, socketException.Message, (clientEndPoint != null ? clientEndPoint.ToString() : "Unknown")); return; } } diff --git a/Source/ACE.Server/Network/GameAction/Actions/GameActionSetCharacterOptions.cs b/Source/ACE.Server/Network/GameAction/Actions/GameActionSetCharacterOptions.cs index 874fe03002..3bfe4e8fbf 100644 --- a/Source/ACE.Server/Network/GameAction/Actions/GameActionSetCharacterOptions.cs +++ b/Source/ACE.Server/Network/GameAction/Actions/GameActionSetCharacterOptions.cs @@ -31,7 +31,7 @@ public static void Handle(ClientMessage message, Session session) // and their client will send the default character options upon clicking the logout button, // overwriting their custom options on the server with the defaults. this code avoids that situation - log.Warn($"{session.Player.Name} sent GameAction 0x1A1 - SetCharacterOptions before FirstEnterWorldDone, ignoring..."); + log.LogWarning("{Name} sent GameAction 0x1A1 - SetCharacterOptions before FirstEnterWorldDone, ignoring...", session.Player.Name); return; } diff --git a/Source/ACE.Server/Network/GameAction/Actions/GameActionTalk.cs b/Source/ACE.Server/Network/GameAction/Actions/GameActionTalk.cs index c6e8916a0c..9326ec300d 100644 --- a/Source/ACE.Server/Network/GameAction/Actions/GameActionTalk.cs +++ b/Source/ACE.Server/Network/GameAction/Actions/GameActionTalk.cs @@ -33,7 +33,7 @@ public static void Handle(ClientMessage clientMessage, Session session) } catch (Exception ex) { - log.Error($"Exception while parsing command: {commandRaw}", ex); + log.LogError(ex, "Exception while parsing command: {CommandRaw}", commandRaw); return; } @@ -43,7 +43,7 @@ public static void Handle(ClientMessage clientMessage, Session session) } catch (Exception ex) { - log.Error($"Exception while getting command handler for: {commandRaw}", ex); + log.LogError(ex, "Exception while getting command handler for: {CommandRaw}", commandRaw); } if (response == CommandHandlerResponse.Ok) @@ -58,7 +58,7 @@ public static void Handle(ClientMessage clientMessage, Session session) } catch (Exception ex) { - log.Error($"Exception while invoking command handler for: {commandRaw}", ex); + log.LogError(ex, "Exception while invoking command handler for: {CommandRaw}", commandRaw); } } else if (response == CommandHandlerResponse.SudoOk) @@ -76,7 +76,7 @@ public static void Handle(ClientMessage clientMessage, Session session) } catch (Exception ex) { - log.Error($"Exception while invoking command handler for: {commandRaw}", ex); + log.LogError(ex, "Exception while invoking command handler for: {CommandRaw}", commandRaw); } } else diff --git a/Source/ACE.Server/Network/Handlers/AuthenticationHandler.cs b/Source/ACE.Server/Network/Handlers/AuthenticationHandler.cs index 86f7bd65a9..5dca0f2c90 100644 --- a/Source/ACE.Server/Network/Handlers/AuthenticationHandler.cs +++ b/Source/ACE.Server/Network/Handlers/AuthenticationHandler.cs @@ -48,8 +48,8 @@ public static void HandleLoginRequest(ClientPacket packet, Session session) } catch (Exception ex) { - log.ErrorFormat("Received LoginRequest from {0} that threw an exception.", session.EndPointC2S); - log.Error(ex); + log.LogError("Received LoginRequest from {EndPointC2S} that threw an exception.", session.EndPointC2S); + log.LogError(ex, "{Message:l}", ex.Message); } } @@ -65,9 +65,9 @@ private static void DoLogin(Session session, PacketInboundLoginRequest loginRequ { // no account, dynamically create one if (WorldManager.WorldStatus == WorldManager.WorldStatusState.Open) - log.Info($"Auto creating account for: {loginRequest.Account}"); + log.LogInformation("Auto creating account for: {Account}", loginRequest.Account); else - log.DebugFormat("Auto creating account for: {0}", loginRequest.Account); + log.LogDebug("Auto creating account for: {Account}", loginRequest.Account); var accessLevel = (AccessLevel)ConfigManager.Config.Server.Accounts.DefaultAccessLevel; @@ -78,7 +78,7 @@ private static void DoLogin(Session session, PacketInboundLoginRequest loginRequ { accessLevel = AccessLevel.Admin; DatabaseManager.AutoPromoteNextAccountToAdmin = false; - log.Warn($"Automatically setting account AccessLevel to Admin for account \"{loginRequest.Account}\" because there are no admin accounts in the current database."); + log.LogWarning("Automatically setting account AccessLevel to Admin for account \"{Account}\" because there are no admin accounts in the current database.", loginRequest.Account); } account = DatabaseManager.Authentication.CreateAccount(loginRequest.Account.ToLower(), loginRequest.Password, accessLevel, session.EndPointC2S.Address); @@ -88,12 +88,12 @@ private static void DoLogin(Session session, PacketInboundLoginRequest loginRequ try { - log.DebugFormat("new client connected: {0}. setting session properties", loginRequest.Account); + log.LogDebug("new client connected: {Account}. setting session properties", loginRequest.Account); AccountSelectCallback(account, session, loginRequest); } catch (Exception ex) { - log.Error("Error in HandleLoginRequest trying to find the account.", ex); + log.LogError(ex, "Error in HandleLoginRequest trying to find the account."); session.Terminate(SessionTerminationReason.AccountSelectCallbackException); } } @@ -101,8 +101,8 @@ private static void DoLogin(Session session, PacketInboundLoginRequest loginRequ private static void AccountSelectCallback(Account account, Session session, PacketInboundLoginRequest loginRequest) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("ConnectRequest TS: {0}", Timers.PortalYearTicks); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("ConnectRequest TS: {PortalYearTicks}", Timers.PortalYearTicks); if (session.Network.ConnectionData.ServerSeed == null || session.Network.ConnectionData.ClientSeed == null) { @@ -140,9 +140,9 @@ private static void AccountSelectCallback(Account account, Session session, Pack } if (WorldManager.WorldStatus == WorldManager.WorldStatusState.Open) - log.InfoFormat("client {0} connected with no Password or GlsTicket included so booting", loginRequest.Account); + log.LogInformation("client {Account} connected with no Password or GlsTicket included so booting", loginRequest.Account); else - log.DebugFormat("client {0} connected with no Password or GlsTicket included so booting", loginRequest.Account); + log.LogDebug("client {Account} connected with no Password or GlsTicket included so booting", loginRequest.Account); session.Terminate(SessionTerminationReason.NotAuthorizedNoPasswordOrGlsTicketIncludedInLoginReq, new GameMessageCharacterError(CharacterError.AccountInvalid)); @@ -169,9 +169,9 @@ private static void AccountSelectCallback(Account account, Session session, Pack if (!account.PasswordMatches(loginRequest.Password)) { if (WorldManager.WorldStatus == WorldManager.WorldStatusState.Open) - log.Info($"client {loginRequest.Account} connected with non matching password so booting"); + log.LogInformation("client {Account} connected with non matching password so booting", loginRequest.Account); else - log.DebugFormat("client {0} connected with non matching password so booting", loginRequest.Account); + log.LogDebug("client {Account} connected with non matching password so booting", loginRequest.Account); session.Terminate(SessionTerminationReason.NotAuthorizedPasswordMismatch, new GameMessageBootAccount(" because the password entered for this account was not correct")); @@ -197,16 +197,16 @@ private static void AccountSelectCallback(Account account, Session session, Pack } if (WorldManager.WorldStatus == WorldManager.WorldStatusState.Open) - log.Info($"client {loginRequest.Account} connected with verified password"); + log.LogInformation("client {Account} connected with verified password", loginRequest.Account); else - log.DebugFormat("client {0} connected with verified password", loginRequest.Account); + log.LogDebug("client {Account} connected with verified password", loginRequest.Account); } else if (loginRequest.NetAuthType == NetAuthType.GlsTicket) { if (WorldManager.WorldStatus == WorldManager.WorldStatusState.Open) - log.Info($"client {loginRequest.Account} connected with GlsTicket which is not implemented yet so booting"); + log.LogInformation("client {Account} connected with GlsTicket which is not implemented yet so booting", loginRequest.Account); else - log.DebugFormat("client {0} connected with GlsTicket which is not implemented yet so booting", loginRequest.Account); + log.LogDebug("client {Account} connected with GlsTicket which is not implemented yet so booting", loginRequest.Account); session.Terminate(SessionTerminationReason.NotAuthorizedGlsTicketNotImplementedToProcLoginReq, new GameMessageCharacterError(CharacterError.AccountInvalid)); diff --git a/Source/ACE.Server/Network/Handlers/CharacterHandler.cs b/Source/ACE.Server/Network/Handlers/CharacterHandler.cs index ccf4f5b374..1f924c6816 100644 --- a/Source/ACE.Server/Network/Handlers/CharacterHandler.cs +++ b/Source/ACE.Server/Network/Handlers/CharacterHandler.cs @@ -113,7 +113,7 @@ private static void CharacterCreateEx(ClientMessage message, Session session) if (weenie == null) // If it is STILL null after the above catchall, the database is missing critical data and cannot continue with character creation. { SendCharacterCreateResponse(session, CharacterGenerationVerificationResponse.DatabaseDown); - log.Error("Database does not contain the weenie for human (1). Characters cannot be created until the missing weenie is restored."); + log.LogError("Database does not contain the weenie for human (1). Characters cannot be created until the missing weenie is restored."); return; } diff --git a/Source/ACE.Server/Network/Handlers/DDDHandler.cs b/Source/ACE.Server/Network/Handlers/DDDHandler.cs index bbfd842114..7bec90019e 100644 --- a/Source/ACE.Server/Network/Handlers/DDDHandler.cs +++ b/Source/ACE.Server/Network/Handlers/DDDHandler.cs @@ -150,7 +150,7 @@ public static void DDD_InterrogationResponse(ClientMessage message, Session sess else if (clientIsMissingIterations) logMsg += " | update required"; else logMsg += " | no update required"; if (clientIsMissingIterations && !enableDATpatching) logMsg += ", but DAT patching is disabled"; - log.Info(logMsg); + log.LogInformation("{Message:l}", logMsg); if (clientHasExtraIterations) { @@ -165,7 +165,7 @@ public static void DDD_InterrogationResponse(ClientMessage message, Session sess session.BeginDDDSentTime = DateTime.UtcNow; session.BeginDDDSent = true; - log.Info($"[DDD] client {session.Account} informed with BeginDDD payload:\n Total Missing Iterations: {totalMissingIterations} | Expected Data Transfer Size: {totalFileSize / 1024:N0} kB"); + log.LogInformation("[DDD] client {Account} informed with BeginDDD payload:\n Total Missing Iterations: {TotalMissingIterations} | Expected Data Transfer Size: {TotalFileSizeKb:N0} kB", session.Account, totalMissingIterations, totalFileSize / 1024); var hasPortalMissingIterations = missingIterations.TryGetValue(DatDatabaseType.Portal, out var portalMissingIterations); var hasLanguageMissingIterations = missingIterations.TryGetValue(DatDatabaseType.Language, out var languageMissingIterations); @@ -181,7 +181,7 @@ public static void DDD_InterrogationResponse(ClientMessage message, Session sess //session.Network.EnqueueSend(new GameMessageDDDDataMessage(fileId, DatDatabaseType.Portal)); DDDManager.AddToQueue(session, fileId, DatDatabaseType.Portal); else - log.Warn($"[DDD] DDD_InterrogationResponse: DDDManager.AddToQueue failed: DatManager.PortalDat.AllFiles does not contain 0x{fileId:X8}"); + log.LogWarning("[DDD] DDD_InterrogationResponse: DDDManager.AddToQueue failed: DatManager.PortalDat.AllFiles does not contain 0x{FileId:X8}", fileId); } } } @@ -196,7 +196,7 @@ public static void DDD_InterrogationResponse(ClientMessage message, Session sess //session.Network.EnqueueSend(new GameMessageDDDDataMessage(fileId, DatDatabaseType.Language)); DDDManager.AddToQueue(session, fileId, DatDatabaseType.Language); else - log.Warn($"[DDD] DDD_InterrogationResponse: DDDManager.AddToQueue failed: DatManager.LanguageDat.AllFiles does not contain 0x{fileId:X8}"); + log.LogWarning("[DDD] DDD_InterrogationResponse: DDDManager.AddToQueue failed: DatManager.LanguageDat.AllFiles does not contain 0x{FileId:X8}", fileId); } } } @@ -211,7 +211,7 @@ public static void DDD_InterrogationResponse(ClientMessage message, Session sess //session.Network.EnqueueSend(new GameMessageDDDDataMessage(fileId, DatDatabaseType.HighRes)); DDDManager.AddToQueue(session, fileId, DatDatabaseType.HighRes); else - log.Warn($"[DDD] DDD_InterrogationResponse: DDDManager.AddToQueue failed: DatManager.HighResDat.AllFiles does not contain 0x{fileId:X8}"); + log.LogWarning("[DDD] DDD_InterrogationResponse: DDDManager.AddToQueue failed: DatManager.HighResDat.AllFiles does not contain 0x{FileId:X8}", fileId); } } } @@ -243,7 +243,7 @@ public static void DDD_EndDDD(ClientMessage message, Session session) session.DatWarnLanguage = false; session.DatWarnHighRes = false; - log.Info($"[DDD] client {session.Account} reported it successfully received and patched its DAT files with expected BeginDDD payload"); + log.LogInformation("[DDD] client {Account} reported it successfully received and patched its DAT files with expected BeginDDD payload", session.Account); } } @@ -256,7 +256,7 @@ public static void DDD_RequestDataMessage(ClientMessage message, Session session var qdid_type = (DatFileType)message.Payload.ReadUInt32(); var qdid_ID = message.Payload.ReadUInt32(); - log.Info($"[DDD] client {session.Account} requested data on 0x{qdid_ID:X8} | {qdid_type}{(!enableDATpatching ? $"; DAT patching is disabled{(showDatWarning ? " and client will be booted" : "")}" : "")}"); + log.LogInformation("[DDD] client {Account} requested data on 0x{Qdid_ID:X8} | {Qdid_type}{DatPatchingNote}", session.Account, qdid_ID, qdid_type, (!enableDATpatching ? $"; DAT patching is disabled{(showDatWarning ? " and client will be booted" : "")}" : "")); if (!enableDATpatching) { @@ -303,11 +303,11 @@ public static void DDD_RequestDataMessage(ClientMessage message, Session session //session.Network.EnqueueSend(new GameMessageDDDDataMessage(qdid_ID, DatDatabaseType.Cell)); DDDManager.AddToQueue(session, qdid_ID, DatDatabaseType.Cell); else if (qdid_type != DatFileType.LandBlockInfo) - log.Warn($"[DDD] DDD_RequestDataMessage: The server does not have the requested data on 0x{qdid_ID:X8} | {qdid_type} to send to client {session.Account}."); + log.LogWarning("[DDD] DDD_RequestDataMessage: The server does not have the requested data on 0x{Qdid_ID:X8} | {Qdid_type} to send to client {Account}.", qdid_ID, qdid_type, session.Account); } else { - log.Warn($"[DDD] DDD_RequestDataMessage: client {session.Account} requested data on 0x{qdid_ID:X8} | {qdid_type} which has been ignored."); + log.LogWarning("[DDD] DDD_RequestDataMessage: client {Account} requested data on 0x{Qdid_ID:X8} | {Qdid_type} which has been ignored.", session.Account, qdid_ID, qdid_type); } } } diff --git a/Source/ACE.Server/Network/Handlers/TurbineChatHandler.cs b/Source/ACE.Server/Network/Handlers/TurbineChatHandler.cs index cc91ce4570..36a548115e 100644 --- a/Source/ACE.Server/Network/Handlers/TurbineChatHandler.cs +++ b/Source/ACE.Server/Network/Handlers/TurbineChatHandler.cs @@ -105,10 +105,10 @@ public static void TurbineChatReceived(ClientMessage clientMessage, Session sess } if (channelID != adjustedChannelID) - log.DebugFormat("[CHAT] ChannelID ({0}) was adjusted to {1} | ChatNetworkBlobDispatchType: {2}", channelID, adjustedChannelID, chatBlobDispatchType); + log.LogDebug("[CHAT] ChannelID ({ChannelID}) was adjusted to {AdjustedChannelID} | ChatNetworkBlobDispatchType: {ChatBlobDispatchType}", channelID, adjustedChannelID, chatBlobDispatchType); if (chatType != adjustedchatType) - log.DebugFormat("[CHAT] ChatType ({0}) was adjusted to {1} | ChatNetworkBlobDispatchType: {2}", chatType, adjustedchatType, chatBlobDispatchType); + log.LogDebug("[CHAT] ChatType ({ChatType}) was adjusted to {AdjustedchatType} | ChatNetworkBlobDispatchType: {ChatBlobDispatchType}", chatType, adjustedchatType, chatBlobDispatchType); var gameMessageTurbineChat = new GameMessageTurbineChat(ChatNetworkBlobType.NETBLOB_EVENT_BINARY, ChatNetworkBlobDispatchType.ASYNCMETHOD_SENDTOROOMBYNAME, adjustedChannelID, session.Player.Name, message, senderID, adjustedchatType); @@ -382,7 +382,7 @@ private static void LogTurbineChat(uint channelID, string name, string message, return; } - log.Info($"[CHAT][{chatType}]{(chatType == ChatType.Allegiance ? $"[{channelID}]" : "")} {name} says, \"{message}\""); + log.LogInformation("[CHAT][{ChatType}]{Channel} {Name} says, \"{Message}\"", chatType, (chatType == ChatType.Allegiance ? $"[{channelID}]" : ""), name, message); } } } diff --git a/Source/ACE.Server/Network/Managers/InboundMessageManager.cs b/Source/ACE.Server/Network/Managers/InboundMessageManager.cs index 77013686e1..d0085c0ed1 100644 --- a/Source/ACE.Server/Network/Managers/InboundMessageManager.cs +++ b/Source/ACE.Server/Network/Managers/InboundMessageManager.cs @@ -107,15 +107,15 @@ public static void HandleClientMessage(ClientMessage message, Session session) } catch (Exception ex) { - log.Error($"Received GameMessage packet that threw an exception from account: {session.AccountId}:{session.Account}, player: {session.Player?.Name}, opcode: 0x{((int)opcode):X4}:{opcode}"); - log.Error(ex); + log.LogError("Received GameMessage packet that threw an exception from account: {AccountId}:{Account}, player: {Name}, opcode: 0x{Opcode:X4}:{Opcode2}", session.AccountId, session.Account, session.Player?.Name, ((int)opcode), opcode); + log.LogError(ex, "{Message:l}", ex.Message); } })); } } else { - log.Warn($"Received unhandled fragment opcode: 0x{(int)opcode:X4} - {opcode}"); + log.LogWarning("Received unhandled fragment opcode: 0x{Opcode:X4} - {Opcode2}", (int)opcode, opcode); } } @@ -139,13 +139,13 @@ public static void HandleGameAction(GameActionType opcode, ClientMessage message } catch (Exception ex) { - log.Error($"Received GameAction packet that threw an exception from account: {session.AccountId}:{session.Account}, player: {session.Player?.Name}, opcode: 0x{((int)opcode):X4}:{opcode}"); - log.Error(ex); + log.LogError("Received GameAction packet that threw an exception from account: {AccountId}:{Account}, player: {Name}, opcode: 0x{Opcode:X4}:{Opcode2}", session.AccountId, session.Account, session.Player?.Name, ((int)opcode), opcode); + log.LogError(ex, "{Message:l}", ex.Message); } } else { - log.Warn($"Received unhandled GameActionType: 0x{(int)opcode:X4} - {opcode}"); + log.LogWarning("Received unhandled GameActionType: 0x{Opcode:X4} - {Opcode2}", (int)opcode, opcode); } } } diff --git a/Source/ACE.Server/Network/Managers/NetworkManager.cs b/Source/ACE.Server/Network/Managers/NetworkManager.cs index 6098a74cdc..67fc92b54b 100644 --- a/Source/ACE.Server/Network/Managers/NetworkManager.cs +++ b/Source/ACE.Server/Network/Managers/NetworkManager.cs @@ -50,8 +50,8 @@ public static void ProcessPacket(ConnectionListener connectionListener, ClientPa //ServerPerformanceMonitor.RestartEvent(ServerPerformanceMonitor.MonitorType.ProcessPacket_1); if (packet.Header.Flags.HasFlag(PacketHeaderFlags.ConnectResponse)) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("{0}, {1}", packet, endPoint); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("{Packet}, {EndPoint}", packet, endPoint); PacketInboundConnectResponse connectResponse = new PacketInboundConnectResponse(packet); // This should be set on the second packet to the server from the client. @@ -88,7 +88,7 @@ public static void ProcessPacket(ConnectionListener connectionListener, ClientPa } else { - log.ErrorFormat("Packet from {0} rejected. Packet sent to listener 1 and is not a ConnectResponse or CICMDCommand", endPoint); + log.LogError("Packet from {EndPoint} rejected. Packet sent to listener 1 and is not a ConnectResponse or CICMDCommand", endPoint); } //ServerPerformanceMonitor.RegisterEventEnd(ServerPerformanceMonitor.MonitorType.ProcessPacket_1); } @@ -97,26 +97,26 @@ public static void ProcessPacket(ConnectionListener connectionListener, ClientPa //ServerPerformanceMonitor.RestartEvent(ServerPerformanceMonitor.MonitorType.ProcessPacket_0); if (packet.Header.HasFlag(PacketHeaderFlags.LoginRequest)) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("{0}, {1}", packet, endPoint); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("{Packet}, {EndPoint}", packet, endPoint); if (GetAuthenticatedSessionCount() >= ConfigManager.Config.Server.Network.MaximumAllowedSessions) { - log.InfoFormat("Login Request from {0} rejected. Server full.", endPoint); + log.LogInformation("Login Request from {EndPoint} rejected. Server full.", endPoint); SendLoginRequestReject(connectionListener, endPoint, CharacterError.LogonServerFull); } else if (ServerManager.ShutdownInProgress) { - log.InfoFormat("Login Request from {0} rejected. Server is shutting down.", endPoint); + log.LogInformation("Login Request from {EndPoint} rejected. Server is shutting down.", endPoint); SendLoginRequestReject(connectionListener, endPoint, CharacterError.ServerCrash1); } else if (ServerManager.ShutdownInitiated && (ServerManager.ShutdownTime - DateTime.UtcNow).TotalMinutes < 2) { - log.InfoFormat("Login Request from {0} rejected. Server shutting down in less than 2 minutes.", endPoint); + log.LogInformation("Login Request from {EndPoint} rejected. Server shutting down in less than 2 minutes.", endPoint); SendLoginRequestReject(connectionListener, endPoint, CharacterError.ServerCrash1); } else { - log.DebugFormat("Login Request from {0}", endPoint); + log.LogDebug("Login Request from {EndPoint}", endPoint); var ipAllowsUnlimited = ConfigManager.Config.Server.Network.AllowUnlimitedSessionsFromIPAddresses.Contains(endPoint.Address.ToString()); if (ipAllowsUnlimited || ConfigManager.Config.Server.Network.MaximumAllowedSessionsPerIPAddress == -1 || GetSessionEndpointTotalByAddressCount(endPoint.Address) < ConfigManager.Config.Server.Network.MaximumAllowedSessionsPerIPAddress) @@ -129,20 +129,20 @@ public static void ProcessPacket(ConnectionListener connectionListener, ClientPa // connect request packet sent to the client was corrupted in transit and session entered an unspecified state. // ignore the request and remove the broken session and the client will start a new session. RemoveSession(session); - log.Warn($"Bad handshake from {endPoint}, aborting session."); + log.LogWarning("Bad handshake from {EndPoint}, aborting session.", endPoint); } session.ProcessPacket(packet); } else { - log.InfoFormat("Login Request from {0} rejected. Failed to find or create session.", endPoint); + log.LogInformation("Login Request from {EndPoint} rejected. Failed to find or create session.", endPoint); SendLoginRequestReject(connectionListener, endPoint, CharacterError.LogonServerFull); } } else { - log.InfoFormat("Login Request from {0} rejected. Session would exceed MaximumAllowedSessionsPerIPAddress limit.", endPoint); + log.LogInformation("Login Request from {EndPoint} rejected. Session would exceed MaximumAllowedSessionsPerIPAddress limit.", endPoint); SendLoginRequestReject(connectionListener, endPoint, CharacterError.LogonServerFull); } } @@ -155,16 +155,16 @@ public static void ProcessPacket(ConnectionListener connectionListener, ClientPa if (session.EndPointC2S.Equals(endPoint)) session.ProcessPacket(packet); else - log.DebugFormat("Session for Id {0} has IP {1} but packet has IP {2}", packet.Header.Id, session.EndPointC2S, endPoint); + log.LogDebug("Session for Id {Id} has IP {EndPointC2S} but packet has IP {EndPoint}", packet.Header.Id, session.EndPointC2S, endPoint); } else { - log.DebugFormat("Unsolicited Packet from {0} with Id {1}", endPoint, packet.Header.Id); + log.LogDebug("Unsolicited Packet from {EndPoint} with Id {Id}", endPoint, packet.Header.Id); } } else { - log.DebugFormat("Unsolicited Packet from {0} with Id {1}", endPoint, packet.Header.Id); + log.LogDebug("Unsolicited Packet from {EndPoint} with Id {Id}", endPoint, packet.Header.Id); } //ServerPerformanceMonitor.RegisterEventEnd(ServerPerformanceMonitor.MonitorType.ProcessPacket_0); } @@ -280,7 +280,7 @@ public static Session FindOrCreateSession(ConnectionListener connectionListener, { if (sessionMap[i] == null) { - log.DebugFormat("Creating new session for {0} with id {1}", endPoint, i); + log.LogDebug("Creating new session for {EndPoint} with id {I}", endPoint, i); session = new Session(connectionListener, endPoint, i, ServerId); sessionMap[i] = session; break; @@ -335,7 +335,7 @@ public static void RemoveSession(Session session) sessionLock.EnterWriteLock(); try { - log.DebugFormat("Removing session for {0} with id {1}", session.EndPointC2S, session.Network.ClientId); + log.LogDebug("Removing session for {EndPointC2S} with id {ClientId}", session.EndPointC2S, session.Network.ClientId); if (sessionMap[session.Network.ClientId] == session) sessionMap[session.Network.ClientId] = null; } diff --git a/Source/ACE.Server/Network/Managers/SocketManager.cs b/Source/ACE.Server/Network/Managers/SocketManager.cs index 61e94bd0cc..c9a082ab68 100644 --- a/Source/ACE.Server/Network/Managers/SocketManager.cs +++ b/Source/ACE.Server/Network/Managers/SocketManager.cs @@ -29,8 +29,8 @@ public static void Initialize() } catch (Exception ex) { - log.Error($"Unable to use {ConfigManager.Config.Server.Network.Host} as host due to: {ex}"); - log.Error("Using IPAddress.Any as host instead."); + log.LogError("Unable to use {Host} as host due to: {Ex}", ConfigManager.Config.Server.Network.Host, ex); + log.LogError("Using IPAddress.Any as host instead."); hosts.Clear(); hosts.Add(IPAddress.Any); } @@ -40,10 +40,10 @@ public static void Initialize() for (int i = 0; i < hosts.Count; i++) { listeners[(i * 2) + 0] = new ConnectionListener(hosts[i], ConfigManager.Config.Server.Network.Port); - log.Info($"Binding ConnectionListener to {hosts[i]}:{ConfigManager.Config.Server.Network.Port}"); + log.LogInformation("Binding ConnectionListener to {Hosts}:{Port}", hosts[i], ConfigManager.Config.Server.Network.Port); listeners[(i * 2) + 1] = new ConnectionListener(hosts[i], ConfigManager.Config.Server.Network.Port + 1); - log.Info($"Binding ConnectionListener to {hosts[i]}:{ConfigManager.Config.Server.Network.Port + 1}"); + log.LogInformation("Binding ConnectionListener to {Hosts}:{Port}", hosts[i], ConfigManager.Config.Server.Network.Port + 1); listeners[(i * 2) + 1].Start(); listeners[(i * 2) + 0].Start(); diff --git a/Source/ACE.Server/Network/MessageFragment.cs b/Source/ACE.Server/Network/MessageFragment.cs index 407cb036e6..d1af8446d3 100644 --- a/Source/ACE.Server/Network/MessageFragment.cs +++ b/Source/ACE.Server/Network/MessageFragment.cs @@ -48,8 +48,8 @@ public MessageFragment(GameMessage message, uint sequence) Index = 0; if (Count == 1) TailSent = true; - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("Sequence {0}, count {1}, DataRemaining {2}", sequence, Count, DataRemaining); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("Sequence {Sequence}, count {Count}, DataRemaining {DataRemaining}", sequence, Count, DataRemaining); } public ServerPacketFragment GetTailFragment() @@ -66,8 +66,8 @@ public ServerPacketFragment GetNextFragment() private ServerPacketFragment CreateServerFragment(ushort index) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("Creating ServerFragment for index {0}", index); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("Creating ServerFragment for index {Index}", index); if (index >= Count) throw new ArgumentOutOfRangeException("index", index, "Passed index is greater then computed count"); @@ -100,8 +100,8 @@ private ServerPacketFragment CreateServerFragment(ushort index) fragment.Header.Queue = (ushort)Message.Group; DataRemaining -= dataToSend; - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("Done creating ServerFragment for index {0}. After reading {1} DataRemaining {2}", index, dataToSend, DataRemaining); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("Done creating ServerFragment for index {Index}. After reading {DataToSend} DataRemaining {DataRemaining}", index, dataToSend, DataRemaining); return fragment; } } diff --git a/Source/ACE.Server/Network/Motion/RawMotionState.cs b/Source/ACE.Server/Network/Motion/RawMotionState.cs index 4b97157294..a99ce33118 100644 --- a/Source/ACE.Server/Network/Motion/RawMotionState.cs +++ b/Source/ACE.Server/Network/Motion/RawMotionState.cs @@ -92,7 +92,7 @@ public RawMotionState(MoveToState moveToState, BinaryReader reader) if (SoulEmote.SoulEmotes.Contains(motionItem.MotionCommand) && motionItem.Speed == 1.0f) Commands.Add(motionItem); else - log.Error($"RawMotionState reader - received non-standard action {motionItem.MotionCommand}, Speed: {motionItem.Speed} for {moveToState.WorldObject?.Name}"); + log.LogError("RawMotionState reader - received non-standard action {MotionCommand}, Speed: {Speed} for {Name}", motionItem.MotionCommand, motionItem.Speed, moveToState.WorldObject?.Name); } } } diff --git a/Source/ACE.Server/Network/NetworkSession.cs b/Source/ACE.Server/Network/NetworkSession.cs index eaf7d09949..c402933659 100644 --- a/Source/ACE.Server/Network/NetworkSession.cs +++ b/Source/ACE.Server/Network/NetworkSession.cs @@ -128,8 +128,8 @@ public void EnqueueSend(params GameMessage[] messages) { var currentBundle = currentBundles[(int) grp]; currentBundle.EncryptedChecksum = true; - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Enqueuing Message {1}", session.LoggingIdentifier, message.Opcode); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Enqueuing Message {Opcode}", session.LoggingIdentifier, message.Opcode); currentBundle.Enqueue(message); } } @@ -153,8 +153,8 @@ public void EnqueueSend(IEnumerable messages) { var currentBundle = currentBundles[(int)grp]; currentBundle.EncryptedChecksum = true; - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Enqueuing Message {1}", session.LoggingIdentifier, message.Opcode); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Enqueuing Message {Opcode}", session.LoggingIdentifier, message.Opcode); currentBundle.Enqueue(message); } } @@ -172,8 +172,8 @@ public void EnqueueSend(params ServerPacket[] packets) foreach (var packet in packets) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Enqueuing Packet {1}", session.LoggingIdentifier, packet.GetHashCode()); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Enqueuing Packet {HashCode}", session.LoggingIdentifier, packet.GetHashCode()); packetQueue.Enqueue(packet); } } @@ -205,8 +205,8 @@ public void Update() { if (sendResync && !currentBundle.TimeSync && DateTime.UtcNow > nextResync) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Setting to send TimeSync packet", session.LoggingIdentifier); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Setting to send TimeSync packet", session.LoggingIdentifier); currentBundle.TimeSync = true; currentBundle.EncryptedChecksum = true; nextResync = DateTime.UtcNow.AddMilliseconds(timeBetweenTimeSync); @@ -214,16 +214,16 @@ public void Update() if (sendAck && !currentBundle.SendAck && DateTime.UtcNow > nextAck) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Setting to send ACK packet", session.LoggingIdentifier); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Setting to send ACK packet", session.LoggingIdentifier); currentBundle.SendAck = true; nextAck = DateTime.UtcNow.AddMilliseconds(timeBetweenAck); } if (currentBundle.NeedsSending && DateTime.UtcNow >= nextSend) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Swapping bundle", session.LoggingIdentifier); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Swapping bundle", session.LoggingIdentifier); // Swap out bundle so we can process it bundleToSend = currentBundle; currentBundles[i] = new NetworkBundle(); @@ -233,8 +233,8 @@ public void Update() { if (currentBundle.NeedsSending && DateTime.UtcNow >= nextSend) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Swapping bundle", session.LoggingIdentifier); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Swapping bundle", session.LoggingIdentifier); // Swap out bundle so we can process it bundleToSend = currentBundle; currentBundles[i] = new NetworkBundle(); @@ -278,8 +278,8 @@ public void ProcessPacket(ClientPacket packet) if (isReleased) // Session has been removed return; - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Processing packet {1}", session.LoggingIdentifier, packet.Header.Sequence); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Processing packet {Sequence}", session.LoggingIdentifier, packet.Header.Sequence); NetworkStatistics.C2S_Packets_Aggregate_Increment(); if (!packet.VerifyCRC(ConnectionData.CryptoClient)) @@ -350,7 +350,7 @@ public void ProcessPacket(ClientPacket packet) if (packet.Header.Sequence <= lastReceivedPacketSequence && packet.Header.Sequence != 0 && !(packet.Header.Flags == PacketHeaderFlags.AckSequence && packet.Header.Sequence == lastReceivedPacketSequence)) { - packetLog.WarnFormat("[{0}] Packet {1} received again", session.LoggingIdentifier, packet.Header.Sequence); + packetLog.LogWarning("[{LoggingIdentifier}] Packet {Sequence} received again", session.LoggingIdentifier, packet.Header.Sequence); return; } @@ -359,8 +359,8 @@ public void ProcessPacket(ClientPacket packet) var desiredSeq = lastReceivedPacketSequence + 1; if (packet.Header.Sequence > desiredSeq) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Packet {1} received out of order", session.LoggingIdentifier, packet.Header.Sequence); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Packet {Sequence} received out of order", session.LoggingIdentifier, packet.Header.Sequence); if (!outOfOrderPackets.ContainsKey(packet.Header.Sequence)) outOfOrderPackets.TryAdd(packet.Header.Sequence, packet); @@ -429,8 +429,8 @@ private void DoRequestForRetransmission(uint rcvdSeq) EnqueueSend(reqPacket); LastRequestForRetransmitTime = DateTime.UtcNow; - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Requested retransmit of {1}", session.LoggingIdentifier, needSeq.Select(k => k.ToString()).Aggregate((a, b) => a + ", " + b)); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Requested retransmit of {Aggregate}", session.LoggingIdentifier, needSeq.Select(k => k.ToString()).Aggregate((a, b) => a + ", " + b)); NetworkStatistics.S2C_RequestsForRetransmit_Aggregate_Increment(); } @@ -443,8 +443,8 @@ private void DoRequestForRetransmission(uint rcvdSeq) /// ClientPacket to handle private void HandleOrderedPacket(ClientPacket packet) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Handling packet {1}", session.LoggingIdentifier, packet.Header.Sequence); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Handling packet {Sequence}", session.LoggingIdentifier, packet.Header.Sequence); // If we have an EchoRequest flag, we should flag to respond with an echo response on next send. if (packet.Header.HasFlag(PacketHeaderFlags.EchoRequest)) @@ -459,8 +459,8 @@ private void HandleOrderedPacket(ClientPacket packet) if (packet.Header.HasFlag(PacketHeaderFlags.TimeSync)) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Incoming TimeSync TS: {1}", session.LoggingIdentifier, packet.HeaderOptional.TimeSynch); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Incoming TimeSync TS: {TimeSynch}", session.LoggingIdentifier, packet.HeaderOptional.TimeSynch); // Do something with this... // Based on network traces these are not 1:1. Server seems to send them every 20 seconds per port. // Client seems to send them alternatingly every 2 or 4 seconds per port. @@ -473,8 +473,8 @@ private void HandleOrderedPacket(ClientPacket packet) // In our current implimenation we handle all roles in this one server. if (packet.Header.HasFlag(PacketHeaderFlags.LoginRequest)) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] LoginRequest", session.LoggingIdentifier); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] LoginRequest", session.LoggingIdentifier); AuthenticationHandler.HandleLoginRequest(packet, session); return; } @@ -494,8 +494,8 @@ private void HandleOrderedPacket(ClientPacket packet) /// ClientPacketFragment to process private void ProcessFragment(ClientPacketFragment fragment) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Processing fragment {1}", session.LoggingIdentifier, fragment.Header.Sequence); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Processing fragment {Sequence}", session.LoggingIdentifier, fragment.Header.Sequence); ClientMessage message = null; @@ -503,20 +503,20 @@ private void ProcessFragment(ClientPacketFragment fragment) if (fragment.Header.Count != 1) { // Packet is split - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Fragment {1} is split, this index {2} of {3} fragments", session.LoggingIdentifier, fragment.Header.Sequence, fragment.Header.Index, fragment.Header.Count); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Fragment {Sequence} is split, this index {Index} of {Count} fragments", session.LoggingIdentifier, fragment.Header.Sequence, fragment.Header.Index, fragment.Header.Count); if (partialFragments.TryGetValue(fragment.Header.Sequence, out var buffer)) { // Existing buffer, add this to it and check if we are finally complete. buffer.AddFragment(fragment); - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Added fragment {1} to existing buffer. Buffer at {2} of {3}", session.LoggingIdentifier, fragment.Header.Sequence, buffer.Count, buffer.TotalFragments); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Added fragment {Sequence} to existing buffer. Buffer at {Count} of {TotalFragments}", session.LoggingIdentifier, fragment.Header.Sequence, buffer.Count, buffer.TotalFragments); if (buffer.Complete) { // The buffer is complete, so we can go ahead and handle - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Buffer {1} is complete", session.LoggingIdentifier, buffer.Sequence); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Buffer {Sequence} is complete", session.LoggingIdentifier, buffer.Sequence); message = buffer.TryGetMessage(); MessageBuffer removed = null; partialFragments.TryRemove(fragment.Header.Sequence, out removed); @@ -525,21 +525,21 @@ private void ProcessFragment(ClientPacketFragment fragment) else { // No existing buffer, so add a new one for this fragment sequence. - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Creating new buffer {1} for this split fragment", session.LoggingIdentifier, fragment.Header.Sequence); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Creating new buffer {Sequence} for this split fragment", session.LoggingIdentifier, fragment.Header.Sequence); var newBuffer = new MessageBuffer(fragment.Header.Sequence, fragment.Header.Count); newBuffer.AddFragment(fragment); - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Added fragment {1} to the new buffer. Buffer at {2} of {3}", session.LoggingIdentifier, fragment.Header.Sequence, newBuffer.Count, newBuffer.TotalFragments); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Added fragment {Sequence} to the new buffer. Buffer at {Count} of {TotalFragments}", session.LoggingIdentifier, fragment.Header.Sequence, newBuffer.Count, newBuffer.TotalFragments); partialFragments.TryAdd(fragment.Header.Sequence, newBuffer); } } else { // Packet is not split, proceed with handling it. - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Fragment {1} is not split", session.LoggingIdentifier, fragment.Header.Sequence); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Fragment {Sequence} is not split", session.LoggingIdentifier, fragment.Header.Sequence); if (fragment.Data.Length >= 4) // ClientMessage must be a minimum of 4 bytes in length message = new ClientMessage(fragment.Data); @@ -551,14 +551,14 @@ private void ProcessFragment(ClientPacketFragment fragment) // First check if this message is the next sequence, if it is not, add it to our outOfOrderFragments if (fragment.Header.Sequence == lastReceivedFragmentSequence + 1) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Handling fragment {1}", session.LoggingIdentifier, fragment.Header.Sequence); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Handling fragment {Sequence}", session.LoggingIdentifier, fragment.Header.Sequence); HandleFragment(message); } else { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Fragment {1} is early, lastReceivedFragmentSequence = {2}", session.LoggingIdentifier, fragment.Header.Sequence, lastReceivedFragmentSequence); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Fragment {Sequence} is early, lastReceivedFragmentSequence = {LastReceivedFragmentSequence}", session.LoggingIdentifier, fragment.Header.Sequence, lastReceivedFragmentSequence); outOfOrderFragments.TryAdd(fragment.Header.Sequence, message); } } @@ -581,8 +581,8 @@ private void CheckOutOfOrderPackets() { while (outOfOrderPackets.TryRemove(lastReceivedPacketSequence + 1, out var packet)) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Ready to handle out-of-order packet {1}", session.LoggingIdentifier, packet.Header.Sequence); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Ready to handle out-of-order packet {Sequence}", session.LoggingIdentifier, packet.Header.Sequence); HandleOrderedPacket(packet); } } @@ -594,8 +594,8 @@ private void CheckOutOfOrderFragments() { while (outOfOrderFragments.TryRemove(lastReceivedFragmentSequence + 1, out var message)) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Ready to handle out of order fragment {1}", session.LoggingIdentifier, lastReceivedFragmentSequence + 1); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Ready to handle out of order fragment {ExpectedSequence}", session.LoggingIdentifier, lastReceivedFragmentSequence + 1); HandleFragment(message); } } @@ -638,11 +638,11 @@ private void VerifyEcho(float clientTime) echoDiff++; if (echoDiff >= EchoLogInterval) - log.Warn($"{session.Player.Name} - TimeSync error: {echoDiff} (diff: {diff})"); + log.LogWarning("{Name} - TimeSync error: {EchoDiff} (diff: {Diff})", session.Player.Name, echoDiff, diff); if (echoDiff >= EchoInterval) { - log.Error($"{session.Player.Name} - disconnected for speedhacking"); + log.LogError("{Name} - disconnected for speedhacking", session.Player.Name); var actionChain = new ActionChain(); actionChain.AddAction(session.Player, () => @@ -662,7 +662,7 @@ private void VerifyEcho(float clientTime) else if (echoDiff > 0) { if (echoDiff > EchoLogInterval) - log.Warn($"{session.Player.Name} - Diff: {diff}"); + log.LogWarning("{Name} - Diff: {Diff}", session.Player.Name, diff); lastDiff = 0; echoDiff = 0; @@ -699,8 +699,8 @@ private bool Retransmit(uint sequence) { if (cachedPackets.TryGetValue(sequence, out var cachedPacket)) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Retransmit {1}", session.LoggingIdentifier, sequence); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Retransmit {Sequence}", session.LoggingIdentifier, sequence); if (!cachedPacket.Header.HasFlag(PacketHeaderFlags.Retransmission)) cachedPacket.Header.Flags |= PacketHeaderFlags.Retransmission; @@ -710,22 +710,22 @@ private bool Retransmit(uint sequence) return true; } - if (packetLog.IsDebugEnabled) + if (packetLog.IsEnabled(LogLevel.Debug)) { if (cachedPackets.Count > 0) { // This is to catch a race condition between .Count and .Min() and .Max() try { - packetLog.DebugFormat("Session {0}\\{1} ({2}:{3}) retransmit requested packet {4} not in cache. Cache range {5} - {6}.", session.Network?.ClientId, session.EndPointC2S, session.Account, session.Player?.Name, sequence, cachedPackets.Keys.Min(), cachedPackets.Keys.Max()); + packetLog.LogDebug("Session {ClientId}\\{EndPointC2S} ({Account}:{Name}) retransmit requested packet {Sequence} not in cache. Cache range {Min} - {Max}.", session.Network?.ClientId, session.EndPointC2S, session.Account, session.Player?.Name, sequence, cachedPackets.Keys.Min(), cachedPackets.Keys.Max()); } catch { - packetLog.DebugFormat("Session {0}\\{1} ({2}:{3}) retransmit requested packet {4} not in cache. Cache is empty. Race condition threw exception.", session.Network?.ClientId, session.EndPointC2S, session.Account, session.Player?.Name, sequence); + packetLog.LogDebug("Session {ClientId}\\{EndPointC2S} ({Account}:{Name}) retransmit requested packet {Sequence} not in cache. Cache is empty. Race condition threw exception.", session.Network?.ClientId, session.EndPointC2S, session.Account, session.Player?.Name, sequence); } } else - packetLog.DebugFormat("Session {0}\\{1} ({2}:{3}) retransmit requested packet {4} not in cache. Cache is empty.", session.Network?.ClientId, session.EndPointC2S, session.Account, session.Player?.Name, sequence); + packetLog.LogDebug("Session {ClientId}\\{EndPointC2S} ({Account}:{Name}) retransmit requested packet {Sequence} not in cache. Cache is empty.", session.Network?.ClientId, session.EndPointC2S, session.Account, session.Player?.Name, sequence); } return false; @@ -735,8 +735,8 @@ private void FlushPackets() { while (packetQueue.TryDequeue(out var packet)) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Flushing packets, count {1}", session.LoggingIdentifier, packetQueue.Count); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Flushing packets, count {Count}", session.LoggingIdentifier, packetQueue.Count); if (packet.Header.HasFlag(PacketHeaderFlags.EncryptedChecksum) && ConnectionData.PacketSequence.CurrentValue == 0) ConnectionData.PacketSequence = new Sequence.UIntSequence(1); @@ -761,15 +761,15 @@ private void FlushPackets() private void SendPacket(ServerPacket packet) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Sending packet {1}", session.LoggingIdentifier, packet.GetHashCode()); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Sending packet {HashCode}", session.LoggingIdentifier, packet.GetHashCode()); NetworkStatistics.S2C_Packets_Aggregate_Increment(); if (packet.Header.HasFlag(PacketHeaderFlags.EncryptedChecksum)) { uint issacXor = ConnectionData.IssacServer.Next(); - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Setting Issac for packet {1} to {2}", session.LoggingIdentifier, packet.GetHashCode(), issacXor); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Setting Issac for packet {HashCode} to {IssacXor}", session.LoggingIdentifier, packet.GetHashCode(), issacXor); packet.IssacXor = issacXor; } @@ -788,16 +788,16 @@ private void SendPacketRaw(ServerPacket packet) packet.CreateReadyToSendPacket(buffer, out var size); - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("{0}", packet); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("{Packet}", packet); - if (packetLog.IsDebugEnabled) + if (packetLog.IsEnabled(LogLevel.Debug)) { var listenerEndpoint = (System.Net.IPEndPoint)socket.LocalEndPoint; var sb = new StringBuilder(); sb.AppendLine(String.Format("[{5}] Sending Packet (Len: {0}) [{1}:{2}=>{3}:{4}]", size, listenerEndpoint.Address, listenerEndpoint.Port, endPoint.Address, endPoint.Port, session.Network.ClientId)); sb.AppendLine(buffer.BuildPacketString(0, size)); - packetLog.DebugFormat("{0}", sb); + packetLog.LogDebug("{Sb}", sb); } try @@ -814,7 +814,7 @@ private void SendPacketRaw(ServerPacket packet) var sb = new StringBuilder(); sb.AppendLine(ex.ToString()); sb.AppendLine(String.Format("[{5}] Sending Packet (Len: {0}) [{1}:{2}=>{3}:{4}]", buffer.Length, listenerEndpoint.Address, listenerEndpoint.Port, endPoint.Address, endPoint.Port, session.Network.ClientId)); - log.Error(sb.ToString()); + log.LogError("{Message:l}", sb.ToString()); session.Terminate(SessionTerminationReason.SendToSocketException, null, null, ex.Message); } @@ -833,8 +833,8 @@ private void SendPacketRaw(ServerPacket packet) /// private void SendBundle(NetworkBundle bundle, GameMessageGroup group) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Sending Bundle", session.LoggingIdentifier); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Sending Bundle", session.LoggingIdentifier); bool writeOptionalHeaders = true; @@ -849,8 +849,8 @@ private void SendBundle(NetworkBundle bundle, GameMessageGroup group) fragments.Add(fragment); } - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Bundle Fragment Count: {1}", session.LoggingIdentifier, fragments.Count); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Bundle Fragment Count: {Count}", session.LoggingIdentifier, fragments.Count); // Loop through while we have fragements while (fragments.Count > 0 || writeOptionalHeaders) @@ -873,8 +873,8 @@ private void SendBundle(NetworkBundle bundle, GameMessageGroup group) // If a large message send only this one, filling the whole packet if (firstMessage.DataRemaining >= availableSpace) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Sending large fragment", session.LoggingIdentifier); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Sending large fragment", session.LoggingIdentifier); ServerPacketFragment spf = firstMessage.GetNextFragment(); packet.Fragments.Add(spf); availableSpace -= spf.Length; @@ -902,8 +902,8 @@ private void SendBundle(NetworkBundle bundle, GameMessageGroup group) // Is this a large fragment and does it have a tail that needs sending? if (!fragment.TailSent && availableSpace >= fragment.TailSize) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Sending tail fragment", session.LoggingIdentifier); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Sending tail fragment", session.LoggingIdentifier); ServerPacketFragment spf = fragment.GetTailFragment(); packet.Fragments.Add(spf); availableSpace -= spf.Length; @@ -911,8 +911,8 @@ private void SendBundle(NetworkBundle bundle, GameMessageGroup group) // Otherwise will this message fit in the remaining space? else if (availableSpace >= fragment.NextSize) { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Sending small message", session.LoggingIdentifier); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Sending small message", session.LoggingIdentifier); ServerPacketFragment spf = fragment.GetNextFragment(); packet.Fragments.Add(spf); availableSpace -= spf.Length; @@ -936,8 +936,8 @@ private void SendBundle(NetworkBundle bundle, GameMessageGroup group) // If no messages, write optional headers else { - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] No messages, just sending optional headers", session.LoggingIdentifier); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] No messages, just sending optional headers", session.LoggingIdentifier); if (writeOptionalHeaders) { writeOptionalHeaders = false; @@ -957,8 +957,8 @@ private void WriteOptionalHeaders(NetworkBundle bundle, ServerPacket packet) if (bundle.SendAck) // 0x4000 { packetHeader.Flags |= PacketHeaderFlags.AckSequence; - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Outgoing AckSeq: {1}", session.LoggingIdentifier, lastReceivedPacketSequence); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Outgoing AckSeq: {LastReceivedPacketSequence}", session.LoggingIdentifier, lastReceivedPacketSequence); packet.InitializeDataWriter(); packet.DataWriter.Write(lastReceivedPacketSequence); } @@ -966,8 +966,8 @@ private void WriteOptionalHeaders(NetworkBundle bundle, ServerPacket packet) if (bundle.TimeSync) // 0x1000000 { packetHeader.Flags |= PacketHeaderFlags.TimeSync; - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Outgoing TimeSync TS: {1}", session.LoggingIdentifier, Timers.PortalYearTicks); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Outgoing TimeSync TS: {PortalYearTicks}", session.LoggingIdentifier, Timers.PortalYearTicks); packet.InitializeDataWriter(); packet.DataWriter.Write(Timers.PortalYearTicks); } @@ -975,8 +975,8 @@ private void WriteOptionalHeaders(NetworkBundle bundle, ServerPacket packet) if (bundle.ClientTime != -1f) // 0x4000000 { packetHeader.Flags |= PacketHeaderFlags.EchoResponse; - if (packetLog.IsDebugEnabled) - packetLog.DebugFormat("[{0}] Outgoing EchoResponse: {1}", session.LoggingIdentifier, bundle.ClientTime); + if (packetLog.IsEnabled(LogLevel.Debug)) + packetLog.LogDebug("[{LoggingIdentifier}] Outgoing EchoResponse: {ClientTime}", session.LoggingIdentifier, bundle.ClientTime); packet.InitializeDataWriter(); packet.DataWriter.Write(bundle.ClientTime); packet.DataWriter.Write((float)Timers.PortalYearTicks - bundle.ClientTime); diff --git a/Source/ACE.Server/Network/Session.cs b/Source/ACE.Server/Network/Session.cs index 909f2afed2..7ffadc0143 100644 --- a/Source/ACE.Server/Network/Session.cs +++ b/Source/ACE.Server/Network/Session.cs @@ -172,8 +172,8 @@ public void TickOutbound() } catch (Exception ex) { - log.WarnFormat("Session TickOutbound {0} that threw an exception.", EndPointC2S); - log.Warn(ex); + log.LogWarning("Session TickOutbound {EndPointC2S} that threw an exception.", EndPointC2S); + log.LogWarning(ex, "{Message:l}", ex.Message); } } @@ -312,9 +312,9 @@ public void DropSession() reas = reas + ", " + PendingTermination.ExtraReason; } if (WorldManager.WorldStatus == WorldManager.WorldStatusState.Open) - log.Info($"Session {Network?.ClientId}\\{EndPointC2S} dropped. Account: {Account}, Player: {Player?.Name}{reas}"); + log.LogInformation("Session {ClientId}\\{EndPointC2S} dropped. Account: {Account}, Player: {Name}{Reas}", Network?.ClientId, EndPointC2S, Account, Player?.Name, reas); else - log.DebugFormat("Session {0}\\{1} dropped. Account: {2}, Player: {3}{4}", Network?.ClientId, EndPointC2S, Account, Player?.Name, reas); + log.LogDebug("Session {ClientId}\\{EndPointC2S} dropped. Account: {Account}, Player: {Name}{Reas}", Network?.ClientId, EndPointC2S, Account, Player?.Name, reas); } if (Player != null) diff --git a/Source/ACE.Server/Network/Structure/SquelchDB.cs b/Source/ACE.Server/Network/Structure/SquelchDB.cs index 94c24e1187..a0c6dcf46b 100644 --- a/Source/ACE.Server/Network/Structure/SquelchDB.cs +++ b/Source/ACE.Server/Network/Structure/SquelchDB.cs @@ -55,7 +55,7 @@ public SquelchDB(List squelches, SquelchMask globals var squelchPlayer = PlayerManager.FindByGuid(squelch.SquelchCharacterId); if (squelchPlayer == null && squelch.SquelchAccountId == 0) { - log.Warn($"BuildSquelchDB(): couldn't find character 0x{squelch.SquelchCharacterId:X8}"); + log.LogWarning("BuildSquelchDB(): couldn't find character 0x{SquelchCharacterId:X8}", squelch.SquelchCharacterId); continue; } @@ -77,7 +77,7 @@ public SquelchDB(List squelches, SquelchMask globals if (mostRecentLoggedInCharacterForSquelchedAccount == null) { - log.Warn($"BuildSquelchDB(): couldn't find character 0x{squelch.SquelchCharacterId:X8} and account {squelch.SquelchAccountId} has no other characters"); + log.LogWarning("BuildSquelchDB(): couldn't find character 0x{SquelchCharacterId:X8} and account {SquelchAccountId} has no other characters", squelch.SquelchCharacterId, squelch.SquelchAccountId); continue; } diff --git a/Source/ACE.Server/Physics/Common/WeenieObject.cs b/Source/ACE.Server/Physics/Common/WeenieObject.cs index 9d9a678b08..59bea704bd 100644 --- a/Source/ACE.Server/Physics/Common/WeenieObject.cs +++ b/Source/ACE.Server/Physics/Common/WeenieObject.cs @@ -281,19 +281,19 @@ public bool CanMoveInto(WeenieObject mover) var house = WorldObject as House; if (house == null) { - log.Error($"{WorldObject?.Name} ({WorldObject?.Guid}).CanMoveInto({mover.WorldObject?.Name} ({mover.WorldObject?.Guid}) - couldn't find house"); + log.LogError("{WorldObjectName} ({WorldObjectGuid}).CanMoveInto({WorldObjectName2} ({WorldObjectGuid2}) - couldn't find house", WorldObject?.Name, WorldObject?.Guid, mover.WorldObject?.Name, mover.WorldObject?.Guid); return true; } var rootHouse = house.RootHouse; if (rootHouse == null) { - log.Error($"{WorldObject?.Name} ({WorldObject?.Guid}).CanMoveInto({mover.WorldObject?.Name} ({mover.WorldObject?.Guid}) - couldn't find root house"); + log.LogError("{WorldObjectName} ({WorldObjectGuid}).CanMoveInto({WorldObjectName2} ({WorldObjectGuid2}) - couldn't find root house", WorldObject?.Name, WorldObject?.Guid, mover.WorldObject?.Name, mover.WorldObject?.Guid); return true; } var player = mover?.WorldObject as Player; if (player == null) { - log.Error($"{WorldObject?.Name} ({WorldObject?.Guid}).CanMoveInto({mover.WorldObject?.Name} ({mover.WorldObject?.Guid}) - couldn't find player"); + log.LogError("{WorldObjectName} ({WorldObjectGuid}).CanMoveInto({WorldObjectName2} ({WorldObjectGuid2}) - couldn't find player", WorldObject?.Name, WorldObject?.Guid, mover.WorldObject?.Name, mover.WorldObject?.Guid); return true; } var result = rootHouse.HouseOwner == null || rootHouse.OpenStatus || rootHouse.HasPermission(player); diff --git a/Source/ACE.Server/Physics/PhysicsObj.cs b/Source/ACE.Server/Physics/PhysicsObj.cs index e52301c39b..b36bf65b38 100644 --- a/Source/ACE.Server/Physics/PhysicsObj.cs +++ b/Source/ACE.Server/Physics/PhysicsObj.cs @@ -1323,7 +1323,7 @@ public SetPositionError SetPositionInternal(Position pos, SetPosition setPos, Tr // ideally CellArray.LoadCells = false would be passed to find_cell_list to prevent it from even attempting to load an unloaded neighboring landblock - log.DebugFormat("{0} ({1:X8}) AddPhysicsObj() - {2}) resulted in {3}, discarding", Name, ID, pos.ShortLoc(), transition.SpherePath.CurPos.ShortLoc()); + log.LogDebug("{Name} ({ID:X8}) AddPhysicsObj() - {PosShortLoc}) resulted in {CurPosShortLoc}, discarding", Name, ID, pos.ShortLoc(), transition.SpherePath.CurPos.ShortLoc()); return SetPositionError.NoValidPosition; } @@ -1437,7 +1437,7 @@ public SetPositionError SetScatterPositionInternal(SetPosition setPos, Transitio var groundZ = landblock.GetZ(newPos.Frame.Origin) + 0.05f; if (Math.Abs(newPos.Frame.Origin.Z - groundZ) > ScatterThreshold_Z) - log.DebugFormat("{0} ({1:X8}).SetScatterPositionInternal() - tried to spawn outdoor object @ {2} ground Z {3} (diff: {4}), investigate ScatterThreshold_Z", Name, ID, newPos, groundZ, newPos.Frame.Origin.Z - groundZ); + log.LogDebug("{Name} ({ID:X8}).SetScatterPositionInternal() - tried to spawn outdoor object @ {NewPos} ground Z {GroundZ} (diff: {HeightAboveGround}), investigate ScatterThreshold_Z", Name, ID, newPos, groundZ, newPos.Frame.Origin.Z - groundZ); else newPos.Frame.Origin.Z = groundZ; @@ -1685,7 +1685,7 @@ public void UpdateObjectInternal(double quantum) if (GetBlockDist(Position, newPos) > 1) { - log.Warn($"WARNING: failed transition for {Name} from {Position} to {newPos}"); + log.LogWarning("WARNING: failed transition for {Name} from {Position} to {NewPos}", Name, Position, newPos); return; } @@ -1702,9 +1702,9 @@ public void UpdateObjectInternal(double quantum) else { if (IsPlayer) - log.DebugFormat("{0} ({1:X8}).UpdateObjectInternal({2}) - failed transition from {3} to {4}", Name, ID, quantum, Position, newPos); + log.LogDebug("{Name} ({ID:X8}).UpdateObjectInternal({Quantum}) - failed transition from {Position} to {NewPos}", Name, ID, quantum, Position, newPos); else if (transit != null && transit.SpherePath.CurCell == null) - log.Warn($"{Name} ({ID:X8}).UpdateObjectInternal({quantum}) - avoided CurCell=null from {Position} to {newPos}"); + log.LogWarning("{Name} ({ID:X8}).UpdateObjectInternal({Quantum}) - avoided CurCell=null from {Position} to {NewPos}", Name, ID, quantum, Position, newPos); newPos.Frame.Origin = Position.Frame.Origin; set_initial_frame(newPos.Frame); @@ -1770,7 +1770,7 @@ public bool UpdateObjectInternalServer(double quantum) //UpdatePhysicsInternal((float)quantum, ref offsetFrame); if (GetBlockDist(Position, RequestPos) > 1) { - log.Warn($"WARNING: failed transition for {Name} from {Position} to {RequestPos}"); + log.LogWarning("WARNING: failed transition for {Name} from {Position} to {RequestPos}", Name, Position, RequestPos); return false; } @@ -1783,7 +1783,7 @@ public bool UpdateObjectInternalServer(double quantum) SetPositionInternal(transit); } else - log.DebugFormat("{0}.UpdateObjectInternalServer({1}) - failed transition from {2} to {3}", Name, quantum, Position, RequestPos); + log.LogDebug("{Name}.UpdateObjectInternalServer({Quantum}) - failed transition from {Position} to {RequestPos}", Name, quantum, Position, RequestPos); if (DetectionManager != null) DetectionManager.CheckDetection(); @@ -2804,9 +2804,9 @@ public bool handle_visible_obj(PhysicsObj obj) if (CurCell == null || obj.CurCell == null) { if (CurCell == null) - log.Warn($"{Name}.handle_visible_obj({obj.Name}): CurCell null"); + log.LogWarning("{Name}.handle_visible_obj({ObjName}): CurCell null", Name, obj.Name); else - log.Warn($"{Name}.handle_visible_obj({obj.Name}): obj.CurCell null"); + log.LogWarning("{Name}.handle_visible_obj({ObjName}): obj.CurCell null", Name, obj.Name); return false; } @@ -4323,7 +4323,7 @@ public bool update_object_server_new(bool forcePos = true) { if (GetBlockDist(Position, RequestPos) > 1) { - log.Warn($"WARNING: failed transition for {Name} from {Position} to {RequestPos}"); + log.LogWarning("WARNING: failed transition for {Name} from {Position} to {RequestPos}", Name, Position, RequestPos); success = false; } diff --git a/Source/ACE.Server/Program.cs b/Source/ACE.Server/Program.cs index 661784e33e..39a034f1ab 100644 --- a/Source/ACE.Server/Program.cs +++ b/Source/ACE.Server/Program.cs @@ -115,7 +115,7 @@ public static void Main(string[] args) LogManager.Factory.AddProvider(new Log4NetBridgeProvider(logRepository)); if (Environment.ProcessorCount < 2) - log.Warn("Only one vCPU was detected. ACE may run with limited performance. You should increase your vCPU count for anything more than a single player server."); + log.LogWarning("Only one vCPU was detected. ACE may run with limited performance. You should increase your vCPU count for anything more than a single player server."); // Do system specific initializations here try @@ -128,13 +128,13 @@ public static void Main(string[] args) } catch (Exception ex) { - log.Error(ex.ToString()); + log.LogError("{Message:l}", ex.ToString()); } - log.Info("Starting ACEmulator..."); + log.LogInformation("Starting ACEmulator..."); if (IsRunningInContainer) - log.Info("ACEmulator is running in a container..."); + log.LogInformation("ACEmulator is running in a container..."); var configFile = Path.Combine(exeLocation, "Config.js"); var configConfigContainer = Path.Combine(containerConfigDirectory, "Config.js"); @@ -158,10 +158,10 @@ public static void Main(string[] args) } } - log.Info("Initializing ConfigManager..."); + log.LogInformation("Initializing ConfigManager..."); ConfigManager.Initialize(); - log.Info("Initializing ModManager..."); + log.LogInformation("Initializing ModManager..."); ModManager.Initialize(); if (ConfigManager.Config.Server.WorldName != "ACEmulator") @@ -172,43 +172,43 @@ public static void Main(string[] args) if (ConfigManager.Config.Offline.PurgeDeletedCharacters) { - log.Info($"Purging deleted characters, and their possessions, older than {ConfigManager.Config.Offline.PurgeDeletedCharactersDays} days ({DateTime.Now.AddDays(-ConfigManager.Config.Offline.PurgeDeletedCharactersDays).ToCommonString()})..."); + log.LogInformation("Purging deleted characters, and their possessions, older than {PurgeDeletedCharactersDays} days ({AddDays})...", ConfigManager.Config.Offline.PurgeDeletedCharactersDays, DateTime.Now.AddDays(-ConfigManager.Config.Offline.PurgeDeletedCharactersDays).ToCommonString()); ShardDatabaseOfflineTools.PurgeCharactersInParallel(ConfigManager.Config.Offline.PurgeDeletedCharactersDays, out var charactersPurged, out var playerBiotasPurged, out var possessionsPurged); - log.Info($"Purged {charactersPurged:N0} characters, {playerBiotasPurged:N0} player biotas and {possessionsPurged:N0} possessions."); + log.LogInformation("Purged {CharactersPurged:N0} characters, {PlayerBiotasPurged:N0} player biotas and {PossessionsPurged:N0} possessions.", charactersPurged, playerBiotasPurged, possessionsPurged); } if (ConfigManager.Config.Offline.PurgeOrphanedBiotas) { - log.Info($"Purging orphaned biotas..."); + log.LogInformation("Purging orphaned biotas..."); ShardDatabaseOfflineTools.PurgeOrphanedBiotasInParallel(out var numberOfBiotasPurged); - log.Info($"Purged {numberOfBiotasPurged:N0} biotas."); + log.LogInformation("Purged {NumberOfBiotasPurged:N0} biotas.", numberOfBiotasPurged); } if (ConfigManager.Config.Offline.PruneDeletedCharactersFromFriendLists) { - log.Info($"Pruning invalid friends from all friend lists..."); + log.LogInformation("Pruning invalid friends from all friend lists..."); ShardDatabaseOfflineTools.PruneDeletedCharactersFromFriendLists(out var numberOfFriendsPruned); - log.Info($"Pruned {numberOfFriendsPruned:N0} invalid friends found on friend lists."); + log.LogInformation("Pruned {NumberOfFriendsPruned:N0} invalid friends found on friend lists.", numberOfFriendsPruned); } if (ConfigManager.Config.Offline.PruneDeletedObjectsFromShortcutBars) { - log.Info($"Pruning invalid shortcuts from all shortcut bars..."); + log.LogInformation("Pruning invalid shortcuts from all shortcut bars..."); ShardDatabaseOfflineTools.PruneDeletedObjectsFromShortcutBars(out var numberOfShortcutsPruned); - log.Info($"Pruned {numberOfShortcutsPruned:N0} deleted objects found on shortcut bars."); + log.LogInformation("Pruned {NumberOfShortcutsPruned:N0} deleted objects found on shortcut bars.", numberOfShortcutsPruned); } if (ConfigManager.Config.Offline.PruneDeletedCharactersFromSquelchLists) { - log.Info($"Pruning invalid squelches from all squelch lists..."); + log.LogInformation("Pruning invalid squelches from all squelch lists..."); ShardDatabaseOfflineTools.PruneDeletedCharactersFromSquelchLists(out var numberOfSquelchesPruned); - log.Info($"Pruned {numberOfSquelchesPruned:N0} invalid squelched characters found on squelch lists."); + log.LogInformation("Pruned {NumberOfSquelchesPruned:N0} invalid squelched characters found on squelch lists.", numberOfSquelchesPruned); } if (ConfigManager.Config.Offline.AutoServerUpdateCheck) CheckForServerUpdate(); else - log.Info($"AutoServerVersionCheck is disabled..."); + log.LogInformation("AutoServerVersionCheck is disabled..."); if (ConfigManager.Config.Offline.AutoUpdateWorldDatabase) { @@ -218,12 +218,12 @@ public static void Main(string[] args) AutoApplyWorldCustomizations(); } else - log.Info($"AutoUpdateWorldDatabase is disabled..."); + log.LogInformation("AutoUpdateWorldDatabase is disabled..."); if (ConfigManager.Config.Offline.AutoApplyDatabaseUpdates) AutoApplyDatabaseUpdates(); else - log.Info($"AutoApplyDatabaseUpdates is disabled..."); + log.LogInformation("AutoApplyDatabaseUpdates is disabled..."); // This should only be enabled manually. To enable it, simply uncomment this line //ACE.Database.OfflineTools.Shard.BiotaGuidConsolidator.ConsolidateBiotaGuids(0xA0000000, true, false, out int numberOfBiotasConsolidated, out int numberOfBiotasSkipped, out int numberOfErrors); @@ -234,98 +234,98 @@ public static void Main(string[] args) // pre-load starterGear.json, abort startup if file is not found as it is required to create new characters. if (Factories.StarterGearFactory.GetStarterGearConfiguration() == null) { - log.Fatal("Unable to load or parse starterGear.json. ACEmulator will now abort startup."); + log.LogCritical("Unable to load or parse starterGear.json. ACEmulator will now abort startup."); ServerManager.StartupAbort(); Environment.Exit(0); } - log.Info("Initializing ServerManager..."); + log.LogInformation("Initializing ServerManager..."); ServerManager.Initialize(); - log.Info("Initializing DatManager..."); + log.LogInformation("Initializing DatManager..."); DatManager.Initialize(ConfigManager.Config.Server.DatFilesDirectory, true); if (ConfigManager.Config.DDD.EnableDATPatching) { - log.Info("Initializing DDDManager..."); + log.LogInformation("Initializing DDDManager..."); DDDManager.Initialize(); } else - log.Info("DAT Patching Disabled..."); + log.LogInformation("DAT Patching Disabled..."); - log.Info("Initializing DatabaseManager..."); + log.LogInformation("Initializing DatabaseManager..."); DatabaseManager.Initialize(); if (DatabaseManager.InitializationFailure) { - log.Fatal("DatabaseManager initialization failed. ACEmulator will now abort startup."); + log.LogCritical("DatabaseManager initialization failed. ACEmulator will now abort startup."); ServerManager.StartupAbort(); Environment.Exit(0); } - log.Info("Starting DatabaseManager..."); + log.LogInformation("Starting DatabaseManager..."); DatabaseManager.Start(); - log.Info("Starting PropertyManager..."); + log.LogInformation("Starting PropertyManager..."); PropertyManager.Initialize(); - log.Info("Initializing GuidManager..."); + log.LogInformation("Initializing GuidManager..."); GuidManager.Initialize(); if (ConfigManager.Config.Server.ServerPerformanceMonitorAutoStart) { - log.Info("Server Performance Monitor auto starting..."); + log.LogInformation("Server Performance Monitor auto starting..."); ServerPerformanceMonitor.Start(); } if (ConfigManager.Config.Server.WorldDatabasePrecaching) { - log.Info("Precaching Weenies..."); + log.LogInformation("Precaching Weenies..."); DatabaseManager.World.CacheAllWeenies(); - log.Info("Precaching Cookbooks..."); + log.LogInformation("Precaching Cookbooks..."); DatabaseManager.World.CacheAllCookbooks(); - log.Info("Precaching Events..."); + log.LogInformation("Precaching Events..."); DatabaseManager.World.GetAllEvents(); - log.Info("Precaching House Portals..."); + log.LogInformation("Precaching House Portals..."); DatabaseManager.World.CacheAllHousePortals(); - log.Info("Precaching Points Of Interest..."); + log.LogInformation("Precaching Points Of Interest..."); DatabaseManager.World.CacheAllPointsOfInterest(); - log.Info("Precaching Spells..."); + log.LogInformation("Precaching Spells..."); DatabaseManager.World.CacheAllSpells(); - log.Info("Precaching Treasures - Death..."); + log.LogInformation("Precaching Treasures - Death..."); DatabaseManager.World.CacheAllTreasuresDeath(); - log.Info("Precaching Treasures - Material Base..."); + log.LogInformation("Precaching Treasures - Material Base..."); DatabaseManager.World.CacheAllTreasureMaterialBase(); - log.Info("Precaching Treasures - Material Groups..."); + log.LogInformation("Precaching Treasures - Material Groups..."); DatabaseManager.World.CacheAllTreasureMaterialGroups(); - log.Info("Precaching Treasures - Material Colors..."); + log.LogInformation("Precaching Treasures - Material Colors..."); DatabaseManager.World.CacheAllTreasureMaterialColor(); - log.Info("Precaching Treasures - Wielded..."); + log.LogInformation("Precaching Treasures - Wielded..."); DatabaseManager.World.CacheAllTreasureWielded(); } else - log.Info("Precaching World Database Disabled..."); + log.LogInformation("Precaching World Database Disabled..."); - log.Info("Initializing PlayerManager..."); + log.LogInformation("Initializing PlayerManager..."); PlayerManager.Initialize(); - log.Info("Initializing HouseManager..."); + log.LogInformation("Initializing HouseManager..."); HouseManager.Initialize(); - log.Info("Initializing InboundMessageManager..."); + log.LogInformation("Initializing InboundMessageManager..."); InboundMessageManager.Initialize(); - log.Info("Initializing SocketManager..."); + log.LogInformation("Initializing SocketManager..."); SocketManager.Initialize(); - log.Info("Initializing WorldManager..."); + log.LogInformation("Initializing WorldManager..."); WorldManager.Initialize(); - log.Info("Initializing EventManager..."); + log.LogInformation("Initializing EventManager..."); EventManager.Initialize(); // Free up memory before the server goes online. This can free up 6 GB+ on larger servers. - log.Info("Forcing .net garbage collection..."); + log.LogInformation("Forcing .net garbage collection..."); for (int i = 0; i < 10; i++) { // https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals @@ -336,11 +336,11 @@ public static void Main(string[] args) } // This should be last - log.Info("Initializing CommandManager..."); + log.LogInformation("Initializing CommandManager..."); CommandManager.Initialize(); //Register mod commands - log.Info("Registering ModManager commands..."); + log.LogInformation("Registering ModManager commands..."); ModManager.RegisterCommands(); ModManager.ListMods(); @@ -352,7 +352,8 @@ public static void Main(string[] args) private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { - log.Error(e.ExceptionObject); + var exception = e.ExceptionObject as Exception; + log.LogError(exception, "{Message:l}", exception?.Message ?? e.ExceptionObject); } private static void OnProcessExit(object sender, EventArgs e) @@ -360,7 +361,7 @@ private static void OnProcessExit(object sender, EventArgs e) if (!IsRunningInContainer) { if (!ServerManager.ShutdownInitiated) - log.Warn("Unsafe server shutdown detected! Data loss is possible!"); + log.LogWarning("Unsafe server shutdown detected! Data loss is possible!"); PropertyManager.StopUpdating(); DatabaseManager.Stop(); @@ -375,7 +376,7 @@ private static void OnProcessExit(object sender, EventArgs e) } catch (Exception ex) { - log.Error(ex.ToString()); + log.LogError("{Message:l}", ex.ToString()); } } else diff --git a/Source/ACE.Server/Program_BinUpdates.cs b/Source/ACE.Server/Program_BinUpdates.cs index 0a93958187..90ef063017 100644 --- a/Source/ACE.Server/Program_BinUpdates.cs +++ b/Source/ACE.Server/Program_BinUpdates.cs @@ -1,7 +1,7 @@ using System; using System.Text.Json; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; namespace ACE.Server { @@ -9,12 +9,12 @@ partial class Program { private static void CheckForServerUpdate() { - log.Info($"Automatic Server version check started..."); + log.LogInformation("Automatic Server version check started..."); try { var worldDb = new Database.WorldDatabase(); var currentVersion = worldDb.GetVersion(); - log.Info($"Current Server Binary: {ServerBuildInfo.FullVersion}"); + log.LogInformation("Current Server Binary: {FullVersion}", ServerBuildInfo.FullVersion); var url = "https://api.github.com/repos/ACEmulator/ACE/releases/latest"; using var client = new WebClient(); @@ -32,8 +32,8 @@ private static void CheckForServerUpdate() // Status returns > 0 if the GitHub version is newer. (0 if the same, or < 0 if older.) if (versionStatus > 0) { - log.Warn("There is a newer version of ACE available!"); - log.Warn($"Please visit {json.GetProperty("html_url").GetString()} for more information."); + log.LogWarning("There is a newer version of ACE available!"); + log.LogWarning("Please visit {String} for more information.", json.GetProperty("html_url").GetString()); // the Console.Title.Get() only works on Windows... #pragma warning disable CA1416 // Validate platform compatibility @@ -42,13 +42,13 @@ private static void CheckForServerUpdate() } else { - log.Info($"Latest Server Version is {tag} -- No Update Required!"); + log.LogInformation("Latest Server Version is {Tag} -- No Update Required!", tag); } return; } catch (Exception ex) { - log.Info($"Unable to continue with Automatic Server Version Check due to the following error: {ex}"); + log.LogInformation("Unable to continue with Automatic Server Version Check due to the following error: {Ex}", ex); } } } diff --git a/Source/ACE.Server/Program_DbUpdates.cs b/Source/ACE.Server/Program_DbUpdates.cs index a80e36b943..634c3f0d2d 100644 --- a/Source/ACE.Server/Program_DbUpdates.cs +++ b/Source/ACE.Server/Program_DbUpdates.cs @@ -6,8 +6,9 @@ using System.Text.Json; using System.Threading; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; namespace ACE.Server { @@ -15,12 +16,12 @@ partial class Program { private static void CheckForWorldDatabaseUpdate() { - log.Info($"Automatic World Database Update started..."); + log.LogInformation("Automatic World Database Update started..."); try { var worldDb = new Database.WorldDatabase(); var currentVersion = worldDb.GetVersion(); - log.Info($"Current World Database version: Base - {currentVersion.BaseVersion} | Patch - {currentVersion.PatchVersion}"); + log.LogInformation("Current World Database version: Base - {BaseVersion} | Patch - {PatchVersion}", currentVersion.BaseVersion, currentVersion.PatchVersion); var url = "https://api.github.com/repos/ACEmulator/ACE-World-16PY-Patches/releases/latest"; @@ -46,26 +47,26 @@ private static void CheckForWorldDatabaseUpdate() if (tagMajor > patchMajor || tagMinor > patchMinor || (tagBuild > patchBuild && patchBuild != 0)) { - log.Info($"Latest patch version is {tag} -- Update Required!"); + log.LogInformation("Latest patch version is {Tag} -- Update Required!", tag); UpdateToLatestWorldDatabase(dbURL, dbFileName); var newVersion = worldDb.GetVersion(); - log.Info($"Updated World Database version: Base - {newVersion.BaseVersion} | Patch - {newVersion.PatchVersion}"); + log.LogInformation("Updated World Database version: Base - {BaseVersion} | Patch - {PatchVersion}", newVersion.BaseVersion, newVersion.PatchVersion); } else { - log.Info($"Latest patch version is {tag} -- No Update Required!"); + log.LogInformation("Latest patch version is {Tag} -- No Update Required!", tag); } } else { - log.Info($"Latest patch version is {tag} -- No Update Required!"); + log.LogInformation("Latest patch version is {Tag} -- No Update Required!", tag); } } catch (Exception ex) { - log.Info($"Unable to continue with Automatic World Database Update due to the following error: {ex}"); + log.LogInformation("Unable to continue with Automatic World Database Update due to the following error: {Ex}", ex); } - log.Info($"Automatic World Database Update complete."); + log.LogInformation("Automatic World Database Update complete."); } private static void UpdateToLatestWorldDatabase(string dbURL, string dbFileName) @@ -223,7 +224,7 @@ private static void AutoApplyWorldCustomizations() private static void AutoApplyDatabaseUpdates() { - log.Info($"Automatic Database Patching started..."); + log.LogInformation("Automatic Database Patching started..."); Thread.Sleep(1000); PatchDatabase("Authentication", ConfigManager.Config.MySql.Authentication.Host, ConfigManager.Config.MySql.Authentication.Port, ConfigManager.Config.MySql.Authentication.Username, ConfigManager.Config.MySql.Authentication.Password, ConfigManager.Config.MySql.Authentication.Database, ConfigManager.Config.MySql.Shard.Database, ConfigManager.Config.MySql.World.Database); @@ -231,7 +232,7 @@ private static void AutoApplyDatabaseUpdates() PatchDatabase("World", ConfigManager.Config.MySql.World.Host, ConfigManager.Config.MySql.World.Port, ConfigManager.Config.MySql.World.Username, ConfigManager.Config.MySql.World.Password, ConfigManager.Config.MySql.Authentication.Database, ConfigManager.Config.MySql.Shard.Database, ConfigManager.Config.MySql.World.Database); Thread.Sleep(1000); - log.Info($"Automatic Database Patching complete."); + log.LogInformation("Automatic Database Patching complete."); } private static void PatchDatabase(string dbType, string host, uint port, string username, string password, string authDB, string shardDB, string worldDB) diff --git a/Source/ACE.Server/WorldObjects/Container.cs b/Source/ACE.Server/WorldObjects/Container.cs index ed834d5197..8a61232163 100644 --- a/Source/ACE.Server/WorldObjects/Container.cs +++ b/Source/ACE.Server/WorldObjects/Container.cs @@ -146,7 +146,7 @@ protected void SortBiotasIntoInventory(IEnumerable 0) - log.Error("Inventory detected without a container to put it in to."); + log.LogError("Inventory detected without a container to put it in to."); } /// diff --git a/Source/ACE.Server/WorldObjects/Corpse.cs b/Source/ACE.Server/WorldObjects/Corpse.cs index c3e9219902..57f2e57bcb 100644 --- a/Source/ACE.Server/WorldObjects/Corpse.cs +++ b/Source/ACE.Server/WorldObjects/Corpse.cs @@ -71,7 +71,7 @@ protected override void OnInitialInventoryLoadCompleted() var dtTimeToRot = DateTime.UtcNow.AddSeconds(TimeToRot ?? 0); var tsDecay = dtTimeToRot - DateTime.UtcNow; - log.Info($"[CORPSE] {Name} (0x{Guid}) Reloaded from Database: Corpse Level: {Level ?? 0} | InventoryLoaded: {InventoryLoaded} | Inventory.Count: {Inventory.Count} | TimeToRot: {TimeToRot} | CreationTimestamp: {CreationTimestamp} ({Time.GetDateTimeFromTimestamp(CreationTimestamp ?? 0).ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")}) | Corpse should not decay before: {dtTimeToRot.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")}, {tsDecay.ToString("%d")} day(s), {tsDecay.ToString("%h")} hours, {tsDecay.ToString("%m")} minutes, and {tsDecay.ToString("%s")} seconds from now."); + log.LogInformation("[CORPSE] {Name} (0x{Guid}) Reloaded from Database: Corpse Level: {Level} | InventoryLoaded: {InventoryLoaded} | Inventory.Count: {Count} | TimeToRot: {TimeToRot} | CreationTimestamp: {CreationTimestamp} ({DateTimeFromTimestamp:yyyy-MM-dd HH:mm:ss}) | Corpse should not decay before: {DtTimeToRot:yyyy-MM-dd HH:mm:ss}, {TsDecay:%d} day(s), {TsDecay:%h} hours, {TsDecay:%m} minutes, and {TsDecay:%s} seconds from now.", Name, Guid, Level ?? 0, InventoryLoaded, Inventory.Count, TimeToRot, CreationTimestamp, Time.GetDateTimeFromTimestamp(CreationTimestamp ?? 0).ToLocalTime(), dtTimeToRot.ToLocalTime(), tsDecay, tsDecay, tsDecay, tsDecay); } } @@ -115,7 +115,7 @@ public void RecalculateDecayTime(Player player) Level = player.Level ?? 1; - log.Info($"[CORPSE] {Name}.RecalculateDecayTime({player.Name}) 0x{Guid}: Player Level: {player.Level} | Inventory.Count: {Inventory.Count} | TimeToRot: {TimeToRot} | CreationTimestamp: {CreationTimestamp} ({Time.GetDateTimeFromTimestamp(CreationTimestamp ?? 0).ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")}) | Corpse should not decay before: {dtTimeToRot.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")}, {tsDecay.ToString("%d")} day(s), {tsDecay.ToString("%h")} hours, {tsDecay.ToString("%m")} minutes, and {tsDecay.ToString("%s")} seconds from now."); + log.LogInformation("[CORPSE] {Name}.RecalculateDecayTime({PlayerName}) 0x{Guid}: Player Level: {Level} | Inventory.Count: {Count} | TimeToRot: {TimeToRot} | CreationTimestamp: {CreationTimestamp} ({DateTimeFromTimestamp:yyyy-MM-dd HH:mm:ss}) | Corpse should not decay before: {DtTimeToRot:yyyy-MM-dd HH:mm:ss}, {TsDecay:%d} day(s), {TsDecay:%h} hours, {TsDecay:%m} minutes, and {TsDecay:%s} seconds from now.", Name, player.Name, Guid, player.Level, Inventory.Count, TimeToRot, CreationTimestamp, Time.GetDateTimeFromTimestamp(CreationTimestamp ?? 0).ToLocalTime(), dtTimeToRot.ToLocalTime(), tsDecay, tsDecay, tsDecay, tsDecay); } /// @@ -249,7 +249,7 @@ public override bool EnterWorld() var success = base.EnterWorld(); if (!success) { - log.Error($"{Name} ({Guid}) failed to spawn @ {Location?.ToLOCString()}"); + log.LogError("{Name} ({Guid}) failed to spawn @ {Location}", Name, Guid, Location?.ToLOCString()); return false; } @@ -345,8 +345,8 @@ public void TryGenerateRare(DamageHistoryInfo killer) var tier = LootGenerationFactory.GetRareTier(wo.WeenieClassId); LootGenerationFactory.RareChances.TryGetValue(tier, out var chance); - log.Info($"[LOOT][RARE] {Name} ({Guid}) generated rare {wo.Name} ({wo.Guid}) for {killer.Name} ({killer.Guid})"); - log.Info($"[LOOT][RARE] Tier {tier} -- 1 / {chance:N0} chance -- {luck:N0} luck"); + log.LogInformation("[LOOT][RARE] {Name} ({Guid}) generated rare {WoName} ({WoGuid}) for {KillerName} ({KillerGuid})", Name, Guid, wo.Name, wo.Guid, killer.Name, killer.Guid); + log.LogInformation("[LOOT][RARE] Tier {Tier} -- 1 / {Chance:N0} chance -- {Luck:N0} luck", tier, chance, luck); if (TryAddToInventory(wo)) { @@ -396,7 +396,7 @@ public void TryGenerateRare(DamageHistoryInfo killer) } } else - log.Error($"[RARE] failed to add to corpse inventory"); + log.LogError("[RARE] failed to add to corpse inventory"); } /// diff --git a/Source/ACE.Server/WorldObjects/Creature.cs b/Source/ACE.Server/WorldObjects/Creature.cs index 0b1efbcd47..1af0b116ca 100644 --- a/Source/ACE.Server/WorldObjects/Creature.cs +++ b/Source/ACE.Server/WorldObjects/Creature.cs @@ -174,7 +174,7 @@ public void GenerateNewFace() if (!cg.HeritageGroups.TryGetValue((uint)Heritage, out var heritageGroup) || !heritageGroup.Genders.TryGetValue((int)Gender, out var sex)) { #if DEBUG - log.DebugFormat("Creature.GenerateNewFace: {0} (0x{1}) - wcid {2} - Heritage: {3} | HeritageGroupName: {4} | Gender: {5} | Sex: {6} - Data invalid, Cannot randomize face.", Name, Guid, WeenieClassId, Heritage, HeritageGroupName, Gender, Sex); + log.LogDebug("Creature.GenerateNewFace: {Name} (0x{Guid}) - wcid {WeenieClassId} - Heritage: {Heritage} | HeritageGroupName: {HeritageGroupName} | Gender: {Gender} | Sex: {Sex} - Data invalid, Cannot randomize face.", Name, Guid, WeenieClassId, Heritage, HeritageGroupName, Gender, Sex); #endif return; } @@ -209,7 +209,7 @@ public void GenerateNewFace() if (sex.HairStyleList.Count < appearance.HairStyle) { - log.Warn($"Creature.GenerateNewFace: {Name} (0x{Guid}) - wcid {WeenieClassId} - HairStyle = {appearance.HairStyle} | HairStyleList.Count = {sex.HairStyleList.Count} - Data invalid, Cannot randomize face."); + log.LogWarning("Creature.GenerateNewFace: {Name} (0x{Guid}) - wcid {WeenieClassId} - HairStyle = {HairStyle} | HairStyleList.Count = {Count} - Data invalid, Cannot randomize face.", Name, Guid, WeenieClassId, appearance.HairStyle, sex.HairStyleList.Count); return; } diff --git a/Source/ACE.Server/WorldObjects/Creature_Combat.cs b/Source/ACE.Server/WorldObjects/Creature_Combat.cs index b468b0da33..21c2d26bde 100644 --- a/Source/ACE.Server/WorldObjects/Creature_Combat.cs +++ b/Source/ACE.Server/WorldObjects/Creature_Combat.cs @@ -1,8 +1,9 @@ using System; using System.Linq; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.Entity; using ACE.Entity.Enum; using ACE.Entity.Enum.Properties; @@ -94,7 +95,7 @@ public float SetCombatMode(CombatMode combatMode, out float queueTime, bool forc animLength = HandleSwitchToMissileCombatMode(); break; default: - log.InfoFormat("Unknown combat mode {0} for {1}", CombatMode, Name); + log.LogInformation("Unknown combat mode {CombatMode} for {Name}", CombatMode, Name); break; } diff --git a/Source/ACE.Server/WorldObjects/Creature_Death.cs b/Source/ACE.Server/WorldObjects/Creature_Death.cs index 0e6831633c..0170ee0b85 100644 --- a/Source/ACE.Server/WorldObjects/Creature_Death.cs +++ b/Source/ACE.Server/WorldObjects/Creature_Death.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using System.Linq; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Database; using ACE.Database.Models.World; using ACE.Entity; @@ -621,9 +622,9 @@ protected void CreateCorpse(DamageHistoryInfo killer, bool hadVitae = false) if (player != null) { if (corpse.PhysicsObj == null || corpse.PhysicsObj.Position == null) - log.InfoFormat("[CORPSE] {0}'s corpse (0x{1}) failed to spawn! Tried at {2}", Name, corpse.Guid, player.Location.ToLOCString()); + log.LogInformation("[CORPSE] {Name}'s corpse (0x{Guid}) failed to spawn! Tried at {Location}", Name, corpse.Guid, player.Location.ToLOCString()); else - log.InfoFormat("[CORPSE] {0}'s corpse (0x{1}) is located at {2}", Name, corpse.Guid, corpse.PhysicsObj.Position); + log.LogInformation("[CORPSE] {Name}'s corpse (0x{Guid}) is located at {Position}", Name, corpse.Guid, corpse.PhysicsObj.Position); } if (saveCorpse) @@ -730,11 +731,11 @@ public void DoCantripLogging(DamageHistoryInfo killer, WorldObject wo) var epicCantrips = wo.EpicCantrips; var legendaryCantrips = wo.LegendaryCantrips; - if (epicCantrips.Count > 0 && log.IsDebugEnabled) - log.Debug($"[LOOT][EPIC] {Name} ({Guid}) generated item with {epicCantrips.Count} epic{(epicCantrips.Count > 1 ? "s" : "")} - {wo.Name} ({wo.Guid}) - {GetSpellList(epicCantrips)} - killed by {killer?.Name} ({killer?.Guid})"); + if (epicCantrips.Count > 0 && log.IsEnabled(LogLevel.Debug)) + log.LogDebug("[LOOT][EPIC] {Name} ({Guid}) generated item with {Count} epic{EpicPlural} - {WoName} ({WoGuid}) - {SpellList} - killed by {KillerName} ({KillerGuid})", Name, Guid, epicCantrips.Count, (epicCantrips.Count > 1 ? "s" : ""), wo.Name, wo.Guid, GetSpellList(epicCantrips), killer?.Name, killer?.Guid); - if (legendaryCantrips.Count > 0 && log.IsDebugEnabled) - log.Debug($"[LOOT][LEGENDARY] {Name} ({Guid}) generated item with {legendaryCantrips.Count} legendar{(legendaryCantrips.Count > 1 ? "ies" : "y")} - {wo.Name} ({wo.Guid}) - {GetSpellList(legendaryCantrips)} - killed by {killer?.Name} ({killer?.Guid})"); + if (legendaryCantrips.Count > 0 && log.IsEnabled(LogLevel.Debug)) + log.LogDebug("[LOOT][LEGENDARY] {Name} ({Guid}) generated item with {Count} legendar{LegendaryPlural} - {WoName} ({WoGuid}) - {SpellList} - killed by {KillerName} ({KillerGuid})", Name, Guid, legendaryCantrips.Count, (legendaryCantrips.Count > 1 ? "ies" : "y"), wo.Name, wo.Guid, GetSpellList(legendaryCantrips), killer?.Name, killer?.Guid); } public static string GetSpellList(Dictionary spellTable) diff --git a/Source/ACE.Server/WorldObjects/Creature_Equipment.cs b/Source/ACE.Server/WorldObjects/Creature_Equipment.cs index bf677e4e1b..ba40bd959c 100644 --- a/Source/ACE.Server/WorldObjects/Creature_Equipment.cs +++ b/Source/ACE.Server/WorldObjects/Creature_Equipment.cs @@ -2,8 +2,9 @@ using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.Database; using ACE.Database.Models.World; using ACE.Entity; @@ -272,7 +273,7 @@ public int GetEquippedItemsRatingSum(PropertyInt rating) if (equippedItemsRatingCache.TryGetValue(rating, out var value)) return value; - log.Error($"Creature_Equipment.GetEquippedItemsRatingsSum() does not support {rating}"); + log.LogError("Creature_Equipment.GetEquippedItemsRatingsSum() does not support {Rating}", rating); return 0; } diff --git a/Source/ACE.Server/WorldObjects/Creature_Missile.cs b/Source/ACE.Server/WorldObjects/Creature_Missile.cs index 659bbb98a0..ab40c9439c 100644 --- a/Source/ACE.Server/WorldObjects/Creature_Missile.cs +++ b/Source/ACE.Server/WorldObjects/Creature_Missile.cs @@ -2,7 +2,8 @@ using System.Linq; using System.Numerics; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Database; using ACE.DatLoader; using ACE.DatLoader.FileTypes; @@ -183,13 +184,13 @@ private static float GetProjectileRadius(uint projectileWcid) if (weenie == null) { - log.Error($"Creature_Missile.GetProjectileRadius(): couldn't find projectile weenie {projectileWcid}"); + log.LogError("Creature_Missile.GetProjectileRadius(): couldn't find projectile weenie {ProjectileWcid}", projectileWcid); return 0.0f; } if (!weenie.PropertiesDID.TryGetValue(PropertyDataId.Setup, out var setupId)) { - log.Error($"Creature_Missile.GetProjectileRadius(): couldn't find SetupId for {weenie.WeenieClassId} - {weenie.ClassName}"); + log.LogError("Creature_Missile.GetProjectileRadius(): couldn't find SetupId for {WeenieClassId} - {ClassName}", weenie.WeenieClassId, weenie.ClassName); return 0.0f; } @@ -216,7 +217,7 @@ public float GetProjectileSpeed() if (maxVelocity == 0.0f) { - log.Warn($"{Name}.GetMissileSpeed() - {missileLauncher.Name} ({missileLauncher.Guid}) has speed 0"); + log.LogWarning("{Name}.GetMissileSpeed() - {MissileLauncherName} ({Guid}) has speed 0", Name, missileLauncher.Name, missileLauncher.Guid); maxVelocity = DefaultProjectileSpeed; } diff --git a/Source/ACE.Server/WorldObjects/Creature_Navigation.cs b/Source/ACE.Server/WorldObjects/Creature_Navigation.cs index 4316d8c1d1..489574a11d 100644 --- a/Source/ACE.Server/WorldObjects/Creature_Navigation.cs +++ b/Source/ACE.Server/WorldObjects/Creature_Navigation.cs @@ -1,7 +1,8 @@ using System; using System.Numerics; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Entity; using ACE.Entity.Enum; using ACE.Entity.Enum.Properties; @@ -427,7 +428,7 @@ public void FakeTeleport(Position _newPosition) if (Location.Landblock != newPosition.Landblock) { - log.Error($"{Name} tried to teleport from {Location} to a different landblock {newPosition}"); + log.LogError("{Name} tried to teleport from {Location} to a different landblock {NewPosition}", Name, Location, newPosition); return; } diff --git a/Source/ACE.Server/WorldObjects/Creature_Vitals.cs b/Source/ACE.Server/WorldObjects/Creature_Vitals.cs index 85df7edc80..de420315c8 100644 --- a/Source/ACE.Server/WorldObjects/Creature_Vitals.cs +++ b/Source/ACE.Server/WorldObjects/Creature_Vitals.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Entity.Enum; using ACE.Entity.Enum.Properties; using ACE.Server.WorldObjects.Entity; @@ -39,7 +40,7 @@ public CreatureVital GetCreatureVital(PropertyAttribute2nd vital) case PropertyAttribute2nd.Mana: return Mana; default: - log.Error($"{Name}.GetCreatureVital({vital}): unexpected vital"); + log.LogError("{Name}.GetCreatureVital({Vital}): unexpected vital", Name, vital); return null; } } diff --git a/Source/ACE.Server/WorldObjects/Hook.cs b/Source/ACE.Server/WorldObjects/Hook.cs index 8725ac2e11..f69e6401de 100644 --- a/Source/ACE.Server/WorldObjects/Hook.cs +++ b/Source/ACE.Server/WorldObjects/Hook.cs @@ -145,7 +145,7 @@ protected override void OnAddItem() if (item == null) { - log.Error("OnAddItem() raised for Hook but Inventory collection has no values."); + log.LogError("OnAddItem() raised for Hook but Inventory collection has no values."); return; } diff --git a/Source/ACE.Server/WorldObjects/House.cs b/Source/ACE.Server/WorldObjects/House.cs index 08cd67c1eb..69af63061a 100644 --- a/Source/ACE.Server/WorldObjects/House.cs +++ b/Source/ACE.Server/WorldObjects/House.cs @@ -95,7 +95,7 @@ public HouseData GetHouseData(IPlayer owner) if (SlumLord == null) { //Console.WriteLine($"No slumlord found for {Name} ({Guid})"); - log.Warn($"[HOUSE] No slumlord found for {Name} ({Guid})"); + log.LogWarning("[HOUSE] No slumlord found for {Name} ({Guid})", Name, Guid); } else { @@ -345,7 +345,7 @@ public void BuildGuests() if (player == null) { //Console.WriteLine($"{Name}.BuildGuests(): couldn't find guest {kvp.Key:X8}"); - log.Warn($"[HOUSE] {Name}.BuildGuests(): couldn't find guest {kvp.Key:X8}"); + log.LogWarning("[HOUSE] {Name}.BuildGuests(): couldn't find guest {Key:X8}", Name, kvp.Key); // character has been deleted -- automatically remove? deleted.Add(kvp.Key); @@ -384,7 +384,7 @@ public void ModifyGuest(IPlayer guest, bool storage) if (existingStorage == null) { //Console.WriteLine($"{Name}.FindGuest({guest.Guid}): couldn't find {guest.Name}"); - log.Warn($"[HOUSE] {Name}.FindGuest({guest.Guid}): couldn't find {guest.Name}"); + log.LogWarning("[HOUSE] {Name}.FindGuest({Guid}): couldn't find {GuestName}", Name, guest.Guid, guest.Name); return; } @@ -424,7 +424,7 @@ public void ClearPermissions() if (player == null) { //Console.WriteLine($"{Name}.ClearPermissions(): couldn't find {guest}"); - log.Warn($"[HOUSE] {Name}.ClearPermissions(): couldn't find {guest}"); + log.LogWarning("[HOUSE] {Name}.ClearPermissions(): couldn't find {Guest}", Name, guest); continue; } RemoveGuest(player); @@ -539,7 +539,7 @@ public ObjectGuid RootGuid _rootGuid = new ObjectGuid(rootGuid); else { - log.Error($"House.RootGuid - couldn't find root guid for house guid {Guid}"); + log.LogError("House.RootGuid - couldn't find root guid for house guid {Guid}", Guid); _rootGuid = Guid; } } diff --git a/Source/ACE.Server/WorldObjects/HousePortal.cs b/Source/ACE.Server/WorldObjects/HousePortal.cs index dcaeb3ccc9..37e37cf50f 100644 --- a/Source/ACE.Server/WorldObjects/HousePortal.cs +++ b/Source/ACE.Server/WorldObjects/HousePortal.cs @@ -41,13 +41,13 @@ public override void SetLinkProperties(WorldObject wo) { if (House == null) { - log.Warn($"[HOUSE] HousePortal.SetLinkProperties({(wo != null ? $"{wo.Name}:0x{wo.Guid}:{wo.WeenieClassId}" : "null")}): House is null for HousePortal 0x{Guid} at {Location.ToLOCString()}"); + log.LogWarning("[HOUSE] HousePortal.SetLinkProperties({WorldObject}): House is null for HousePortal 0x{Guid} at {Location}", (wo != null ? $"{wo.Name}:0x{wo.Guid}:{wo.WeenieClassId}" : "null"), Guid, Location.ToLOCString()); return; } if (wo == null) { - log.Warn($"[HOUSE] HousePortal.SetLinkProperties(null): WorldObject is null for HousePortal 0x{Guid} at {Location.ToLOCString()} | {(House != null ? $"House = {House.Name}:0x{House.Guid}:{House.WeenieClassId}" : "House is null")}"); + log.LogWarning("[HOUSE] HousePortal.SetLinkProperties(null): WorldObject is null for HousePortal 0x{Guid} at {Location} | {House}", Guid, Location.ToLOCString(), (House != null ? $"House = {House.Name}:0x{House.Guid}:{House.WeenieClassId}" : "House is null")); return; } @@ -96,7 +96,7 @@ public override void SetLinkProperties(WorldObject wo) } catch (Exception ex) { - log.Error($"[HOUSE] HousePortal.SetLinkProperties({(wo != null ? $"{wo.Name}:0x{wo.Guid}:{wo.WeenieClassId}" : "null")}): {(ParentLink != null ? $"ParentLink = {ParentLink.Name}:0x{ParentLink.Guid}:{ParentLink.WeenieClassId}" : "ParentLink is null")} {(House != null ? $"House = {House.Name}:0x{House.Guid}:{House.WeenieClassId}" : "House is null")} for HousePortal 0x{Guid} at {Location.ToLOCString()}\n Exception: {ex}"); + log.LogError("[HOUSE] HousePortal.SetLinkProperties({WorldObject}): {ParentLink} {House} for HousePortal 0x{Guid} at {Location}\n Exception: {Ex}", (wo != null ? $"{wo.Name}:0x{wo.Guid}:{wo.WeenieClassId}" : "null"), (ParentLink != null ? $"ParentLink = {ParentLink.Name}:0x{ParentLink.Guid}:{ParentLink.WeenieClassId}" : "ParentLink is null"), (House != null ? $"House = {House.Name}:0x{House.Guid}:{House.WeenieClassId}" : "House is null"), Guid, Location.ToLOCString(), ex); } } @@ -106,8 +106,8 @@ public override ActivationResult CheckUseRequirements(WorldObject activator) if (activator == null || rootHouse == null) { - log.Warn($"HousePortal.CheckUseRequirements: 0x{Guid} - {Location.ToLOCString()}"); - log.Warn($"HousePortal.CheckUseRequirements: activator is null - {activator == null} | House is null - {House == null} | RootHouse is null - {rootHouse == null}"); + log.LogWarning("HousePortal.CheckUseRequirements: 0x{Guid} - {Location}", Guid, Location.ToLOCString()); + log.LogWarning("HousePortal.CheckUseRequirements: activator is null - {ActivatorIsNull} | House is null - {HouseIsNull} | RootHouse is null - {RootHouseIsNull}", activator == null, House == null, rootHouse == null); return new ActivationResult(false); } diff --git a/Source/ACE.Server/WorldObjects/Key.cs b/Source/ACE.Server/WorldObjects/Key.cs index d5fa4101c2..cf4f521246 100644 --- a/Source/ACE.Server/WorldObjects/Key.cs +++ b/Source/ACE.Server/WorldObjects/Key.cs @@ -68,7 +68,7 @@ public override void HandleActionUseOnTarget(Player player, WorldObject target) if (Structure == 0 || Structure > MaxStructure) { - log.Warn($"Key.HandleActionUseOnTarget: Structure / MaxStructure is {Structure:N0} / {MaxStructure:N0} for {Name} (0x{Guid}:{WeenieClassId}), used on {target.Name} (0x{target.Guid}:{target.WeenieClassId}) and used by {player.Name} (0x{player.Guid})"); + log.LogWarning("Key.HandleActionUseOnTarget: Structure / MaxStructure is {Structure:N0} / {MaxStructure:N0} for {Name} (0x{Guid}:{WeenieClassId}), used on {TargetName} (0x{TargetGuid}:{TargetWeenieClassId}) and used by {PlayerName} (0x{PlayerGuid})", Structure, MaxStructure, Name, Guid, WeenieClassId, target.Name, target.Guid, target.WeenieClassId, player.Name, player.Guid); var wo = player.FindObject(Guid.Full, Player.SearchLocations.Everywhere, out _, out Container rootOwner, out bool wasEquipped); DeleteObject(rootOwner); diff --git a/Source/ACE.Server/WorldObjects/Lock.cs b/Source/ACE.Server/WorldObjects/Lock.cs index 96153d08e9..4d390b08dc 100644 --- a/Source/ACE.Server/WorldObjects/Lock.cs +++ b/Source/ACE.Server/WorldObjects/Lock.cs @@ -88,7 +88,7 @@ public static void ConsumeUnlocker(Player player, WorldObject unlocker, WorldObj if (unlocker.Structure == 0) { if (!player.TryConsumeFromInventoryWithNetworking(unlocker, 1)) - log.Warn($"UnlockerHelper.ConsumeUnlocker: TryConsumeFromInventoryWithNetworking failed for {unlocker.Name} (0x{unlocker.Guid}:{unlocker.WeenieClassId}), used on {target.Name} (0x{target.Guid}:{target.WeenieClassId}) and used by {player.Name} (0x{player.Guid})"); + log.LogWarning("UnlockerHelper.ConsumeUnlocker: TryConsumeFromInventoryWithNetworking failed for {UnlockerName} (0x{UnlockerGuid}:{UnlockerWeenieClassId}), used on {TargetName} (0x{TargetGuid}:{TargetWeenieClassId}) and used by {PlayerName} (0x{PlayerGuid})", unlocker.Name, unlocker.Guid, unlocker.WeenieClassId, target.Name, target.Guid, target.WeenieClassId, player.Name, player.Guid); } else { diff --git a/Source/ACE.Server/WorldObjects/ManaStone.cs b/Source/ACE.Server/WorldObjects/ManaStone.cs index 50958371bc..9e78bda227 100644 --- a/Source/ACE.Server/WorldObjects/ManaStone.cs +++ b/Source/ACE.Server/WorldObjects/ManaStone.cs @@ -95,7 +95,7 @@ public override void HandleActionUseOnTarget(Player player, WorldObject target) { if (!player.TryConsumeFromInventoryWithNetworking(target, 1) && !player.TryDequipObjectWithNetworking(target.Guid, out _, Player.DequipObjectAction.ConsumeItem)) { - log.Error($"Failed to remove {target.Name} from player inventory."); + log.LogError("Failed to remove {Name} from player inventory.", target.Name); player.Session.Network.EnqueueSend(new GameEventUseDone(player.Session, WeenieError.ActionCancelled)); return; } diff --git a/Source/ACE.Server/WorldObjects/Managers/ConfirmationManager.cs b/Source/ACE.Server/WorldObjects/Managers/ConfirmationManager.cs index 5ae5402274..e8b42ab28d 100644 --- a/Source/ACE.Server/WorldObjects/Managers/ConfirmationManager.cs +++ b/Source/ACE.Server/WorldObjects/Managers/ConfirmationManager.cs @@ -103,7 +103,7 @@ public bool HandleResponse(ConfirmationType confirmType, uint contextId, bool re break; default: - log.Error($"{Player.Name}.ConfirmationManager.HandleResponse({confirmType}, {contextId}, {response}, {timeout}) - confirmType not found"); + log.LogError("{Name}.ConfirmationManager.HandleResponse({ConfirmType}, {ContextId}, {Response}, {Timeout}) - confirmType not found", Player.Name, confirmType, contextId, response, timeout); break; } @@ -116,17 +116,17 @@ public bool HandleResponse(ConfirmationType confirmType, uint contextId, bool re { // dialog box does not dismiss on ConfirmationDone, unlike on all other types, so we must let the player know when they click either yes or no, nothing occured because the offer has already expired. if (!confirmations.TryAdd(confirm.ConfirmationType, confirm)) - log.Error($"{Player.Name}.ConfirmationManager.HandleResponse({confirm.ConfirmationType}, {confirm.ContextId}) - Unable to re-add confirmation, duplicate confirmation type"); + log.LogError("{Name}.ConfirmationManager.HandleResponse({ConfirmationType}, {ContextId}) - Unable to re-add confirmation, duplicate confirmation type", Player.Name, confirm.ConfirmationType, confirm.ContextId); Player.SendMessage("That offer of fellowship has expired."); // still looking for pcap accurate response return false; } - log.Error($"{Player.Name}.ConfirmationManager.HandleResponse({confirmType}, {contextId}, {response}, {timeout}) - contextId != confirm.ContextId"); + log.LogError("{Name}.ConfirmationManager.HandleResponse({ConfirmType}, {ContextId}, {Response}, {Timeout}) - contextId != confirm.ContextId", Player.Name, confirmType, contextId, response, timeout); if (!confirmations.TryAdd(confirm.ConfirmationType, confirm)) - log.Error($"{Player.Name}.ConfirmationManager.HandleResponse({confirm.ConfirmationType}, {confirm.ContextId}) - Unable to re-add confirmation, duplicate confirmation type"); + log.LogError("{Name}.ConfirmationManager.HandleResponse({ConfirmationType}, {ContextId}) - Unable to re-add confirmation, duplicate confirmation type", Player.Name, confirm.ConfirmationType, confirm.ContextId); return false; } diff --git a/Source/ACE.Server/WorldObjects/Managers/EmoteManager.cs b/Source/ACE.Server/WorldObjects/Managers/EmoteManager.cs index d9f27a2391..eb21a1e01e 100644 --- a/Source/ACE.Server/WorldObjects/Managers/EmoteManager.cs +++ b/Source/ACE.Server/WorldObjects/Managers/EmoteManager.cs @@ -188,7 +188,7 @@ public float ExecuteEmote(PropertiesEmote emoteSet, PropertiesEmoteAction emote, text = Replace(emote.Message, WorldObject, targetObject, emoteSet.Quest); - log.Info($"0x{WorldObject.Guid}:{WorldObject.Name}({WorldObject.WeenieClassId}).EmoteManager.BLog - {text}"); + log.LogInformation("0x{Guid}:{Name}({WeenieClassId}).EmoteManager.BLog - {Text}", WorldObject.Guid, WorldObject.Name, WorldObject.WeenieClassId, text); break; case EmoteType.CastSpell: @@ -198,7 +198,7 @@ public float ExecuteEmote(PropertiesEmote emoteSet, PropertiesEmoteAction emote, var spell = new Spell((uint)emote.SpellId); if (spell.NotFound) { - log.Error($"{WorldObject.Name} ({WorldObject.Guid}) EmoteManager.CastSpell - unknown spell {emote.SpellId}"); + log.LogError("{Name} ({Guid}) EmoteManager.CastSpell - unknown spell {SpellId}", WorldObject.Name, WorldObject.Guid, emote.SpellId); break; } @@ -1273,7 +1273,7 @@ public float ExecuteEmote(PropertiesEmote emoteSet, PropertiesEmoteAction emote, var questName = emote.Message; if (questName.EndsWith("@#kt", StringComparison.Ordinal)) - log.Warn($"0x{WorldObject.Guid}:{WorldObject.Name} ({WorldObject.WeenieClassId}).EmoteManager.ExecuteEmote: EmoteType.StampQuest({questName}) is a depreciated kill task method."); + log.LogWarning("0x{Guid}:{Name} ({WeenieClassId}).EmoteManager.ExecuteEmote: EmoteType.StampQuest({QuestName}) is a depreciated kill task method.", WorldObject.Guid, WorldObject.Name, WorldObject.WeenieClassId, questName); questTarget.QuestManager.Stamp(emote.Message); } @@ -1304,13 +1304,13 @@ public float ExecuteEmote(PropertiesEmote emoteSet, PropertiesEmoteAction emote, if (weenieItemToTake == 0) { - log.Warn($"EmoteManager.Execute: 0x{WorldObject.Guid} {WorldObject.Name} ({WorldObject.WeenieClassId}) EmoteType.TakeItems has invalid emote.WeenieClassId: {weenieItemToTake}"); + log.LogWarning("EmoteManager.Execute: 0x{Guid} {Name} ({WeenieClassId}) EmoteType.TakeItems has invalid emote.WeenieClassId: {WeenieItemToTake}", WorldObject.Guid, WorldObject.Name, WorldObject.WeenieClassId, weenieItemToTake); break; } if (amountToTake < -1 || amountToTake == 0) { - log.Warn($"EmoteManager.Execute: 0x{WorldObject.Guid} {WorldObject.Name} ({WorldObject.WeenieClassId}) EmoteType.TakeItems has invalid emote.StackSize: {amountToTake}"); + log.LogWarning("EmoteManager.Execute: 0x{Guid} {Name} ({WeenieClassId}) EmoteType.TakeItems has invalid emote.StackSize: {AmountToTake}", WorldObject.Guid, WorldObject.Name, WorldObject.WeenieClassId, amountToTake); break; } @@ -1500,7 +1500,7 @@ public float ExecuteEmote(PropertiesEmote emoteSet, PropertiesEmoteAction emote, break; default: - log.DebugFormat("EmoteManager.Execute - Encountered Unhandled EmoteType {0} for {1} ({2})", (EmoteType)emote.Type, WorldObject.Name, WorldObject.WeenieClassId); + log.LogDebug("EmoteManager.Execute - Encountered Unhandled EmoteType {Type} for {Name} ({WeenieClassId})", (EmoteType)emote.Type, WorldObject.Name, WorldObject.WeenieClassId); break; } @@ -1611,7 +1611,7 @@ public void Enqueue(PropertiesEmote emoteSet, WorldObject targetObject, int emot foreach (var e in emoteSet.PropertiesEmoteAction) emoteStack += $" - {(EmoteType)emote.Type}{(string.IsNullOrEmpty(emote.Message) ? "" : $": {emote.Message}")}\n"; - log.Error($"[EMOTE] {WorldObject.Name}.EmoteManager.Enqueue(): Nested > 75, possible Infinite loop detected and aborted on 0x{WorldObject.Guid}:{WorldObject.WeenieClassId}\n-> {emoteStack}"); + log.LogError("[EMOTE] {Name}.EmoteManager.Enqueue(): Nested > 75, possible Infinite loop detected and aborted on 0x{Guid}:{WeenieClassId}\n-> {EmoteStack}", WorldObject.Name, WorldObject.Guid, WorldObject.WeenieClassId, emoteStack); Nested--; @@ -1781,7 +1781,7 @@ public string Replace(string message, WorldObject source, WorldObject target, st if (result == null) { - log.Warn($"[EMOTE] {WorldObject.Name}.EmoteManager.Replace(message, {source.Name}:0x{source.Guid}:{source.WeenieClassId}, {target.Name}:0x{target.Guid}:{target.WeenieClassId}, {quest}): message was null!"); + log.LogWarning("[EMOTE] {WorldObjectName}.EmoteManager.Replace(message, {SourceName}:0x{SourceGuid}:{SourceWeenieClassId}, {TargetName}:0x{TargetGuid}:{TargetWeenieClassId}, {Quest}): message was null!", WorldObject.Name, source.Name, source.Guid, source.WeenieClassId, target.Name, target.Guid, target.WeenieClassId, quest); return ""; } diff --git a/Source/ACE.Server/WorldObjects/Monster_Combat.cs b/Source/ACE.Server/WorldObjects/Monster_Combat.cs index 0f2dfbf971..fefefeb42f 100644 --- a/Source/ACE.Server/WorldObjects/Monster_Combat.cs +++ b/Source/ACE.Server/WorldObjects/Monster_Combat.cs @@ -3,8 +3,9 @@ using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.Database; using ACE.DatLoader; using ACE.DatLoader.FileTypes; @@ -432,7 +433,7 @@ public static BodyPartTable GetBodyParts(uint wcid) if (weenie == null) { // should never happen? - log.Error($"Monster_Combat.GetBodyParts({wcid}) - unknown wcid"); + log.LogError("Monster_Combat.GetBodyParts({Wcid}) - unknown wcid", wcid); return null; } @@ -442,8 +443,8 @@ public static BodyPartTable GetBodyParts(uint wcid) } catch (Exception e) { - log.Error(e); - log.Error($"Monster_Combat.GetBodyParts({wcid}) - bad data for wcid {wcid}"); + log.LogError(e, "{Message:l}", e.Message); + log.LogError("Monster_Combat.GetBodyParts({Wcid}) - bad data for wcid {Wcid}", wcid, wcid); return null; } BPTableCache[wcid] = bpTable; diff --git a/Source/ACE.Server/WorldObjects/Monster_Melee.cs b/Source/ACE.Server/WorldObjects/Monster_Melee.cs index dc6593e8fd..36c82a4920 100644 --- a/Source/ACE.Server/WorldObjects/Monster_Melee.cs +++ b/Source/ACE.Server/WorldObjects/Monster_Melee.cs @@ -3,8 +3,9 @@ using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.DatLoader; using ACE.DatLoader.Entity.AnimationHooks; using ACE.Entity; @@ -168,7 +169,7 @@ public float MeleeAttack() if (CombatTable == null) { - log.Error($"{Name} ({Guid}).GetCombatManeuver() - WCID: {WeenieClassId} | CombatTable is null"); + log.LogError("{Name} ({Guid}).GetCombatManeuver() - WCID: {WeenieClassId} | CombatTable is null", Name, Guid, WeenieClassId); return null; } @@ -177,13 +178,13 @@ public float MeleeAttack() var motionTable = DatManager.PortalDat.ReadFromDat(MotionTableId); if (motionTable == null) { - log.Error($"{Name} ({Guid}).GetCombatManeuver() - WCID: {WeenieClassId} | motionTable is null"); + log.LogError("{Name} ({Guid}).GetCombatManeuver() - WCID: {WeenieClassId} | motionTable is null", Name, Guid, WeenieClassId); return null; } if (!CombatTable.Stances.TryGetValue(CurrentMotionState.Stance, out var stanceManeuvers)) { - log.Error($"{Name} ({Guid}).GetCombatManeuver() - WCID: {WeenieClassId} | couldn't find stance {CurrentMotionState.Stance} in CMT {CombatTableDID:X8}"); + log.LogError("{Name} ({Guid}).GetCombatManeuver() - WCID: {WeenieClassId} | couldn't find stance {Stance} in CMT {CombatTableDID:X8}", Name, Guid, WeenieClassId, CurrentMotionState.Stance, CombatTableDID); return null; } @@ -191,7 +192,7 @@ public float MeleeAttack() motionTable.Links.TryGetValue(stanceKey, out var motions); if (motions == null) { - log.Error($"{Name} ({Guid}).GetCombatManeuver() - WCID: {WeenieClassId} | couldn't find stance {CurrentMotionState.Stance} in MotionTable {MotionTableId:X8}"); + log.LogError("{Name} ({Guid}).GetCombatManeuver() - WCID: {WeenieClassId} | couldn't find stance {Stance} in MotionTable {MotionTableId:X8}", Name, Guid, WeenieClassId, CurrentMotionState.Stance, MotionTableId); return null; } @@ -206,7 +207,7 @@ public float MeleeAttack() if (!stanceManeuvers.Table.TryGetValue(AttackHeight.Value, out var attackTypes)) { - log.Error($"{Name} ({Guid}).GetCombatManeuver() - WCID: {WeenieClassId} | couldn't find attack height {AttackHeight} for stance {CurrentMotionState.Stance} in CMT {CombatTableDID:X8}"); + log.LogError("{Name} ({Guid}).GetCombatManeuver() - WCID: {WeenieClassId} | couldn't find attack height {AttackHeight} for stance {Stance} in CMT {CombatTableDID:X8}", Name, Guid, WeenieClassId, AttackHeight, CurrentMotionState.Stance, CombatTableDID); return null; } @@ -242,7 +243,7 @@ public float MeleeAttack() if (!attackTypes.Table.TryGetValue(AttackType, out maneuvers) || maneuvers.Count == 0) { - log.Error($"{Name} ({Guid}).GetCombatManeuver() - WCID: {WeenieClassId} | couldn't find attack type Kick or Punch for attack height {AttackHeight} and stance {CurrentMotionState.Stance} in CMT {CombatTableDID:X8}"); + log.LogError("{Name} ({Guid}).GetCombatManeuver() - WCID: {WeenieClassId} | couldn't find attack type Kick or Punch for attack height {AttackHeight} and stance {Stance} in CMT {CombatTableDID:X8}", Name, Guid, WeenieClassId, AttackHeight, CurrentMotionState.Stance, CombatTableDID); return null; } } @@ -252,7 +253,7 @@ public float MeleeAttack() if (!attackTypes.Table.TryGetValue(reduced, out maneuvers) || maneuvers.Count == 0) { - log.Error($"{Name} ({Guid}).GetCombatManeuver() - WCID: {WeenieClassId} | couldn't find attack type {reduced} for attack height {AttackHeight} and stance {CurrentMotionState.Stance} in CMT {CombatTableDID:X8}"); + log.LogError("{Name} ({Guid}).GetCombatManeuver() - WCID: {WeenieClassId} | couldn't find attack type {Reduced} for attack height {AttackHeight} and stance {Stance} in CMT {CombatTableDID:X8}", Name, Guid, WeenieClassId, reduced, AttackHeight, CurrentMotionState.Stance, CombatTableDID); return null; } //else @@ -260,7 +261,7 @@ public float MeleeAttack() } else { - log.Error($"{Name} ({Guid}).GetCombatManeuver() - WCID: {WeenieClassId} | couldn't find attack type {AttackType} for attack height {AttackHeight} and stance {CurrentMotionState.Stance} in CMT {CombatTableDID:X8}"); + log.LogError("{Name} ({Guid}).GetCombatManeuver() - WCID: {WeenieClassId} | couldn't find attack type {AttackType} for attack height {AttackHeight} and stance {Stance} in CMT {CombatTableDID:X8}", Name, Guid, WeenieClassId, AttackType, AttackHeight, CurrentMotionState.Stance, CombatTableDID); return null; } } @@ -305,7 +306,7 @@ public float MeleeAttack() return firstCommand; } } - log.Error($"{Name} ({Guid}).GetCombatManeuver() - WCID: {WeenieClassId} | couldn't find {motionCommand} in MotionTable {MotionTableId:X8}"); + log.LogError("{Name} ({Guid}).GetCombatManeuver() - WCID: {WeenieClassId} | couldn't find {MotionCommand} in MotionTable {MotionTableId:X8}", Name, Guid, WeenieClassId, motionCommand, MotionTableId); return null; } @@ -362,7 +363,7 @@ public void DoSwingMotion(WorldObject target, MotionCommand motionCommand, out f if (!missingAttackFrames.ContainsKey(attackFrameParams)) { // only show warning message once for each combo - log.Warn($"{Name} ({Guid}) - no attack frames for MotionTable {MotionTableId:X8}, {CurrentMotionState.Stance}, {motionCommand}, using defaults"); + log.LogWarning("{Name} ({Guid}) - no attack frames for MotionTable {MotionTableId:X8}, {Stance}, {MotionCommand}, using defaults", Name, Guid, MotionTableId, CurrentMotionState.Stance, motionCommand); missingAttackFrames.TryAdd(attackFrameParams, true); } attackFrames = defaultAttackFrames; @@ -610,8 +611,8 @@ public KeyValuePair GetAttackPart(MotionComm if (parts.Count == 0) { - log.Warn($"{Name} ({Guid}.GetAttackPart({motionCommand}) failed"); - log.Warn($"CombatTable: {CombatTableDID:X8}, MotionTable: {MotionTableId:X8}, CurrentStance: {CurrentMotionState.Stance}, AttackHeight: {AttackHeight}, AttackType: {AttackType}"); + log.LogWarning("{Name} ({Guid}.GetAttackPart({MotionCommand}) failed", Name, Guid, motionCommand); + log.LogWarning("CombatTable: {CombatTableDID:X8}, MotionTable: {MotionTableId:X8}, CurrentStance: {Stance}, AttackHeight: {AttackHeight}, AttackType: {AttackType}", CombatTableDID, MotionTableId, CurrentMotionState.Stance, AttackHeight, AttackType); return new KeyValuePair(); } diff --git a/Source/ACE.Server/WorldObjects/Pet.cs b/Source/ACE.Server/WorldObjects/Pet.cs index 90687d1387..4aec5a337b 100644 --- a/Source/ACE.Server/WorldObjects/Pet.cs +++ b/Source/ACE.Server/WorldObjects/Pet.cs @@ -209,7 +209,7 @@ public void SlowTick(double currentUnixTime) if (P_PetOwner?.PhysicsObj == null) { - log.Error($"{Name} ({Guid}).SlowTick() - P_PetOwner: {P_PetOwner}, P_PetOwner.PhysicsObj: {P_PetOwner?.PhysicsObj}"); + log.LogError("{Name} ({Guid}).SlowTick() - P_PetOwner: {P_PetOwner}, P_PetOwner.PhysicsObj: {PhysicsObj}", Name, Guid, P_PetOwner, P_PetOwner?.PhysicsObj); Destroy(); return; } diff --git a/Source/ACE.Server/WorldObjects/PetDevice.cs b/Source/ACE.Server/WorldObjects/PetDevice.cs index e1629e582e..0612a8b599 100644 --- a/Source/ACE.Server/WorldObjects/PetDevice.cs +++ b/Source/ACE.Server/WorldObjects/PetDevice.cs @@ -69,7 +69,7 @@ public override void ActOnUse(WorldObject activator) if (PetClass == null) { - log.Error($"{activator.Name}.ActOnUse({Name}) - PetClass is null for PetDevice {WeenieClassId}"); + log.LogError("{ActivatorName}.ActOnUse({Name}) - PetClass is null for PetDevice {WeenieClassId}", activator.Name, Name, WeenieClassId); return; } @@ -152,7 +152,7 @@ public override ActivationResult CheckUseRequirements(WorldObject activator) if (wo == null) { - log.Error($"{player.Name}.SummonCreature({wcid}) - couldn't find wcid for PetDevice {WeenieClassId} - {WeenieClassName}"); + log.LogError("{Name}.SummonCreature({Wcid}) - couldn't find wcid for PetDevice {WeenieClassId} - {WeenieClassName}", player.Name, wcid, WeenieClassId, WeenieClassName); return false; } @@ -160,7 +160,7 @@ public override ActivationResult CheckUseRequirements(WorldObject activator) if (pet == null) { - log.Error($"{player.Name}.SummonCreature({wcid}) - PetDevice {WeenieClassId} - {WeenieClassName} tried to summon {wo.WeenieClassId} - {wo.WeenieClassName} of unknown type {wo.WeenieType}"); + log.LogError("{Name}.SummonCreature({Wcid}) - PetDevice {WeenieClassId} - {WeenieClassName} tried to summon {WoWeenieClassId} - {WoWeenieClassName} of unknown type {WeenieType}", player.Name, wcid, WeenieClassId, WeenieClassName, wo.WeenieClassId, wo.WeenieClassName, wo.WeenieType); return false; } var success = pet.Init(player, this); diff --git a/Source/ACE.Server/WorldObjects/Player.cs b/Source/ACE.Server/WorldObjects/Player.cs index c90dd7aeb5..08482a7ece 100644 --- a/Source/ACE.Server/WorldObjects/Player.cs +++ b/Source/ACE.Server/WorldObjects/Player.cs @@ -643,7 +643,7 @@ public void ForceLogoff() { if (!ForcedLogOffRequested) return; - log.WarnFormat("[LOGOUT] Executing ForcedLogoff for Account {0} with character {1} (0x{2}) at {3}.", Account.AccountName, Name, Guid, DateTime.Now.ToCommonString()); + log.LogWarning("[LOGOUT] Executing ForcedLogoff for Account {AccountName} with character {Name} (0x{Guid}) at {Now}.", Account.AccountName, Name, Guid, DateTime.Now.ToCommonString()); FinalizeLogout(); @@ -658,7 +658,7 @@ private void FinalizeLogout() SavePlayerToDatabase(); PlayerManager.SwitchPlayerFromOnlineToOffline(this); - log.DebugFormat("[LOGOUT] Account {0} exited the world with character {1} (0x{2}) at {3}.", Account.AccountName, Name, Guid, DateTime.Now.ToCommonString()); + log.LogDebug("[LOGOUT] Account {AccountName} exited the world with character {Name} (0x{Guid}) at {Now}.", Account.AccountName, Name, Guid, DateTime.Now.ToCommonString()); } public void HandleMRT() diff --git a/Source/ACE.Server/WorldObjects/Player_Allegiance.cs b/Source/ACE.Server/WorldObjects/Player_Allegiance.cs index 5a93fe0ae3..cda361caff 100644 --- a/Source/ACE.Server/WorldObjects/Player_Allegiance.cs +++ b/Source/ACE.Server/WorldObjects/Player_Allegiance.cs @@ -1,7 +1,8 @@ using System; using System.Linq; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Entity; using ACE.Entity.Enum; using ACE.Entity.Enum.Properties; @@ -95,7 +96,7 @@ public void SwearAllegiance(uint targetGuid, bool success, bool confirmed = fals return; } - log.InfoFormat("[ALLEGIANCE] {0} ({1}) swearing allegiance to {2} ({3})", Name, Level, patron.Name, patron.Level); + log.LogInformation("[ALLEGIANCE] {Name} ({Level}) swearing allegiance to {PatronName} ({PatronLevel})", Name, Level, patron.Name, patron.Level); PatronId = targetGuid; @@ -176,7 +177,7 @@ public void HandleActionBreakAllegiance(uint targetGuid) if (target == null) return; - log.InfoFormat("[ALLEGIANCE] {0} breaking allegiance to {1}", Name, target.Name); + log.LogInformation("[ALLEGIANCE] {Name} breaking allegiance to {TargetName}", Name, target.Name); // target can be either patron or vassal var isPatron = PatronId == target.Guid.Full; @@ -982,7 +983,7 @@ public void HandleActionDoAllegianceLockAction(AllegianceLockAction action) if (approvedVassal == null) { // automatically remove? - log.Warn($"{Name}.HandleActionDoAllegianceLockAction({action}): couldn't find approved vassal {entity.Key:X8}"); + log.LogWarning("{Name}.HandleActionDoAllegianceLockAction({Action}): couldn't find approved vassal {Key:X8}", Name, action, entity.Key); continue; } @@ -1300,7 +1301,7 @@ public void HandleActionListAllegianceBans() if (player == null) { // automatically remove? - log.Warn($"{Name}.HandleActionListAllegianceBans(): couldn't find banned player {entity.Key:X8}"); + log.LogWarning("{Name}.HandleActionListAllegianceBans(): couldn't find banned player {Key:X8}", Name, entity.Key); continue; } @@ -1395,7 +1396,7 @@ public void HandleActionRemoveAllegianceBan(string playerName) public void HandleActionBreakAllegianceBoot(string playerName, bool accountBoot) { - log.InfoFormat("[ALLEGIANCE] {0}.HandleActionBreakAllegianceBoot({1}, {2})", Name, playerName, accountBoot); + log.LogInformation("[ALLEGIANCE] {Name}.HandleActionBreakAllegianceBoot({PlayerName}, {AccountBoot})", Name, playerName, accountBoot); // TODO: handle account boot diff --git a/Source/ACE.Server/WorldObjects/Player_Attributes.cs b/Source/ACE.Server/WorldObjects/Player_Attributes.cs index f3679a8567..dbad78bce4 100644 --- a/Source/ACE.Server/WorldObjects/Player_Attributes.cs +++ b/Source/ACE.Server/WorldObjects/Player_Attributes.cs @@ -1,4 +1,5 @@ -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.DatLoader; using ACE.Entity.Enum; using ACE.Entity.Enum.Properties; @@ -15,13 +16,13 @@ public bool HandleActionRaiseAttribute(PropertyAttribute attribute, uint amount) { if (!Attributes.TryGetValue(attribute, out var creatureAttribute)) { - log.Warn($"{Name}.HandleActionRaiseAttribute({attribute}, {amount}) - invalid attribute"); + log.LogWarning("{Name}.HandleActionRaiseAttribute({Attribute}, {Amount}) - invalid attribute", Name, attribute, amount); return false; } if (amount > AvailableExperience) { - log.Warn($"{Name}.HandleActionRaiseAttribute({attribute}, {amount}) - amount > AvaiableExperience ({AvailableExperience})"); + log.LogWarning("{Name}.HandleActionRaiseAttribute({Attribute}, {Amount}) - amount > AvaiableExperience ({AvailableExperience})", Name, attribute, amount, AvailableExperience); return false; } @@ -78,7 +79,7 @@ private bool SpendAttributeXp(CreatureAttribute creatureAttribute, uint amount, // ensure attribute is not already max rank if (creatureAttribute.IsMaxRank) { - log.Warn($"{Name}.SpendAttributeXp({creatureAttribute.Attribute}, {amount}) - player tried to raise attribute beyond max rank"); + log.LogWarning("{Name}.SpendAttributeXp({Attribute}, {Amount}) - player tried to raise attribute beyond max rank", Name, creatureAttribute.Attribute, amount); return false; } @@ -88,7 +89,7 @@ private bool SpendAttributeXp(CreatureAttribute creatureAttribute, uint amount, if (amount > amountToEnd) { - log.Warn($"{Name}.SpendAttributeXp({creatureAttribute.Attribute}, {amount}) - player tried to raise attribute beyond {amountToEnd} experience"); + log.LogWarning("{Name}.SpendAttributeXp({Attribute}, {Amount}) - player tried to raise attribute beyond {AmountToEnd} experience", Name, creatureAttribute.Attribute, amount, amountToEnd); return false; // returning error here, instead of setting amount to amountToEnd } @@ -96,7 +97,7 @@ private bool SpendAttributeXp(CreatureAttribute creatureAttribute, uint amount, // spend xp on attribute if (!SpendXP(amount, sendNetworkUpdate)) { - log.Warn($"{Name}.SpendAttributeXp({creatureAttribute.Attribute}, {amount}) - SpendXP failed"); + log.LogWarning("{Name}.SpendAttributeXp({Attribute}, {Amount}) - SpendXP failed", Name, creatureAttribute.Attribute, amount); return false; } diff --git a/Source/ACE.Server/WorldObjects/Player_Combat.cs b/Source/ACE.Server/WorldObjects/Player_Combat.cs index 6b24bf0c04..5745e04fe5 100644 --- a/Source/ACE.Server/WorldObjects/Player_Combat.cs +++ b/Source/ACE.Server/WorldObjects/Player_Combat.cs @@ -2,8 +2,9 @@ using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.DatLoader.Entity; using ACE.Entity; using ACE.Entity.Enum; @@ -486,7 +487,7 @@ public int TakeDamage(WorldObject source, DamageType damageType, float _amount, if (_amount < 0) { - log.Error($"{Name}.TakeDamage({source?.Name} ({source?.Guid}), {damageType}, {_amount}) - negative damage, this shouldn't happen"); + log.LogError("{Name}.TakeDamage({SourceName} ({Guid}), {DamageType}, {Amount}) - negative damage, this shouldn't happen", Name, source?.Name, source?.Guid, damageType, _amount); return 0; } @@ -531,7 +532,7 @@ public int TakeDamage(WorldObject source, DamageType damageType, float _amount, if (!BodyParts.Indices.TryGetValue(bodyPart, out var iDamageLocation)) { - log.Warn($"{Name}.TakeDamage({source.Name}, {damageType}, {amount}, {bodyPart}, {crit}): avoided crash for bad damage location"); + log.LogWarning("{Name}.TakeDamage({SourceName}, {DamageType}, {Amount}, {BodyPart}, {Crit}): avoided crash for bad damage location", Name, source.Name, damageType, amount, bodyPart, crit); return 0; } var damageLocation = (DamageLocation)iDamageLocation; @@ -1077,7 +1078,7 @@ public void CheckHouseRestrictions_GetHouse(uint houseGuid, HashSet house houses.Add(rootHouse); } else - log.Error($"{Name}.CheckHouseRestrictions_GetHouse({houseGuid:X8}): couldn't find house from {CurrentLandblock.Id.Raw:X8}"); + log.LogError("{Name}.CheckHouseRestrictions_GetHouse({HouseGuid:X8}): couldn't find house from {Id:X8}", Name, houseGuid, CurrentLandblock.Id.Raw); } /// @@ -1102,7 +1103,7 @@ public override DamageType GetDamageType(bool multiple = false, CombatType? comb weapon = FootArmor; else { - log.Warn($"{Name}.GetDamageType(): no weapon, AttackType={AttackType}"); + log.LogWarning("{Name}.GetDamageType(): no weapon, AttackType={AttackType}", Name, AttackType); return DamageType.Undef; } @@ -1119,7 +1120,7 @@ public override DamageType GetDamageType(bool multiple = false, CombatType? comb if (damageType == DamageType.Undef) { - log.Warn($"{Name}.GetDamageType(): {damageSource} ({damageSource.Guid}, {damageSource.WeenieClassId}): no DamageType"); + log.LogWarning("{Name}.GetDamageType(): {DamageSource} ({Guid}, {WeenieClassId}): no DamageType", Name, damageSource, damageSource.Guid, damageSource.WeenieClassId); return DamageType.Bludgeon; } diff --git a/Source/ACE.Server/WorldObjects/Player_Commerce.cs b/Source/ACE.Server/WorldObjects/Player_Commerce.cs index ebd9c905dd..f30d855fe8 100644 --- a/Source/ACE.Server/WorldObjects/Player_Commerce.cs +++ b/Source/ACE.Server/WorldObjects/Player_Commerce.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using System.Linq; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Entity.Enum; using ACE.Entity.Enum.Properties; using ACE.Server.Entity; @@ -76,7 +77,7 @@ public void FinalizeBuyTransaction(Vendor vendor, List genericItems // errors shouldn't be possible here, since the items were pre-validated, but just in case... if (!TryCreateInInventoryWithNetworking(item)) { - log.Error($"[VENDOR] {Name}.FinalizeBuyTransaction({vendor.Name}) - couldn't add {item.Name} ({item.Guid}) to player inventory after validation, this shouldn't happen!"); + log.LogError("[VENDOR] {Name}.FinalizeBuyTransaction({VendorName}) - couldn't add {ItemName} ({Guid}) to player inventory after validation, this shouldn't happen!", Name, vendor.Name, item.Name, item.Guid); item.Destroy(); // cleanup for guid manager } @@ -100,7 +101,7 @@ public void FinalizeBuyTransaction(Vendor vendor, List genericItems vendor.NumItemsSold++; } else - log.Error($"[VENDOR] {Name}.FinalizeBuyTransaction({vendor.Name}) - couldn't add {item.Name} ({item.Guid}) to player inventory after validation, this shouldn't happen!"); + log.LogError("[VENDOR] {Name}.FinalizeBuyTransaction({VendorName}) - couldn't add {ItemName} ({Guid}) to player inventory after validation, this shouldn't happen!", Name, vendor.Name, item.Name, item.Guid); } Session.Network.EnqueueSend(new GameMessageSound(Guid, Sound.PickUpItem)); @@ -165,7 +166,7 @@ public void HandleActionSellItem(uint vendorGuid, List itemProfiles if (payoutCoinAmount < 0) { - log.Warn($"[VENDOR] {Name} (0x({Guid}) tried to sell something to {vendor.Name} (0x{vendor.Guid}) resulting in a payout of {payoutCoinAmount} pyreals."); + log.LogWarning("[VENDOR] {Name} (0x({Guid}) tried to sell something to {VendorName} (0x{VendorGuid}) resulting in a payout of {PayoutCoinAmount} pyreals.", Name, Guid, vendor.Name, vendor.Guid, payoutCoinAmount); SendTransientError("Transaction failed."); Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, Guid.Full)); @@ -202,7 +203,7 @@ public void HandleActionSellItem(uint vendorGuid, List itemProfiles if (TryRemoveFromInventoryWithNetworking(item.Guid, out _, RemoveFromInventoryAction.SellItem) || TryDequipObjectWithNetworking(item.Guid, out _, DequipObjectAction.SellItem)) Session.Network.EnqueueSend(new GameEventItemServerSaysContainId(Session, item, vendor)); else - log.WarnFormat("[VENDOR] Item 0x{0:X8}:{1} for player {2} not found in HandleActionSellItem.", item.Guid.Full, item.Name, Name); // This shouldn't happen + log.LogWarning("[VENDOR] Item 0x{Guid:X8}:{ItemName} for player {Name} not found in HandleActionSellItem.", item.Guid.Full, item.Name, Name); // This shouldn't happen } // send the list of items to the vendor @@ -214,7 +215,7 @@ public void HandleActionSellItem(uint vendorGuid, List itemProfiles { if (!TryCreateInInventoryWithNetworking(item)) // this shouldn't happen because of pre-validations in itemsToReceive { - log.WarnFormat("[VENDOR] Payout 0x{0:X8}:{1} for player {2} failed to add to inventory HandleActionSellItem.", item.Guid.Full, item.Name, Name); + log.LogWarning("[VENDOR] Payout 0x{Guid:X8}:{ItemName} for player {Name} failed to add to inventory HandleActionSellItem.", item.Guid.Full, item.Name, Name); item.Destroy(); } } @@ -242,26 +243,26 @@ private Dictionary VerifySellItems(List sellItem { if (!allPossessions.TryGetValue(sellItem.ObjectGuid, out var wo)) { - log.Warn($"[VENDOR] {Name} tried to sell item {sellItem.ObjectGuid:X8} not in their inventory to {vendor.Name}"); + log.LogWarning("[VENDOR] {Name} tried to sell item {ObjectGuid:X8} not in their inventory to {VendorName}", Name, sellItem.ObjectGuid, vendor.Name); continue; } // verify item profile (unique guids, amount) if (verified.ContainsKey(wo.Guid.Full)) { - log.Warn($"[VENDOR] {Name} tried to sell duplicate item {wo.Name} ({wo.Guid}) to {vendor.Name}"); + log.LogWarning("[VENDOR] {Name} tried to sell duplicate item {WoName} ({Guid}) to {VendorName}", Name, wo.Name, wo.Guid, vendor.Name); continue; } if (!sellItem.IsValidAmount) { - log.Warn($"[VENDOR] {Name} tried to sell {sellItem.Amount}x {wo.Name} ({wo.Guid}) to {vendor.Name}"); + log.LogWarning("[VENDOR] {Name} tried to sell {Amount}x {WoName} ({Guid}) to {VendorName}", Name, sellItem.Amount, wo.Name, wo.Guid, vendor.Name); continue; } if (sellItem.Amount > (wo.StackSize ?? 1)) { - log.Warn($"[VENDOR] {Name} tried to sell {sellItem.Amount}x {wo.Name} ({wo.Guid}) to {vendor.Name}, but they only have {wo.StackSize ?? 1}x"); + log.LogWarning("[VENDOR] {Name} tried to sell {Amount}x {WoName} ({Guid}) to {VendorName}, but they only have {StackSize}x", Name, sellItem.Amount, wo.Name, wo.Guid, vendor.Name, wo.StackSize ?? 1); continue; } diff --git a/Source/ACE.Server/WorldObjects/Player_Crafting.cs b/Source/ACE.Server/WorldObjects/Player_Crafting.cs index 8998a1787a..3c15534750 100644 --- a/Source/ACE.Server/WorldObjects/Player_Crafting.cs +++ b/Source/ACE.Server/WorldObjects/Player_Crafting.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using System.Linq; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Entity.Enum; using ACE.Entity.Enum.Properties; using ACE.Server.Entity; @@ -159,7 +160,7 @@ public void HandleSalvaging(uint tool, List salvageItems) if (item.MaterialType == null) { - log.Warn($"[CRAFTING] {Name}.HandleSalvaging({item.Name}): no material type"); + log.LogWarning("[CRAFTING] {Name}.HandleSalvaging({ItemName}): no material type", Name, item.Name); continue; } diff --git a/Source/ACE.Server/WorldObjects/Player_Database.cs b/Source/ACE.Server/WorldObjects/Player_Database.cs index ec31fbacaa..01511589fd 100644 --- a/Source/ACE.Server/WorldObjects/Player_Database.cs +++ b/Source/ACE.Server/WorldObjects/Player_Database.cs @@ -2,8 +2,9 @@ using System.Collections.ObjectModel; using System.Threading; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.Database; using ACE.Entity.Enum; using ACE.Entity.Enum.Properties; @@ -103,7 +104,7 @@ public void SavePlayerToDatabase() DatabaseManager.Shard.SaveBiotasInParallel(biotas, result => { - log.DebugFormat("{0} has been saved. It took {1:N0} ms to process the request.", Name, (DateTime.UtcNow - requestedTime).TotalMilliseconds); + log.LogDebug("{Name} has been saved. It took {TotalMilliseconds:N0} ms to process the request.", Name, (DateTime.UtcNow - requestedTime).TotalMilliseconds); if (!result) { diff --git a/Source/ACE.Server/WorldObjects/Player_Death.cs b/Source/ACE.Server/WorldObjects/Player_Death.cs index 607b6df4f7..b69b8c1e15 100644 --- a/Source/ACE.Server/WorldObjects/Player_Death.cs +++ b/Source/ACE.Server/WorldObjects/Player_Death.cs @@ -2,8 +2,9 @@ using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.DatLoader; using ACE.DatLoader.FileTypes; using ACE.Entity; @@ -63,7 +64,7 @@ public override DeathMessage OnDeath(DamageHistoryInfo lastDamager, DamageType d var broadcastMsg = new GameMessagePlayerKilled(nearbyMsg, Guid, lastDamager?.Guid ?? ObjectGuid.Invalid); - log.Info("[CORPSE] " + nearbyMsg); + log.LogInformation("[CORPSE] {NearbyMsg}", nearbyMsg); var excludePlayers = new List(); @@ -541,7 +542,7 @@ public List CalculateDeathItems(Corpse corpse) } else { - log.WarnFormat("Couldn't find death item stack 0x{0:X8}:{1} for player {2}", deathItem.WorldObject.Guid.Full, deathItem.WorldObject.Name, Name); + log.LogWarning("Couldn't find death item stack 0x{Guid:X8}:{WorldObjectName} for player {Name}", deathItem.WorldObject.Guid.Full, deathItem.WorldObject.Name, Name); } } else @@ -553,7 +554,7 @@ public List CalculateDeathItems(Corpse corpse) } else { - log.WarnFormat("Couldn't find death item 0x{0:X8}:{1} for player {2}", deathItem.WorldObject.Guid.Full, deathItem.WorldObject.Name, Name); + log.LogWarning("Couldn't find death item 0x{Guid:X8}:{WorldObjectName} for player {Name}", deathItem.WorldObject.Guid.Full, deathItem.WorldObject.Name, Name); } } } @@ -581,10 +582,10 @@ public List CalculateDeathItems(Corpse corpse) if (!corpse.TryAddToInventory(dropItem)) { - log.Warn($"Player_Death: couldn't add item to {Name}'s corpse: {dropItem.Name}"); + log.LogWarning("Player_Death: couldn't add item to {Name}'s corpse: {DropItemName}", Name, dropItem.Name); if (!TryAddToInventory(dropItem)) - log.Warn($"Player_Death: couldn't re-add item to {Name}'s inventory: {dropItem.Name}"); + log.LogWarning("Player_Death: couldn't re-add item to {Name}'s inventory: {DropItemName}", Name, dropItem.Name); } } @@ -615,7 +616,7 @@ public void DeathItemLog(List dropItems, Corpse corpse) msg = msg.Substring(0, msg.Length - 2); - log.Info(msg); + log.LogInformation("{Message:l}", msg); } /// @@ -1073,7 +1074,7 @@ public List CalculateDeathItems_Olthoi(Corpse corpse, bool hadVitae return new(); if (!corpse.TryAddToInventory(slag)) - log.Warn($"CalculateDeathItems_Olthoi: couldn't add item to {Name}'s corpse: {slag.Name}"); + log.LogWarning("CalculateDeathItems_Olthoi: couldn't add item to {Name}'s corpse: {SlagName}", Name, slag.Name); return new() { slag }; } @@ -1094,7 +1095,7 @@ public List CalculateDeathItems_Olthoi(Corpse corpse, bool hadVitae foreach (WorldObject wo in items) { if (!corpse.TryAddToInventory(wo)) - log.Warn($"CalculateDeathItems_Olthoi: couldn't add item to {Name}'s corpse: {wo.Name}"); + log.LogWarning("CalculateDeathItems_Olthoi: couldn't add item to {Name}'s corpse: {WoName}", Name, wo.Name); } return items; diff --git a/Source/ACE.Server/WorldObjects/Player_Fellowship.cs b/Source/ACE.Server/WorldObjects/Player_Fellowship.cs index 0e64b98e87..e243165590 100644 --- a/Source/ACE.Server/WorldObjects/Player_Fellowship.cs +++ b/Source/ACE.Server/WorldObjects/Player_Fellowship.cs @@ -1,4 +1,5 @@ -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Entity.Enum; using ACE.Server.Entity; using ACE.Server.Managers; @@ -117,7 +118,7 @@ public void FellowshipNewLeader(uint newLeaderGuid) if (Guid.Full != Fellowship.FellowshipLeaderGuid) { - log.Warn($"{Name} tried to assign new fellowship leader from {Fellowship.FellowshipLeaderGuid:X8} to {newLeaderGuid:X8}"); + log.LogWarning("{Name} tried to assign new fellowship leader from {FellowshipLeaderGuid:X8} to {NewLeaderGuid:X8}", Name, Fellowship.FellowshipLeaderGuid, newLeaderGuid); return; } diff --git a/Source/ACE.Server/WorldObjects/Player_House.cs b/Source/ACE.Server/WorldObjects/Player_House.cs index 6f434e2775..f1a76cafa3 100644 --- a/Source/ACE.Server/WorldObjects/Player_House.cs +++ b/Source/ACE.Server/WorldObjects/Player_House.cs @@ -2,8 +2,9 @@ using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.Entity; using ACE.Entity.Enum; using ACE.Entity.Enum.Properties; @@ -31,7 +32,7 @@ partial class Player public void HandleActionBuyHouse(uint slumlord_id, List item_ids) { //Console.WriteLine($"\n{Name}.HandleActionBuyHouse()"); - log.Info($"[HOUSE] {Name}.HandleActionBuyHouse()"); + log.LogInformation("[HOUSE] {Name}.HandleActionBuyHouse()", Name); // verify player doesn't already own a house var houseInstance = GetHouseInstance(); @@ -40,14 +41,14 @@ public void HandleActionBuyHouse(uint slumlord_id, List item_ids) { //Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.HouseAlreadyOwned)); Session.Network.EnqueueSend(new GameMessageSystemChat("You already own a house!", ChatMessageType.Broadcast)); - log.Info($"[HOUSE] {Name}.HandleActionBuyHouse(): Failed pre-purchase requirement - Already owns another house"); + log.LogInformation("[HOUSE] {Name}.HandleActionBuyHouse(): Failed pre-purchase requirement - Already owns another house", Name); return; } var slumlord = (SlumLord)CurrentLandblock.GetObject(slumlord_id); if (slumlord == null) { - log.Error($"[HOUSE] {Name}.HandleActionBuyHouse: Couldn't find slumlord 0x{slumlord_id:X8}!"); + log.LogError("[HOUSE] {Name}.HandleActionBuyHouse: Couldn't find slumlord 0x{Slumlord_id:X8}!", Name, slumlord_id); return; } @@ -57,7 +58,7 @@ public void HandleActionBuyHouse(uint slumlord_id, List item_ids) if (playerLevel < slumlord.MinLevel) { Session.Network.EnqueueSend(new GameEventWeenieErrorWithString(Session, WeenieErrorWithString.YouMustBeAboveLevel_ToBuyHouse, slumlord.MinLevel.ToString())); - log.Info($"[HOUSE] {Name}.HandleActionBuyHouse(): Failed pre-purchase requirement - MinLevel"); + log.LogInformation("[HOUSE] {Name}.HandleActionBuyHouse(): Failed pre-purchase requirement - MinLevel", Name); return; } } @@ -67,7 +68,7 @@ public void HandleActionBuyHouse(uint slumlord_id, List item_ids) if (Allegiance == null || Allegiance.MonarchId != Guid.Full) { Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.YouMustBeMonarchToPurchaseDwelling)); - log.Info($"[HOUSE] {Name}.HandleActionBuyHouse(): Failed pre-purchase requirement - HouseRequiresMonarch"); + log.LogInformation("[HOUSE] {Name}.HandleActionBuyHouse(): Failed pre-purchase requirement - HouseRequiresMonarch", Name); return; } } @@ -81,7 +82,7 @@ public void HandleActionBuyHouse(uint slumlord_id, List item_ids) if (allegianceMinLevel > 0 && (Allegiance == null || AllegianceNode.Rank < allegianceMinLevel)) { Session.Network.EnqueueSend(new GameEventWeenieErrorWithString(Session, WeenieErrorWithString.YouMustBeAboveAllegianceRank_ToBuyHouse, allegianceMinLevel.ToString())); - log.Info($"[HOUSE] {Name}.HandleActionBuyHouse(): Failed pre-purchase requirement - AllegianceMinLevel"); + log.LogInformation("[HOUSE] {Name}.HandleActionBuyHouse(): Failed pre-purchase requirement - AllegianceMinLevel", Name); return; } } @@ -95,7 +96,7 @@ public void HandleActionBuyHouse(uint slumlord_id, List item_ids) { var msg = "Your account must be at least 15 days old to purchase this dwelling. This applies to all housing except apartments."; Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, msg), new GameMessageSystemChat(msg, ChatMessageType.Broadcast)); - log.Info($"[HOUSE] {Name}.HandleActionBuyHouse(): Failed pre-purchase requirement - house_15day_account"); + log.LogInformation("[HOUSE] {Name}.HandleActionBuyHouse(): Failed pre-purchase requirement - house_15day_account", Name); return; } } @@ -111,7 +112,7 @@ public void HandleActionBuyHouse(uint slumlord_id, List item_ids) if (lastPurchaseTimePlus30 > DateTime.UtcNow) { Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.YouMustWaitToPurchaseHouse)); - log.Info($"[HOUSE] {Name}.HandleActionBuyHouse(): Failed pre-purchase requirement - house_30day_cooldown"); + log.LogInformation("[HOUSE] {Name}.HandleActionBuyHouse(): Failed pre-purchase requirement - house_30day_cooldown", Name); return; } } @@ -120,12 +121,12 @@ public void HandleActionBuyHouse(uint slumlord_id, List item_ids) var verified = VerifyPurchase(slumlord, item_ids); if (!verified) { - log.Warn($"[HOUSE] {Name} tried to purchase house {slumlord.Guid} without the required items!"); + log.LogWarning("[HOUSE] {Name} tried to purchase house {Guid} without the required items!", Name, slumlord.Guid); return; } //Console.WriteLine("\nInventory check passed!"); - log.Info($"[HOUSE] {Name}.HandleActionBuyHouse(): Inventory check passed!"); + log.LogInformation("[HOUSE] {Name}.HandleActionBuyHouse(): Inventory check passed!", Name); // get the list of items / amounts to consume for purchase var houseProfile = slumlord.GetHouseProfile(); @@ -138,7 +139,7 @@ public void HandleActionBuyHouse(uint slumlord_id, List item_ids) var item_id_list = string.Join(", ", item_ids.Select(i => i.ToString("X8"))); var consumeItemsList = string.Join(", ", consumeItems.Select(i => $"{i.Name} ({i.Guid}) x{i.Value}")); - log.ErrorFormat("[HOUSE] {0}.HandleActionBuyHouse({1:X8}, {2}) - TryConsumePurchaseItems failed with {3}", Name, slumlord_id, item_id_list, consumeItemsList); + log.LogError("[HOUSE] {Name}.HandleActionBuyHouse({Slumlord_id:X8}, {Item_id_list}) - TryConsumePurchaseItems failed with {ConsumeItemsList}", Name, slumlord_id, item_id_list, consumeItemsList); return; } @@ -162,7 +163,7 @@ public void GiveDeed(SlumLord slumLord) if (location == null) { if (!HouseManager.ApartmentBlocks.TryGetValue(slumLord.Location.Landblock, out location)) - log.ErrorFormat("{0}.GiveDeed() - couldn't find location {1}", Name, slumLord.Location.ToLOCString()); + log.LogError("{Name}.GiveDeed() - couldn't find location {Location}", Name, slumLord.Location.ToLOCString()); } deed.LongDesc = $"Bought by {Name}{titleStr} on {date} at {time}\n\nPurchased at {location}"; @@ -178,7 +179,7 @@ public void RemoveDeed() var deeds = GetInventoryItemsOfWCID(9549); if (deeds == null) { - log.Warn($"[HOUSE] {Name}.RemoveDeed(): couldn't find inventory deed"); + log.LogWarning("[HOUSE] {Name}.RemoveDeed(): couldn't find inventory deed", Name); return; } foreach (var deed in deeds) @@ -188,12 +189,12 @@ public void RemoveDeed() public void HandleActionRentHouse(uint slumlord_id, List item_ids) { //Console.WriteLine($"{Name}.HandleActionRentHouse({slumlord_id:X8}, {string.Join(", ", item_ids.Select(i => i.ToString("X8")))})"); - log.Info($"[HOUSE] {Name}.HandleActionRentHouse({slumlord_id:X8}, {string.Join(", ", item_ids.Select(i => i.ToString("X8")))})"); + log.LogInformation("[HOUSE] {Name}.HandleActionRentHouse({Slumlord_id:X8}, {Join})", Name, slumlord_id, string.Join(", ", item_ids.Select(i => i.ToString("X8")))); var slumlord = FindObject(slumlord_id, SearchLocations.Landblock) as SlumLord; if (slumlord == null) { - log.Warn($"[HOUSE] {Name}.HandleActionRentHouse({slumlord_id:X8}): Could not find SlumLord in world."); + log.LogWarning("[HOUSE] {Name}.HandleActionRentHouse({Slumlord_id:X8}): Could not find SlumLord in world.", Name, slumlord_id); return; } @@ -202,7 +203,7 @@ public void HandleActionRentHouse(uint slumlord_id, List item_ids) //Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.HouseRentFailed)); // WeenieError.HouseRentFailed == blank message Session.Network.EnqueueSend(new GameMessageSystemChat("The maintenance has already been paid for this period.\nYou may not prepay next period's maintenance.", ChatMessageType.Broadcast)); - log.Info($"[HOUSE] {Name}.HandleActionRentHouse({slumlord_id:X8}): The maintenance has already been paid for this period."); + log.LogInformation("[HOUSE] {Name}.HandleActionRentHouse({Slumlord_id:X8}): The maintenance has already been paid for this period.", Name, slumlord_id); return; } @@ -218,12 +219,12 @@ public void HandleActionRentHouse(uint slumlord_id, List item_ids) { Session.Network.EnqueueSend(new GameMessageSystemChat("The owner of this house currently owns multiple houses. Maintenance cannot be paid until they only own 1 house.", ChatMessageType.Broadcast)); - log.Info($"[HOUSE] {Name}.HandleActionRentHouse({slumlord_id:X8}): The owner of this house currently owns multiple houses. Maintenance cannot be paid until they only own 1 house."); + log.LogInformation("[HOUSE] {Name}.HandleActionRentHouse({Slumlord_id:X8}): The owner of this house currently owns multiple houses. Maintenance cannot be paid until they only own 1 house.", Name, slumlord_id); return; } } else - log.ErrorFormat("[HOUSE] {0}.HandleActionRentHouse({1:X8}): couldn't find house owner {2}", Name, slumlord_id, slumlord.HouseOwner); + log.LogError("[HOUSE] {Name}.HandleActionRentHouse({Slumlord_id:X8}): couldn't find house owner {HouseOwner}", Name, slumlord_id, slumlord.HouseOwner); var logLine = $"[HOUSE] HandleActionRentHouse:" + Environment.NewLine; @@ -264,7 +265,7 @@ public void HandleActionRentHouse(uint slumlord_id, List item_ids) } //Console.WriteLine(); logLine += Environment.NewLine; - log.Info(logLine); + log.LogInformation("{Message:l}", logLine); // filter to items found in player's inventory var items = GetInventoryItems(item_ids); @@ -284,7 +285,7 @@ public void HandleActionRentHouse(uint slumlord_id, List item_ids) if (consumeItems.Count == 0) { - log.Warn($"[HOUSE] {Name}.HandleActionRentHouse({slumlord_id:X8}): Nothing sent could be transferred to slumlord for rent."); + log.LogWarning("[HOUSE] {Name}.HandleActionRentHouse({Slumlord_id:X8}): Nothing sent could be transferred to slumlord for rent.", Name, slumlord_id); return; } @@ -307,7 +308,7 @@ public void HandleActionRentHouse(uint slumlord_id, List item_ids) Session.Network.EnqueueSend(new GameMessageSystemChat(maintenanceStatus, ChatMessageType.Broadcast)); - log.Info($"[HOUSE] {Name}.HandleActionRentHouse({slumlord_id:X8}): {maintenanceStatus}"); + log.LogInformation("[HOUSE] {Name}.HandleActionRentHouse({Slumlord_id:X8}): {MaintenanceStatus}", Name, slumlord_id, maintenanceStatus); } /// @@ -324,7 +325,7 @@ public List GetInventoryItems(List item_ids) if (item != null) inventoryItems.Add(item); else - log.ErrorFormat("{0}.GetInventoryItems() - couldn't find {1:X8}", Name, item_id); + log.LogError("{Name}.GetInventoryItems() - couldn't find {Item_id:X8}", Name, item_id); } return inventoryItems; @@ -353,7 +354,7 @@ public bool TryConsumeItemForRent(SlumLord slumlord, WorldObjectInfo itemIn var item = itemInfo.TryGetWorldObject(); if (item == null) { - log.Error($"[HOUSE] {Name}.TryConsumeItemForRent({itemInfo.Guid:X8}) - couldn't get item"); + log.LogError("[HOUSE] {Name}.TryConsumeItemForRent({Guid:X8}) - couldn't get item", Name, itemInfo.Guid); return false; } @@ -362,7 +363,7 @@ public bool TryConsumeItemForRent(SlumLord slumlord, WorldObjectInfo itemIn if (amount > stackSize) { - log.Error($"[HOUSE] {Name}.TryConsumeItemForRent({item.Name} ({item.Guid}) - amount {amount} > stacksize {stackSize}"); + log.LogError("[HOUSE] {Name}.TryConsumeItemForRent({ItemName} ({Guid}) - amount {Amount} > stacksize {StackSize}", Name, item.Name, item.Guid, amount, stackSize); return false; } @@ -384,25 +385,25 @@ public bool TryMoveItemForRent(SlumLord slumlord, WorldObject item) // verify slumlord can add item to inventory if (!slumlord.CanAddToInventory(item)) { - log.Error($"[HOUSE] {Name}.TryMoveItemForRent({slumlord.Name} ({slumlord.Guid}), {item.Name} ({item.Guid}) ) - CanAddToInventory failed!"); + log.LogError("[HOUSE] {Name}.TryMoveItemForRent({SlumlordName} ({SlumlordGuid}), {ItemName} ({ItemGuid}) ) - CanAddToInventory failed!", Name, slumlord.Name, slumlord.Guid, item.Name, item.Guid); return false; } // remove entire item from player's inventory if (!TryRemoveFromInventoryWithNetworking(item.Guid, out _, RemoveFromInventoryAction.SpendItem)) { - log.Error($"[HOUSE] {Name}.TryMoveItemForRent({slumlord.Name} ({slumlord.Guid}), {item.Name} ({item.Guid}) ) - TryRemoveFromInventoryWithNetworking failed!"); + log.LogError("[HOUSE] {Name}.TryMoveItemForRent({SlumlordName} ({SlumlordGuid}), {ItemName} ({ItemGuid}) ) - TryRemoveFromInventoryWithNetworking failed!", Name, slumlord.Name, slumlord.Guid, item.Name, item.Guid); return false; } // add to slumlord inventory if (!slumlord.TryAddToInventory(item)) { - log.Error($"[HOUSE] {Name}.TryMoveItemForRent({slumlord.Name} ({slumlord.Guid}), {item.Name} ({item.Guid}) ) - TryAddToInventory failed!"); + log.LogError("[HOUSE] {Name}.TryMoveItemForRent({SlumlordName} ({SlumlordGuid}), {ItemName} ({ItemGuid}) ) - TryAddToInventory failed!", Name, slumlord.Name, slumlord.Guid, item.Name, item.Guid); return false; } - log.InfoFormat("[HOUSE] {0}.TryMoveItemForRent({1} ({2}), {3}{4} ({5})) - Successfully moved to Slumlord.", Name, slumlord.Name, slumlord.Guid, ((item.StackSize ?? 1) > 1 ? $"{item.StackSize}x " : ""), item.Name, item.Guid); + log.LogInformation("[HOUSE] {Name}.TryMoveItemForRent({SlumlordName} ({SlumlordGuid}), {StackPrefix}{ItemName} ({ItemGuid})) - Successfully moved to Slumlord.", Name, slumlord.Name, slumlord.Guid, ((item.StackSize ?? 1) > 1 ? $"{item.StackSize}x " : ""), item.Name, item.Guid); return true; } @@ -418,7 +419,7 @@ public bool TrySplitItemForRent(SlumLord slumlord, WorldObject item, int amount) // verify it can be added to slumlord's inventory if (!slumlord.CanAddToInventory(newItem)) { - log.Error($"[HOUSE] {Name}.TrySplitItemForRent({slumlord.Name} ({slumlord.Guid}), {item.Name} ({item.Guid}), {amount}) - CanAddToInventory failed for split item {newItem.Name} ({newItem.Guid})!"); + log.LogError("[HOUSE] {Name}.TrySplitItemForRent({SlumlordName} ({SlumlordGuid}), {ItemName} ({ItemGuid}), {Amount}) - CanAddToInventory failed for split item {NewItemName} ({NewItemGuid})!", Name, slumlord.Name, slumlord.Guid, item.Name, item.Guid, amount, newItem.Name, newItem.Guid); newItem.Destroy(); return false; } @@ -426,7 +427,7 @@ public bool TrySplitItemForRent(SlumLord slumlord, WorldObject item, int amount) // fetch container for AdjustStack if (GetInventoryItem(item.Guid, out var container) == null) { - log.Error($"[HOUSE] {Name}.TrySplitItemForRent({slumlord.Name} ({slumlord.Guid}), {item.Name} ({item.Guid}), {amount}) - GetInventoryItem failed!"); + log.LogError("[HOUSE] {Name}.TrySplitItemForRent({SlumlordName} ({SlumlordGuid}), {ItemName} ({ItemGuid}), {Amount}) - GetInventoryItem failed!", Name, slumlord.Name, slumlord.Guid, item.Name, item.Guid, amount); newItem.Destroy(); return false; } @@ -434,7 +435,7 @@ public bool TrySplitItemForRent(SlumLord slumlord, WorldObject item, int amount) // subtract amount from player's item stacksize if (!AdjustStack(item, -amount, container, this)) { - log.Error($"[HOUSE] {Name}.TrySplitItemForRent({slumlord.Name} ({slumlord.Guid}), {item.Name} ({item.Guid}), {amount}) - failed to adjust stack!"); + log.LogError("[HOUSE] {Name}.TrySplitItemForRent({SlumlordName} ({SlumlordGuid}), {ItemName} ({ItemGuid}), {Amount}) - failed to adjust stack!", Name, slumlord.Name, slumlord.Guid, item.Name, item.Guid, amount); newItem.Destroy(); return false; } @@ -451,12 +452,12 @@ public bool TrySplitItemForRent(SlumLord slumlord, WorldObject item, int amount) if (!slumlord.TryAddToInventory(newItem)) { - log.Error($"[HOUSE] {Name}.TrySplitItemForRent({slumlord.Name} ({slumlord.Guid}), {item.Name} ({item.Guid}), {amount}) - TryAddToInventory failed for split item {newItem.Name} ({newItem.Guid})!"); + log.LogError("[HOUSE] {Name}.TrySplitItemForRent({SlumlordName} ({SlumlordGuid}), {ItemName} ({ItemGuid}), {Amount}) - TryAddToInventory failed for split item {NewItemName} ({NewItemGuid})!", Name, slumlord.Name, slumlord.Guid, item.Name, item.Guid, amount, newItem.Name, newItem.Guid); newItem.Destroy(); return false; } - log.Info($"[HOUSE] {Name}.TrySplitItemForRent({slumlord.Name} ({slumlord.Guid}), {item.Name} ({item.Guid}), {amount}) - Created new item {((newItem.StackSize ?? 1) > 1 ? $"{newItem.StackSize}x " : "")}{newItem.Name} ({newItem.Guid}) and moved to Slumlord."); + log.LogInformation("[HOUSE] {Name}.TrySplitItemForRent({SlumlordName} ({SlumlordGuid}), {ItemName} ({ItemGuid}), {Amount}) - Created new item {StackPrefix}{NewItemName} ({NewItemGuid}) and moved to Slumlord.", Name, slumlord.Name, slumlord.Guid, item.Name, item.Guid, amount, ((newItem.StackSize ?? 1) > 1 ? $"{newItem.StackSize}x " : ""), newItem.Name, newItem.Guid); // force save of new slumlord stack newItem.SaveBiotaToDatabase(); @@ -467,7 +468,7 @@ public bool TrySplitItemForRent(SlumLord slumlord, WorldObject item, int amount) public void HandleActionAbandonHouse() { //Console.WriteLine($"\n{Name}.HandleActionAbandonHouse()"); - log.Info($"[HOUSE] {Name}.HandleActionAbandonHouse()"); + log.LogInformation("[HOUSE] {Name}.HandleActionAbandonHouse()", Name); var houseInstance = GetHouseInstance(); @@ -621,7 +622,7 @@ public void SetHouseOwner(SlumLord slumlord) var house = slumlord.House; //Console.WriteLine($"Setting {Name} as owner of {house.Name}"); - log.Info($"[HOUSE] Setting {Name} (0x{Guid}) as owner of {house.Name} (0x{house.Guid:X8})"); + log.LogInformation("[HOUSE] Setting {Name} (0x{Guid}) as owner of {HouseName} (0x{HouseGuid:X8})", Name, Guid, house.Name, house.Guid); // set player properties HouseId = house.HouseId; @@ -699,7 +700,7 @@ public bool TryConsumePurchaseItems(List> purchaseItems) if (item == null) { // this should never happen, due to previous verifications - log.Error($"[HOUSE] {Name}.ConsumeItemsForHousePurchase(): couldn't find {purchaseItem.Guid}!"); + log.LogError("[HOUSE] {Name}.ConsumeItemsForHousePurchase(): couldn't find {Guid}!", Name, purchaseItem.Guid); return false; } @@ -709,14 +710,14 @@ public bool TryConsumePurchaseItems(List> purchaseItems) if (amount > stackSize) { // this should also never happen, due to previous checks - log.Error($"[HOUSE] {Name}.ConsumeItemsForHousePurchase(): {item.Name} ({item.Guid}) amount({amount}) > stackSize({stackSize})!"); + log.LogError("[HOUSE] {Name}.ConsumeItemsForHousePurchase(): {ItemName} ({Guid}) amount({Amount}) > stackSize({StackSize})!", Name, item.Name, item.Guid, amount, stackSize); return false; } if (!TryConsumeFromInventoryWithNetworking(item, amount)) { // all of these things should never happen, just being absolutely certain... - log.Error($"[HOUSE] {Name}.ConsumeItemsForHousePurchase(): TryConsumeFromInventoryWithNetworking({item.Name} ({item.Guid}), {amount}) failed!"); + log.LogError("[HOUSE] {Name}.ConsumeItemsForHousePurchase(): TryConsumeFromInventoryWithNetworking({ItemName} ({Guid}), {Amount}) failed!", Name, item.Name, item.Guid, amount); return false; } @@ -774,7 +775,7 @@ public bool VerifyPurchase(SlumLord slumlord, List item_ids) } //Console.WriteLine(); logLine += Environment.NewLine; - log.Info(logLine); + log.LogInformation("{Message:l}", logLine); // compare list of input items // to required items for purchase @@ -811,7 +812,7 @@ public bool HasItem(List sentItems, WorldObject buyItem) { var stackStr = buyItem.StackSize != null && buyItem.StackSize > 1 ? buyItem.StackSize.ToString() + " " : ""; //Console.WriteLine($"Checking for item: {stackStr}{buyItem.Name}"); - log.Info($"[HOUSE] Checking for item: {stackStr}{buyItem.Name}"); + log.LogInformation("[HOUSE] Checking for item: {StackStr}{Name}", stackStr, buyItem.Name); // get all items of this wcid from inventory var itemMatches = sentItems.Where(i => i.WeenieClassId == buyItem.WeenieClassId).ToList(); @@ -820,14 +821,14 @@ public bool HasItem(List sentItems, WorldObject buyItem) if (itemMatches.Count == 0) { //Console.WriteLine("No matching items found."); - log.Info($"[HOUSE] No matching items found."); + log.LogInformation("[HOUSE] No matching items found."); return false; } var required = buyItem.StackSize ?? 1; if (totalStack < required) { //Console.WriteLine($"Found {totalStack} items, requires {required}."); - log.Info($"[HOUSE] Found {totalStack} items, requires {required}."); + log.LogInformation("[HOUSE] Found {TotalStack} items, requires {Required}.", totalStack, required); return false; } return true; @@ -841,7 +842,7 @@ public bool HasItem(List sentItems, WorldObject buyItem) public bool HasCurrency(List sentItems, uint amount, bool useTradeNotes = true) { //Console.WriteLine($"Checking for currency: {amount}"); - log.Info($"[HOUSE] Checking for currency: {amount}"); + log.LogInformation("[HOUSE] Checking for currency: {Amount}", amount); var totalCurrency = GetTotalCurrency(sentItems, useTradeNotes); return totalCurrency >= amount; } @@ -854,13 +855,13 @@ public uint GetTotalCurrency(List sentItems, bool useTradeNotes = t { var totalPyreals = GetTotalPyreals(sentItems); //Console.WriteLine($"Total pyreals: {totalPyreals}"); - log.Info($"[HOUSE] Total pyreals: {totalPyreals}"); + log.LogInformation("[HOUSE] Total pyreals: {TotalPyreals}", totalPyreals); if (!useTradeNotes) return totalPyreals; var totalTradeNotes = GetTotalTradeNotes(sentItems); //Console.WriteLine($"Total trade notes: {totalTradeNotes}"); - log.Info($"[HOUSE] Total trade notes: {totalTradeNotes}"); + log.LogInformation("[HOUSE] Total trade notes: {TotalTradeNotes}", totalTradeNotes); return totalPyreals + totalTradeNotes; } @@ -1850,7 +1851,7 @@ public void ShowMultiHouseWarning(List houses, string type) var slumlord = house.SlumLord; if (slumlord == null) { - log.Error($"{Name}.IsMultiHouseOwner(): {house.Guid} slumlord is null!"); + log.LogError("{Name}.IsMultiHouseOwner(): {Guid} slumlord is null!", Name, house.Guid); continue; } var coords = HouseManager.GetCoords(slumlord.Location); diff --git a/Source/ACE.Server/WorldObjects/Player_Inventory.cs b/Source/ACE.Server/WorldObjects/Player_Inventory.cs index 4c777e87b4..937a12f6b2 100644 --- a/Source/ACE.Server/WorldObjects/Player_Inventory.cs +++ b/Source/ACE.Server/WorldObjects/Player_Inventory.cs @@ -4,7 +4,8 @@ using System.Linq; using System.Threading; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Database; using ACE.DatLoader; using ACE.DatLoader.FileTypes; @@ -730,7 +731,7 @@ private bool AdjustStack(WorldObject stack, int amount, Container container, Con { if (stack.StackSize + amount <= 0 || stack.StackSize + amount > stack.MaxStackSize) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to adjust stack by an invalid amount amount ({4}) 0x{2:X8}:{3}.", Guid.Full, Name, stack.Guid.Full, stack.Name, amount); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to adjust stack by an invalid amount amount ({Amount}) 0x{StackGuid:X8}:{StackName}.", Guid.Full, Name, amount, stack.Guid.Full, stack.Name); return false; } @@ -831,7 +832,7 @@ private bool HandleActionPutItemInContainer_Verify(uint itemGuid, uint container if (!item.Guid.IsDynamic() || item is Creature || item.Stuck) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to move item 0x{2:X8}:{3}.", Guid.Full, Name, item.Guid.Full, item.Name); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to move item 0x{ItemGuid:X8}:{ItemName}.", Guid.Full, Name, item.Guid.Full, item.Name); Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.Stuck)); Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, itemGuid)); return false; @@ -1097,7 +1098,7 @@ public void HandleActionPutItemInContainer(uint itemGuid, uint containerGuid, in if (isFromAPlayerCorpse) { - log.InfoFormat("[CORPSE] {0} (0x{1}) picked up {2} (0x{3}) from {4} (0x{5})", Name, Guid, item.Name, item.Guid, itemRootOwner.Name, itemRootOwner.Guid); + log.LogInformation("[CORPSE] {Name} (0x{Guid}) picked up {ItemName} (0x{ItemGuid}) from {ItemRootOwnerName} (0x{ItemRootOwnerGuid})", Name, Guid, item.Name, item.Guid, itemRootOwner.Name, itemRootOwner.Guid); item.SaveBiotaToDatabase(); } } @@ -1340,7 +1341,7 @@ private bool DoHandleActionPutItemInContainer(WorldObject item, Container itemRo } else if (itemRootOwner == null || !itemRootOwner.TryAddToInventory(item)) { - log.Error($"{Name}.DoHandleActionPutItemInContainer({item.Name} ({item.Guid}), {itemRootOwner?.Name} ({itemRootOwner?.Guid}), {itemWasEquipped}, {container.Name} ({container.Guid}), {containerRootOwner?.Name} ({containerRootOwner?.Guid}), {placement}) - removed item from original location, failed to add to new container, failed to re-add to original location"); + log.LogError("{Name}.DoHandleActionPutItemInContainer({ItemName} ({ItemGuid}), {ItemRootOwnerName} ({ItemRootOwnerGuid}), {ItemWasEquipped}, {ContainerName} ({ContainerGuid}), {ContainerRootOwnerName} ({ContainerRootOwnerGuid}), {Placement}) - removed item from original location, failed to add to new container, failed to re-add to original location", Name, item.Name, item.Guid, itemRootOwner?.Name, itemRootOwner?.Guid, itemWasEquipped, container.Name, container.Guid, containerRootOwner?.Name, containerRootOwner?.Guid, placement); } return false; @@ -1461,7 +1462,7 @@ public void HandleActionDropItem(uint itemGuid) Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, item.Guid.Full)); } else - log.Warn($"0x{item.Guid}:{item.Name} for player {Name} lost from HandleActionDropItem failure."); + log.LogWarning("0x{Guid}:{ItemName} for player {Name} lost from HandleActionDropItem failure.", item.Guid, item.Name, Name); } var returnStance = new Motion(CurrentMotionState.Stance); @@ -1546,7 +1547,7 @@ public void HandleActionGetAndWieldItem(uint itemGuid, EquipMask wieldedLocation if (!item.Guid.IsDynamic() || item is Creature || item.Stuck) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to move item 0x{2:X8}:{3}.", Guid.Full, Name, item.Guid.Full, item.Name); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to move item 0x{ItemGuid:X8}:{ItemName}.", Guid.Full, Name, item.Guid.Full, item.Name); Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.Stuck)); Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, itemGuid)); return; @@ -1561,7 +1562,7 @@ public void HandleActionGetAndWieldItem(uint itemGuid, EquipMask wieldedLocation if (!item.ValidLocations.HasValue || item.ValidLocations == EquipMask.None) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to wield item 0x{2:X8}:{3} to {4} (0x{4:X}), not in item's validlocatiions {5} (0x{5:X}).", Guid.Full, Name, item.Guid.Full, item.Name, wieldedLocation, item.ValidLocations ?? 0); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to wield item 0x{ItemGuid:X8}:{ItemName} to {WieldedLocation} (0x{WieldedLocation:X}), not in item's validlocatiions {ValidLocations} (0x{ValidLocations:X}).", Guid.Full, Name, item.Guid.Full, item.Name, wieldedLocation, wieldedLocation, item.ValidLocations ?? 0, item.ValidLocations ?? 0); Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.InvalidInventoryLocation)); Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, itemGuid)); return; @@ -1633,7 +1634,7 @@ public void HandleActionGetAndWieldItem(uint itemGuid, EquipMask wieldedLocation if (isFromAPlayerCorpse) { - log.InfoFormat("[CORPSE] {0} (0x{1}) picked up and wielded {2} (0x{3}) from {4} (0x{5})", Name, Guid, item.Name, item.Guid, rootOwner.Name, rootOwner.Guid); + log.LogInformation("[CORPSE] {Name} (0x{Guid}) picked up and wielded {ItemName} (0x{ItemGuid}) from {RootOwnerName} (0x{RootOwnerGuid})", Name, Guid, item.Name, item.Guid, rootOwner.Name, rootOwner.Guid); item.SaveBiotaToDatabase(); } } @@ -1753,7 +1754,7 @@ private bool DoHandleActionGetAndWieldItem(WorldObject item, Container fromConta } else { - log.Warn($"{Name} tried to wield {item.Name} ({item.Guid}) in slot {wieldedLocation}, which doesn't match valid slots {item.ValidLocations}"); + log.LogWarning("{Name} tried to wield {ItemName} ({Guid}) in slot {WieldedLocation}, which doesn't match valid slots {ValidLocations}", Name, item.Name, item.Guid, wieldedLocation, item.ValidLocations); Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, item.Guid.Full)); return false; } @@ -1859,7 +1860,7 @@ private bool DoHandleActionGetAndWieldItem(WorldObject item, Container fromConta Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, item.Guid.Full)); // todo: So the item isn't lost, we should try to put the item in the players inventory, or if that's full, on the landblock. - log.WarnFormat("Item 0x{0:X8}:{1} for player {2} lost from DoHandleActionGetAndWieldItem failure.", item.Guid.Full, item.Name, Name); + log.LogWarning("Item 0x{Guid:X8}:{ItemName} for player {Name} lost from DoHandleActionGetAndWieldItem failure.", item.Guid.Full, item.Name, Name); return false; } @@ -1895,7 +1896,7 @@ private bool CheckWeaponCollision(WorldObject item = null, EquipMask? wieldedLoc offhand = GetEquippedOffHand(); if (offhand != null) { - log.Warn($"'{Name}' tried to wield '{item.Name}' ({item.Guid}) in slot {wieldedLocation}, but is occupied by '{offhand.Name}'"); + log.LogWarning("'{Name}' tried to wield '{ItemName}' ({Guid}) in slot {WieldedLocation}, but is occupied by '{OffhandName}'", Name, item.Name, item.Guid, wieldedLocation, offhand.Name); return false; } @@ -1903,7 +1904,7 @@ private bool CheckWeaponCollision(WorldObject item = null, EquipMask? wieldedLoc // Remove any Two Handed, Caster (magic), or Missile Weapons if (mainhand != null && (mainhand.IsTwoHanded || mainhand.IsCaster || mainhand.IsAmmoLauncher)) { - log.Warn($"'{Name}' tried to wield '{item.Name}' ({item.Guid}) in slot {wieldedLocation}, which conflicts with '{mainhand.Name}'"); + log.LogWarning("'{Name}' tried to wield '{ItemName}' ({Guid}) in slot {WieldedLocation}, which conflicts with '{MainhandName}'", Name, item.Name, item.Guid, wieldedLocation, mainhand.Name); return false; } @@ -1914,14 +1915,14 @@ private bool CheckWeaponCollision(WorldObject item = null, EquipMask? wieldedLoc offhand = GetEquippedOffHand(); if (offhand != null && item.IsAmmoLauncher) { - log.Warn($"'{Name}' tried to wield '{item.Name}' ({item.Guid}) in slot {wieldedLocation}, which conflicts with '{offhand.Name}'"); + log.LogWarning("'{Name}' tried to wield '{ItemName}' ({Guid}) in slot {WieldedLocation}, which conflicts with '{OffhandName}'", Name, item.Name, item.Guid, wieldedLocation, offhand.Name); return false; } mainhand = GetEquippedMainHand(); if (mainhand != null) { - log.Warn($"'{Name}' tried to wield '{item.Name}' ({item.Guid}) in slot {wieldedLocation}, which conflicts with '{mainhand.Name}'"); + log.LogWarning("'{Name}' tried to wield '{ItemName}' ({Guid}) in slot {WieldedLocation}, which conflicts with '{MainhandName}'", Name, item.Name, item.Guid, wieldedLocation, mainhand.Name); return false; } @@ -1929,7 +1930,7 @@ private bool CheckWeaponCollision(WorldObject item = null, EquipMask? wieldedLoc ammo = GetEquippedAmmo(); if (item.AmmoType != null && ammo != null && ammo.AmmoType != item.AmmoType) { - log.Warn($"'{Name}' tried to wield '{item.Name}' ({item.Guid}), AmmoType: {item.AmmoType} in slot {wieldedLocation}, which conflicts with ammo of '{ammo.Name}' ({ammo.AmmoType})"); + log.LogWarning("'{Name}' tried to wield '{ItemName}' ({Guid}), AmmoType: {ItemAmmoType} in slot {WieldedLocation}, which conflicts with ammo of '{AmmoName}' ({AmmoAmmoType})", Name, item.Name, item.Guid, item.AmmoType, wieldedLocation, ammo.Name, ammo.AmmoType); return false; } @@ -1939,7 +1940,7 @@ private bool CheckWeaponCollision(WorldObject item = null, EquipMask? wieldedLoc mainhand = GetEquippedMainHand(); if (mainhand != null && mainhand.AmmoType != null && item.AmmoType != null && mainhand.AmmoType != item.AmmoType) { - log.Warn($"'{Name}' tried to wield '{item.Name}' ({item.Guid}), AmmoType: {item.AmmoType} in slot {wieldedLocation}, which conflicts with AmmoType of '{mainhand.Name}' ({mainhand.AmmoType})"); + log.LogWarning("'{Name}' tried to wield '{ItemName}' ({Guid}), AmmoType: {ItemAmmoType} in slot {WieldedLocation}, which conflicts with AmmoType of '{MainhandName}' ({MainhandAmmoType})", Name, item.Name, item.Guid, item.AmmoType, wieldedLocation, mainhand.Name, mainhand.AmmoType); return false; } @@ -1949,7 +1950,7 @@ private bool CheckWeaponCollision(WorldObject item = null, EquipMask? wieldedLoc offhand = GetEquippedOffHand(); if (offhand != null) { - log.Warn($"'{Name}' tried to wield '{item.Name}' ({item.Guid}) in slot {wieldedLocation}, which conflicts with '{offhand.Name}'"); + log.LogWarning("'{Name}' tried to wield '{ItemName}' ({Guid}) in slot {WieldedLocation}, which conflicts with '{OffhandName}'", Name, item.Name, item.Guid, wieldedLocation, offhand.Name); return false; } @@ -1957,7 +1958,7 @@ private bool CheckWeaponCollision(WorldObject item = null, EquipMask? wieldedLoc // Remove anything in the main hand! if (mainhand != null) { - log.Warn($"'{Name}' tried to wield '{item.Name}' ({item.Guid}) in slot {wieldedLocation}, which conflicts with '{mainhand.Name}'"); + log.LogWarning("'{Name}' tried to wield '{ItemName}' ({Guid}) in slot {WieldedLocation}, which conflicts with '{MainhandName}'", Name, item.Name, item.Guid, wieldedLocation, mainhand.Name); return false; } break; @@ -1966,14 +1967,14 @@ private bool CheckWeaponCollision(WorldObject item = null, EquipMask? wieldedLoc offhand = GetEquippedOffHand(); if (offhand != null && (offhand.IsTwoHanded || offhand.IsCaster || offhand.IsAmmoLauncher)) { - log.Warn($"'{Name}' tried to wield '{item.Name}' ({item.Guid}) in slot {wieldedLocation}, which conflicts with '{offhand.Name}'"); + log.LogWarning("'{Name}' tried to wield '{ItemName}' ({Guid}) in slot {WieldedLocation}, which conflicts with '{OffhandName}'", Name, item.Name, item.Guid, wieldedLocation, offhand.Name); return false; } mainhand = GetEquippedMainHand(); if (mainhand != null && (mainhand.IsTwoHanded || mainhand.IsCaster || mainhand.IsAmmoLauncher)) { - log.Warn($"'{Name}' tried to wield '{item.Name}' ({item.Guid}) in slot {wieldedLocation}, which conflicts with '{mainhand.Name}'"); + log.LogWarning("'{Name}' tried to wield '{ItemName}' ({Guid}) in slot {WieldedLocation}, which conflicts with '{MainhandName}'", Name, item.Name, item.Guid, wieldedLocation, mainhand.Name); return false; } break; @@ -1985,7 +1986,7 @@ private bool CheckWeaponCollision(WorldObject item = null, EquipMask? wieldedLoc offhand = GetEquippedOffHand(); if (offhand != null) { - log.Warn($"'{Name}' tried to wield '{item.Name}' ({item.Guid}) in slot {wieldedLocation}, which conflicts with '{offhand.Name}'"); + log.LogWarning("'{Name}' tried to wield '{ItemName}' ({Guid}) in slot {WieldedLocation}, which conflicts with '{OffhandName}'", Name, item.Name, item.Guid, wieldedLocation, offhand.Name); return false; } } @@ -1994,7 +1995,7 @@ private bool CheckWeaponCollision(WorldObject item = null, EquipMask? wieldedLoc mainhand = GetEquippedMainHand(); if (mainhand != null) { - log.Warn($"'{Name}' tried to wield '{item.Name}' ({item.Guid}) in slot {wieldedLocation}, which conflicts with '{mainhand.Name}'"); + log.LogWarning("'{Name}' tried to wield '{ItemName}' ({Guid}) in slot {WieldedLocation}, which conflicts with '{MainhandName}'", Name, item.Name, item.Guid, wieldedLocation, mainhand.Name); return false; } @@ -2002,7 +2003,7 @@ private bool CheckWeaponCollision(WorldObject item = null, EquipMask? wieldedLoc // can only be wielded in NonCombat mode if (combatMode != CombatMode.NonCombat && item.DefaultCombatStyle == null) { - log.Warn($"'{Name}' tried to wield '{item.Name}' ({item.Guid}) in slot {wieldedLocation}, which conflicts with {combatMode} combat mode"); + log.LogWarning("'{Name}' tried to wield '{ItemName}' ({Guid}) in slot {WieldedLocation}, which conflicts with {CombatMode} combat mode", Name, item.Name, item.Guid, wieldedLocation, combatMode); return false; } break; @@ -2024,7 +2025,7 @@ private bool CheckWeaponCollision(WorldObject item = null, EquipMask? wieldedLoc // Can't wield these with anything else! if (mainhand.IsTwoHanded || mainhand.IsAmmoLauncher || mainhand.IsCaster) { - log.Warn($"'{Name}' is illegally wielding '{mainhand.Name}' ({mainhand.Guid}) and {offhand.Name}' ({offhand.Guid})"); + log.LogWarning("'{Name}' is illegally wielding '{MainhandName}' ({MainhandGuid}) and {OffhandName}' ({OffhandGuid})", Name, mainhand.Name, mainhand.Guid, offhand.Name, offhand.Guid); return false; } } @@ -2035,7 +2036,7 @@ private bool CheckWeaponCollision(WorldObject item = null, EquipMask? wieldedLoc ammo = GetEquippedAmmo(); if (ammo != null && ammo.AmmoType != null && mainhand.AmmoType != null && ammo.AmmoType != mainhand.AmmoType) { - log.Warn($"'{Name}' is illegally wielding '{mainhand.Name}' ({mainhand.Guid}) with ammo {ammo.Name}' ({ammo.AmmoType})"); + log.LogWarning("'{Name}' is illegally wielding '{MainhandName}' ({Guid}) with ammo {AmmoName}' ({AmmoType})", Name, mainhand.Name, mainhand.Guid, ammo.Name, ammo.AmmoType); return false; } } @@ -2047,7 +2048,7 @@ private bool CheckWeaponCollision(WorldObject item = null, EquipMask? wieldedLoc if (mainhand.DefaultCombatStyle == null) { - log.Warn($"'{Name}' is illegally wielding '{mainhand.Name}' ({mainhand.Guid}) in {combatMode} combat mode"); + log.LogWarning("'{Name}' is illegally wielding '{MainhandName}' ({Guid}) in {CombatMode} combat mode", Name, mainhand.Name, mainhand.Guid, combatMode); return false; } } @@ -2248,7 +2249,7 @@ public void HandleActionStackableSplitToContainer(uint stackId, uint containerId if (amount <= 0) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to split item with invalid amount ({3}) 0x{2:X8}.", Guid.Full, Name, stackId, amount); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to split item with invalid amount ({Amount}) 0x{StackId:X8}.", Guid.Full, Name, amount, stackId); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Split amount not valid!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId)); return; @@ -2266,7 +2267,7 @@ public void HandleActionStackableSplitToContainer(uint stackId, uint containerId if (!stack.Guid.IsDynamic() || stack.Stuck) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to move item 0x{2:X8}:{3}.", Guid.Full, Name, stack.Guid.Full, stack.Name); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to move item 0x{StackGuid:X8}:{StackName}.", Guid.Full, Name, stack.Guid.Full, stack.Name); Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.Stuck)); Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId)); return; @@ -2275,7 +2276,7 @@ public void HandleActionStackableSplitToContainer(uint stackId, uint containerId var isStackable = stack is Stackable; if (!isStackable) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to split an item 0x{2:X8}:{3} that is not stackable.", Guid.Full, Name, stack.Guid.Full, stack.Name); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to split an item 0x{StackGuid:X8}:{StackName} that is not stackable.", Guid.Full, Name, stack.Guid.Full, stack.Name); //Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.Stuck)); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "You cannot split that!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId)); @@ -2305,7 +2306,7 @@ public void HandleActionStackableSplitToContainer(uint stackId, uint containerId if (stack.StackSize == null || stack.StackSize == 0) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to split invalid item 0x{2:X8}:{3}.", Guid.Full, Name, stack.Guid.Full, stack.Name); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to split invalid item 0x{StackGuid:X8}:{StackName}.", Guid.Full, Name, stack.Guid.Full, stack.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Stack not valid!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId)); return; @@ -2313,7 +2314,7 @@ public void HandleActionStackableSplitToContainer(uint stackId, uint containerId if (stack.StackSize <= amount) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to split item with invalid amount ({4}) 0x{2:X8}:{3}.", Guid.Full, Name, stack.Guid.Full, stack.Name, amount); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to split item with invalid amount ({Amount}) 0x{StackGuid:X8}:{StackName}.", Guid.Full, Name, amount, stack.Guid.Full, stack.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Split amount not valid!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId)); return; @@ -2366,7 +2367,7 @@ public void HandleActionStackableSplitToContainer(uint stackId, uint containerId // We make sure the stack is still valid. It could have changed during our movement if (stackOriginalContainer != stack.ContainerId || stack.StackSize <= amount) { - log.DebugFormat("Player 0x{0:X8}:{1} tried to split an item that's no longer valid 0x{2:X8}:{3}.", Guid.Full, Name, stack.Guid.Full, stack.Name); + log.LogDebug("Player 0x{Guid:X8}:{Name} tried to split an item that's no longer valid 0x{StackGuid:X8}:{StackName}.", Guid.Full, Name, stack.Guid.Full, stack.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Split failed!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId, WeenieError.ActionCancelled)); return; @@ -2382,7 +2383,7 @@ public void HandleActionStackableSplitToContainer(uint stackId, uint containerId // We make sure the stack is still valid. It could have changed during our pickup animation if (stackOriginalContainer != stack.ContainerId || stack.StackSize <= amount) { - log.DebugFormat("Player 0x{0:X8}:{1} tried to split an item that's no longer valid 0x{2:X8}:{3}.", Guid.Full, Name, stack.Guid.Full, stack.Name); + log.LogDebug("Player 0x{Guid:X8}:{Name} tried to split an item that's no longer valid 0x{StackGuid:X8}:{StackName}.", Guid.Full, Name, stack.Guid.Full, stack.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Split failed!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId, WeenieError.ActionCancelled)); EnqueuePickupDone(pickupMotion); @@ -2480,7 +2481,7 @@ public void HandleActionStackableSplitTo3D(uint stackId, int amount) { if (amount <= 0) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to split item with invalid amount ({3}) 0x{2:X8}.", Guid.Full, Name, stackId, amount); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to split item with invalid amount ({Amount}) 0x{StackId:X8}.", Guid.Full, Name, amount, stackId); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Split amount not valid!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId)); return; @@ -2498,7 +2499,7 @@ public void HandleActionStackableSplitTo3D(uint stackId, int amount) var isStackable = stack is Stackable; if (!isStackable) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to split an item 0x{2:X8}:{3} that is not stackable.", Guid.Full, Name, stack.Guid.Full, stack.Name); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to split an item 0x{StackGuid:X8}:{StackName} that is not stackable.", Guid.Full, Name, stack.Guid.Full, stack.Name); //Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.Stuck)); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "You cannot split that!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId)); @@ -2507,7 +2508,7 @@ public void HandleActionStackableSplitTo3D(uint stackId, int amount) if (stack.StackSize == null || stack.StackSize == 0) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to split invalid item 0x{2:X8}:{3}.", Guid.Full, Name, stack.Guid.Full, stack.Name); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to split invalid item 0x{StackGuid:X8}:{StackName}.", Guid.Full, Name, stack.Guid.Full, stack.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Stack not valid!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId)); return; @@ -2515,7 +2516,7 @@ public void HandleActionStackableSplitTo3D(uint stackId, int amount) if (stack.StackSize <= amount) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to split item with invalid amount ({4}) 0x{2:X8}:{3}.", Guid.Full, Name, stack.Guid.Full, stack.Name, amount); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to split item with invalid amount ({Amount}) 0x{StackGuid:X8}:{StackName}.", Guid.Full, Name, amount, stack.Guid.Full, stack.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Split amount not valid!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId)); return; @@ -2546,7 +2547,7 @@ public void HandleActionStackableSplitTo3D(uint stackId, int amount) // We make sure the stack is still valid. It could have changed during our pickup animation if (FindObject(stack.Guid, SearchLocations.MyInventory | SearchLocations.MyEquippedItems, out stackFoundInContainer, out stackRootOwner, out _) != stack || stack.StackSize <= amount) { - log.DebugFormat("Player 0x{0:X8}:{1} tried to split an item that's no longer valid 0x{2:X8}:{3}.", Guid.Full, Name, stack.Guid.Full, stack.Name); + log.LogDebug("Player 0x{Guid:X8}:{Name} tried to split an item that's no longer valid 0x{StackGuid:X8}:{StackName}.", Guid.Full, Name, stack.Guid.Full, stack.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Split failed!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId, WeenieError.ActionCancelled)); return; @@ -2592,7 +2593,7 @@ public void HandleActionStackableSplitTo3D(uint stackId, int amount) UpdateCoinValue(); } else - log.WarnFormat("Partial stack 0x{0:X8}:{1} for player {2} lost from HandleActionStackableSplitTo3D failure.", stack.Guid.Full, stack.Name, Name); + log.LogWarning("Partial stack 0x{Guid:X8}:{StackName} for player {Name} lost from HandleActionStackableSplitTo3D failure.", stack.Guid.Full, stack.Name, Name); newStack.Destroy(); } @@ -2610,7 +2611,7 @@ public void HandleActionStackableSplitToWield(uint stackId, EquipMask wieldedLoc if (amount <= 0) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to split item with invalid amount ({3}) 0x{2:X8}.", Guid.Full, Name, stackId, amount); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to split item with invalid amount ({Amount}) 0x{StackId:X8}.", Guid.Full, Name, amount, stackId); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Split amount not valid!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId)); return; @@ -2627,7 +2628,7 @@ public void HandleActionStackableSplitToWield(uint stackId, EquipMask wieldedLoc if (!stack.Guid.IsDynamic() || stack.Stuck) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to move item 0x{2:X8}:{3}.", Guid.Full, Name, stack.Guid.Full, stack.Name); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to move item 0x{StackGuid:X8}:{StackName}.", Guid.Full, Name, stack.Guid.Full, stack.Name); Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.Stuck)); Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId)); return; @@ -2636,7 +2637,7 @@ public void HandleActionStackableSplitToWield(uint stackId, EquipMask wieldedLoc var isStackable = stack is Stackable; if (!isStackable) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to split an item 0x{2:X8}:{3} that is not stackable.", Guid.Full, Name, stack.Guid.Full, stack.Name); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to split an item 0x{StackGuid:X8}:{StackName} that is not stackable.", Guid.Full, Name, stack.Guid.Full, stack.Name); //Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.Stuck)); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "You cannot split that!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId)); @@ -2652,7 +2653,7 @@ public void HandleActionStackableSplitToWield(uint stackId, EquipMask wieldedLoc if (stack.StackSize == null || stack.StackSize == 0) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to split invalid item 0x{2:X8}:{3}.", Guid.Full, Name, stack.Guid.Full, stack.Name); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to split invalid item 0x{StackGuid:X8}:{StackName}.", Guid.Full, Name, stack.Guid.Full, stack.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Stack not valid!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId)); return; @@ -2660,7 +2661,7 @@ public void HandleActionStackableSplitToWield(uint stackId, EquipMask wieldedLoc if (stack.StackSize <= amount) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to split item with invalid amount ({4}) 0x{2:X8}:{3}.", Guid.Full, Name, stack.Guid.Full, stack.Name, amount); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to split item with invalid amount ({Amount}) 0x{StackGuid:X8}:{StackName}.", Guid.Full, Name, amount, stack.Guid.Full, stack.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Split amount not valid!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId)); return; @@ -2680,7 +2681,7 @@ public void HandleActionStackableSplitToWield(uint stackId, EquipMask wieldedLoc if (!stack.ValidLocations.HasValue || stack.ValidLocations == EquipMask.None) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to wield item 0x{2:X8}:{3} to {4} (0x{4:X}), not in item's validlocatiions {5} (0x{5:X}).", Guid.Full, Name, stack.Guid.Full, stack.Name, wieldedLocation, stack.ValidLocations ?? 0); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to wield item 0x{StackGuid:X8}:{StackName} to {WieldedLocation} (0x{WieldedLocation:X}), not in item's validlocatiions {ValidLocations} (0x{ValidLocations:X}).", Guid.Full, Name, stack.Guid.Full, stack.Name, wieldedLocation, wieldedLocation, stack.ValidLocations ?? 0, stack.ValidLocations ?? 0); Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.InvalidInventoryLocation)); Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId)); return; @@ -2718,7 +2719,7 @@ public void HandleActionStackableSplitToWield(uint stackId, EquipMask wieldedLoc // We make sure the stack is still valid. It could have changed during our movement if (stackOriginalContainer != stack.ContainerId || stack.StackSize <= amount) { - log.DebugFormat("Player 0x{0:X8}:{1} tried to split an item that's no longer valid 0x{2:X8}:{3}.", Guid.Full, Name, stack.Guid.Full, stack.Name); + log.LogDebug("Player 0x{Guid:X8}:{Name} tried to split an item that's no longer valid 0x{StackGuid:X8}:{StackName}.", Guid.Full, Name, stack.Guid.Full, stack.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Split failed!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId, WeenieError.ActionCancelled)); return; @@ -2734,7 +2735,7 @@ public void HandleActionStackableSplitToWield(uint stackId, EquipMask wieldedLoc // We make sure the stack is still valid. It could have changed during our pickup animation if (stackOriginalContainer != stack.ContainerId || stack.StackSize <= amount) { - log.DebugFormat("Player 0x{0:X8}:{1} tried to split an item that's no longer valid 0x{2:X8}:{3}.", Guid.Full, Name, stack.Guid.Full, stack.Name); + log.LogDebug("Player 0x{Guid:X8}:{Name} tried to split an item that's no longer valid 0x{StackGuid:X8}:{StackName}.", Guid.Full, Name, stack.Guid.Full, stack.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Split failed!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, stackId, WeenieError.ActionCancelled)); EnqueuePickupDone(pickupMotion); @@ -2792,7 +2793,7 @@ public void HandleActionStackableSplitToWield(uint stackId, EquipMask wieldedLoc Session.Network.EnqueueSend(new GameMessageSetStackSize(stack)); } else - log.WarnFormat("Partial stack 0x{0:X8}:{1} for player {2} lost from HandleActionStackableSplitToWield failure.", stack.Guid.Full, stack.Name, Name); + log.LogWarning("Partial stack 0x{Guid:X8}:{StackName} for player {Name} lost from HandleActionStackableSplitToWield failure.", stack.Guid.Full, stack.Name, Name); newStack.Destroy(); } @@ -2838,7 +2839,7 @@ public void HandleActionStackableSplitToWield(uint stackId, EquipMask wieldedLoc Session.Network.EnqueueSend(new GameMessageSetStackSize(stack)); } else - log.WarnFormat("Partial stack 0x{0:X8}:{1} for player {2} lost from HandleActionStackableSplitToWield failure.", stack.Guid.Full, stack.Name, Name); + log.LogWarning("Partial stack 0x{Guid:X8}:{StackName} for player {Name} lost from HandleActionStackableSplitToWield failure.", stack.Guid.Full, stack.Name, Name); newStack.Destroy(); } @@ -2863,7 +2864,7 @@ public void HandleActionStackableMerge(uint mergeFromGuid, uint mergeToGuid, int if (amount <= 0) { - log.WarnFormat("Player 0x{0}:{1} tried to merge item with invalid amount ({3}) 0x{2:X8}.", Guid.Full, Name, mergeFromGuid, amount); + log.LogWarning("Player 0x{Guid}:{Name} tried to merge item with invalid amount ({Amount}) 0x{MergeFromGuid:X8}.", Guid.Full, Name, amount, mergeFromGuid); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Merge amount not valid!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, mergeFromGuid)); return; @@ -2881,7 +2882,7 @@ public void HandleActionStackableMerge(uint mergeFromGuid, uint mergeToGuid, int if (!sourceStack.Guid.IsDynamic() || sourceStack.Stuck) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to move item 0x{2:X8}:{3}.", Guid.Full, Name, sourceStack.Guid.Full, sourceStack.Name); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to move item 0x{SourceStackGuid:X8}:{SourceStackName}.", Guid.Full, Name, sourceStack.Guid.Full, sourceStack.Name); Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.Stuck)); Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, mergeFromGuid)); return; @@ -2903,7 +2904,7 @@ public void HandleActionStackableMerge(uint mergeFromGuid, uint mergeToGuid, int if (!targetStack.Guid.IsDynamic() || targetStack.Stuck) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to move item 0x{2:X8}:{3}.", Guid.Full, Name, targetStack.Guid.Full, targetStack.Name); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to move item 0x{TargetStackGuid:X8}:{TargetStackName}.", Guid.Full, Name, targetStack.Guid.Full, targetStack.Name); Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.Stuck)); Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, mergeToGuid)); return; @@ -2923,12 +2924,12 @@ public void HandleActionStackableMerge(uint mergeFromGuid, uint mergeToGuid, int Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "You cannot merge those items!")); // Custom error message if (!sourceIsStackable) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to merge an item 0x{2:X8}:{3} that is not stackable.", Guid.Full, Name, sourceStack.Guid.Full, sourceStack.Name); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to merge an item 0x{SourceStackGuid:X8}:{SourceStackName} that is not stackable.", Guid.Full, Name, sourceStack.Guid.Full, sourceStack.Name); Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, mergeFromGuid)); } else { - log.WarnFormat("Player 0x{0:X8}:{1} tried to merge an item 0x{2:X8}:{3} that is not stackable.", Guid.Full, Name, targetStack.Guid.Full, targetStack.Name); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to merge an item 0x{TargetStackGuid:X8}:{TargetStackName} that is not stackable.", Guid.Full, Name, targetStack.Guid.Full, targetStack.Name); Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, mergeToGuid)); } return; @@ -2936,7 +2937,7 @@ public void HandleActionStackableMerge(uint mergeFromGuid, uint mergeToGuid, int if (sourceStack.WeenieClassId != targetStack.WeenieClassId) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to merge different items 0x{2:X8}:{3} and 0x{4:X8}:{5}.", Guid.Full, Name, sourceStack.Guid.Full, sourceStack.Name, targetStack.Guid.Full, targetStack.Name); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to merge different items 0x{SourceStackGuid:X8}:{SourceStackName} and 0x{TargetStackGuid:X8}:{TargetStackName}.", Guid.Full, Name, sourceStack.Guid.Full, sourceStack.Name, targetStack.Guid.Full, targetStack.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Stacks not compatible!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, mergeFromGuid, WeenieError.YouCannotMergeDifferentStacks)); return; @@ -2944,7 +2945,7 @@ public void HandleActionStackableMerge(uint mergeFromGuid, uint mergeToGuid, int if (sourceStack.StackSize == null || sourceStack.StackSize == 0) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to merge invalid source item 0x{2:X8}:{3}.", Guid.Full, Name, sourceStack.Guid.Full, sourceStack.Name); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to merge invalid source item 0x{SourceStackGuid:X8}:{SourceStackName}.", Guid.Full, Name, sourceStack.Guid.Full, sourceStack.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Stack not valid!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, mergeFromGuid)); return; @@ -2952,7 +2953,7 @@ public void HandleActionStackableMerge(uint mergeFromGuid, uint mergeToGuid, int if (targetStack.StackSize == null || targetStack.StackSize == 0 || targetStack.StackSize == targetStack.MaxStackSize) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to merge invalid target item 0x{2:X8}:{3}.", Guid.Full, Name, targetStack.Guid.Full, targetStack.Name); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to merge invalid target item 0x{TargetStackGuid:X8}:{TargetStackName}.", Guid.Full, Name, targetStack.Guid.Full, targetStack.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Target not valid!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, mergeFromGuid)); return; @@ -2960,7 +2961,7 @@ public void HandleActionStackableMerge(uint mergeFromGuid, uint mergeToGuid, int if (sourceStack.StackSize < amount) { - log.WarnFormat("Player 0x{0}:{1} tried to merge item with invalid amount ({4}) 0x{2:X8}:{3}.", Guid.Full, Name, sourceStack.Guid.Full, sourceStack.Name, amount); + log.LogWarning("Player 0x{Guid}:{Name} tried to merge item with invalid amount ({Amount}) 0x{SourceStackGuid:X8}:{SourceStackName}.", Guid.Full, Name, amount, sourceStack.Guid.Full, sourceStack.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Merge amount not valid!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, mergeFromGuid)); return; @@ -3027,7 +3028,7 @@ public void HandleActionStackableMerge(uint mergeFromGuid, uint mergeToGuid, int // We make sure the stack is still valid. It could have changed during our movement if (sourceStackOriginalContainer != sourceStack.ContainerId || sourceStack.StackSize < amount) { - log.DebugFormat("Player 0x{0}:{1} tried to merge an item that's no longer valid 0x{2:X8}:{3}.", Guid.Full, Name, sourceStack.Guid.Full, sourceStack.Name); + log.LogDebug("Player 0x{Guid}:{Name} tried to merge an item that's no longer valid 0x{SourceStackGuid:X8}:{SourceStackName}.", Guid.Full, Name, sourceStack.Guid.Full, sourceStack.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Merge Failed!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, mergeFromGuid, WeenieError.ActionCancelled)); return; @@ -3043,7 +3044,7 @@ public void HandleActionStackableMerge(uint mergeFromGuid, uint mergeToGuid, int // We make sure the stack is still valid. It could have changed during our pickup animation if (sourceStackOriginalContainer != sourceStack.ContainerId || sourceStack.StackSize < amount) { - log.DebugFormat("Player 0x{0}:{1} tried to merge an item that's no longer valid 0x{2:X8}:{3}.", Guid.Full, Name, sourceStack.Guid.Full, sourceStack.Name); + log.LogDebug("Player 0x{Guid}:{Name} tried to merge an item that's no longer valid 0x{SourceStackGuid:X8}:{SourceStackName}.", Guid.Full, Name, sourceStack.Guid.Full, sourceStack.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Merge Failed!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, mergeFromGuid, WeenieError.ActionCancelled)); EnqueuePickupDone(pickupMotion); @@ -3180,7 +3181,7 @@ private bool DoHandleActionStackableMerge(WorldObject sourceStack, WorldObject t if (isFromAPlayerCorpse) { - log.Info($"[CORPSE] {Name} (0x{Guid}) merged {amount:N0} {(sourceStack.IsDestroyed ? $"which resulted in the destruction" : $"leaving behind {sourceStack.StackSize:N0}")} of {sourceStack.Name} (0x{sourceStack.Guid}) to {targetStack.Name} (0x{targetStack.Guid}) from {sourceStackRootOwner.Name} (0x{sourceStackRootOwner.Guid})"); + log.LogInformation("[CORPSE] {Name} (0x{Guid}) merged {Amount:N0} {StackOutcome} of {SourceStackName} (0x{SourceStackGuid}) to {TargetStackName} (0x{TargetStackGuid}) from {SourceStackRootOwnerName} (0x{SourceStackRootOwnerGuid})", Name, Guid, amount, (sourceStack.IsDestroyed ? $"which resulted in the destruction" : $"leaving behind {sourceStack.StackSize:N0}"), sourceStack.Name, sourceStack.Guid, targetStack.Name, targetStack.Guid, sourceStackRootOwner.Name, sourceStackRootOwner.Guid); targetStack.SaveBiotaToDatabase(); } @@ -3209,7 +3210,7 @@ public void HandleActionGiveObjectRequest(uint targetGuid, uint itemGuid, int am if (amount <= 0) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to give item with invalid amount ({3}) 0x{2:X8}.", Guid.Full, Name, itemGuid, amount); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to give item with invalid amount ({Amount}) 0x{ItemGuid:X8}.", Guid.Full, Name, amount, itemGuid); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Give amount not valid!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, itemGuid)); return; @@ -3234,7 +3235,7 @@ public void HandleActionGiveObjectRequest(uint targetGuid, uint itemGuid, int am if (item.StackSize < amount) { - log.WarnFormat("Player 0x{0:X8}:{1} tried to give item with invalid amount ({4}) 0x{2:X8}:{3}.", Guid.Full, Name, item.Guid.Full, item.Name, amount); + log.LogWarning("Player 0x{Guid:X8}:{Name} tried to give item with invalid amount ({Amount}) 0x{ItemGuid:X8}:{ItemName}.", Guid.Full, Name, amount, item.Guid.Full, item.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Give amount not valid!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, itemGuid)); return; @@ -3263,7 +3264,7 @@ public void HandleActionGiveObjectRequest(uint targetGuid, uint itemGuid, int am // We make sure the item is still valid. It could have changed during our movement if (FindObject(item.Guid, SearchLocations.MyInventory | SearchLocations.MyEquippedItems, out itemFoundInContainer, out itemRootOwner, out itemWasEquipped) != item || item.StackSize < amount) { - log.DebugFormat("Player 0x{0:X8}:{1} tried to give an item that's no longer valid 0x{2:X8}:{3}.", Guid.Full, Name, item.Guid.Full, item.Name); + log.LogDebug("Player 0x{Guid:X8}:{Name} tried to give an item that's no longer valid 0x{ItemGuid:X8}:{ItemName}.", Guid.Full, Name, item.Guid.Full, item.Name); Session.Network.EnqueueSend(new GameEventCommunicationTransientString(Session, "Give failed!")); // Custom error message Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, itemGuid, WeenieError.ActionCancelled)); return; @@ -3370,7 +3371,7 @@ private void GiveObjectToPlayer(Player target, WorldObject item, Container itemF Session.Network.EnqueueSend(new GameEventInventoryServerSaveFailed(Session, itemToGive.Guid.Full)); if (!TryCreateInInventoryWithNetworking(itemToGive)) - log.WarnFormat("Item 0x{0:X8}:{1} for player {2} lost from GiveObjecttoPlayer failure.", item.Guid.Full, item.Name, Name); + log.LogWarning("Item 0x{Guid:X8}:{ItemName} for player {Name} lost from GiveObjecttoPlayer failure.", item.Guid.Full, item.Name, Name); return; } @@ -3555,7 +3556,7 @@ private void HandleIOUTurnIn(WorldObject target, WorldObject iouToTurnIn) if (PropertyManager.GetBool("player_receive_immediate_save").Item) RushNextPlayerSave(5); - log.DebugFormat("[IOU] {0} (0x{1}) traded in a IOU (0x{2}) for {3} which became {4} (0x{5}).", Name, Guid, iouToTurnIn.Guid, wcid, item.Name, item.Guid); + log.LogDebug("[IOU] {Name} (0x{Guid}) traded in a IOU (0x{IouToTurnInGuid}) for {Wcid} which became {ItemName} (0x{ItemGuid}).", Name, Guid, iouToTurnIn.Guid, wcid, item.Name, item.Guid); } return; } @@ -3662,7 +3663,7 @@ public void HandleActionSetInscription(uint itemGuid, string inscriptionText) if (item == null) { - log.Error("Player_Inventory HandleActionSetInscription failed"); + log.LogError("Player_Inventory HandleActionSetInscription failed"); return; } } @@ -3744,10 +3745,10 @@ public void GiveFromEmote(WorldObject emoter, uint weenieClassId, int amount = 1 { if (emoter is null || weenieClassId == 0) { - log.Warn($"Player.GiveFromEmote: Emoter is null: {emoter is null} | weenieClassId == 0: {weenieClassId == 0}"); + log.LogWarning("Player.GiveFromEmote: Emoter is null: {EmoterIsNull} | weenieClassId == 0: {WeenieClassIdIsZero}", emoter is null, weenieClassId == 0); if (emoter != null) - log.Warn($"Player.GiveFromEmote: Emoter is {emoter.Name} (0x{emoter.Guid}) | WCID: {emoter.WeenieClassId}"); + log.LogWarning("Player.GiveFromEmote: Emoter is {Name} (0x{Guid}) | WCID: {WeenieClassId}", emoter.Name, emoter.Guid, emoter.WeenieClassId); return; } @@ -3784,7 +3785,7 @@ public void GiveFromEmote(WorldObject emoter, uint weenieClassId, int amount = 1 if (item == null) { - log.Warn($"Player.GiveFromEmote: Emoter is {emoter.Name} (0x{emoter.Guid}) | WCID: {emoter.WeenieClassId} is not able to be created."); + log.LogWarning("Player.GiveFromEmote: Emoter is {Name} (0x{Guid}) | WCID: {WeenieClassId} is not able to be created.", emoter.Name, emoter.Guid, emoter.WeenieClassId); return; } @@ -3808,7 +3809,7 @@ public void GiveFromEmote(WorldObject emoter, uint weenieClassId, int amount = 1 } else { - log.Warn($"Player.GiveFromEmote: itemStacks <= 0: emoter: {emoter.Name} (0x{emoter.Guid}) - {emoter.WeenieClassId} | weenieClassId: {weenieClassId} | amount: {amount}"); + log.LogWarning("Player.GiveFromEmote: itemStacks <= 0: emoter: {Name} (0x{Guid}) - {EmoterWeenieClassId} | weenieClassId: {WeenieClassId} | amount: {Amount}", emoter.Name, emoter.Guid, emoter.WeenieClassId, weenieClassId, amount); if (PropertyManager.GetBool("iou_trades").Item) { @@ -3898,7 +3899,7 @@ public void AuditEquippedItems() foreach (var dequipItem in dequipItems) { - log.Warn($"{Name}.AuditEquippedItems() - dequipping {dequipItem.Name} ({dequipItem.Guid})"); + log.LogWarning("{Name}.AuditEquippedItems() - dequipping {DequipItemName} ({Guid})", Name, dequipItem.Name, dequipItem.Guid); HandleActionPutItemInContainer(dequipItem.Guid.Full, Guid.Full); } } @@ -3966,19 +3967,19 @@ public bool MoveItemToFirstContainerSlot(WorldObject target) if (container == null) { - log.Error($"{Name}.Player_Inventory.MoveItemToFirstContainerSlot() - failed to find target item {target.Name} ({target.Guid}) in player inventory"); + log.LogError("{Name}.Player_Inventory.MoveItemToFirstContainerSlot() - failed to find target item {TargetName} ({Guid}) in player inventory", Name, target.Name, target.Guid); return false; } if (!TryRemoveFromInventory(target.Guid)) { - log.Error($"{Name}.Player_Inventory.MoveItemToFirstContainerSlot() - failed to remove target item {target.Name} ({target.Guid}) from player inventory"); + log.LogError("{Name}.Player_Inventory.MoveItemToFirstContainerSlot() - failed to remove target item {TargetName} ({Guid}) from player inventory", Name, target.Name, target.Guid); return false; } if (!container.TryAddToInventory(target, 0, true, false)) { - log.Error($"{Name}.Player_Inventory.MoveItemToFirstContainerSlot() - failed to re-add target item {target.Name} ({target.Guid}) to player inventory"); + log.LogError("{Name}.Player_Inventory.MoveItemToFirstContainerSlot() - failed to re-add target item {TargetName} ({Guid}) to player inventory", Name, target.Name, target.Guid); return false; } diff --git a/Source/ACE.Server/WorldObjects/Player_Magic.cs b/Source/ACE.Server/WorldObjects/Player_Magic.cs index 3a9c9791be..af6b77a04e 100644 --- a/Source/ACE.Server/WorldObjects/Player_Magic.cs +++ b/Source/ACE.Server/WorldObjects/Player_Magic.cs @@ -2,8 +2,9 @@ using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.DatLoader; using ACE.Entity; using ACE.Entity.Enum; @@ -84,7 +85,7 @@ public void HandleActionCastTargetedSpell(uint targetGuid, uint spellId, WorldOb if (CombatMode != CombatMode.Magic) { - log.Warn($"{Name}.HandleActionCastTargetedSpell({targetGuid:X8}, {spellId}, {casterItem?.Name}) - CombatMode mismatch {CombatMode}, LastCombatMode: {LastCombatMode}"); + log.LogWarning("{Name}.HandleActionCastTargetedSpell({TargetGuid:X8}, {SpellId}, {CasterItemName}) - CombatMode mismatch {CombatMode}, LastCombatMode: {LastCombatMode}", Name, targetGuid, spellId, casterItem?.Name, CombatMode, LastCombatMode); if (LastCombatMode == CombatMode.Magic) CombatMode = CombatMode.Magic; @@ -97,7 +98,7 @@ public void HandleActionCastTargetedSpell(uint targetGuid, uint spellId, WorldOb if (FastTick && PhysicsObj.MovementManager.MotionInterpreter.InterpretedState.CurrentStyle != (uint)MotionStance.Magic) { - log.Warn($"{Name} CombatMode: {CombatMode}, CurrentMotionState: {CurrentMotionState.Stance}.{CurrentMotionState.MotionState.ForwardCommand}, Physics: {(MotionStance)PhysicsObj.MovementManager.MotionInterpreter.InterpretedState.CurrentStyle}.{(MotionCommand)PhysicsObj.MovementManager.MotionInterpreter.InterpretedState.ForwardCommand}"); + log.LogWarning("{Name} CombatMode: {CombatMode}, CurrentMotionState: {Stance}.{MotionStateForwardCommand}, Physics: {CurrentStyle}.{InterpretedStateForwardCommand}", Name, CombatMode, CurrentMotionState.Stance, CurrentMotionState.MotionState.ForwardCommand, (MotionStance)PhysicsObj.MovementManager.MotionInterpreter.InterpretedState.CurrentStyle, (MotionCommand)PhysicsObj.MovementManager.MotionInterpreter.InterpretedState.ForwardCommand); ApplyPhysicsMotion(new Motion(MotionStance.Magic)); SendUseDoneEvent(WeenieError.YoureTooBusy); return; @@ -275,7 +276,7 @@ public void HandleActionMagicCastUnTargetedSpell(uint spellId) if (CombatMode != CombatMode.Magic) { - log.Warn($"{Name}.HandleActionMagicCastUnTargetedSpell({spellId}) - CombatMode mismatch {CombatMode}, LastCombatMode {LastCombatMode}"); + log.LogWarning("{Name}.HandleActionMagicCastUnTargetedSpell({SpellId}) - CombatMode mismatch {CombatMode}, LastCombatMode {LastCombatMode}", Name, spellId, CombatMode, LastCombatMode); if (LastCombatMode == CombatMode.Magic) CombatMode = CombatMode.Magic; @@ -288,7 +289,7 @@ public void HandleActionMagicCastUnTargetedSpell(uint spellId) if (FastTick && PhysicsObj.MovementManager.MotionInterpreter.InterpretedState.CurrentStyle != (uint)MotionStance.Magic) { - log.Warn($"{Name} CombatMode: {CombatMode}, CurrentMotionState: {CurrentMotionState.Stance}.{CurrentMotionState.MotionState.ForwardCommand}, Physics: {(MotionStance)PhysicsObj.MovementManager.MotionInterpreter.InterpretedState.CurrentStyle}.{(MotionCommand)PhysicsObj.MovementManager.MotionInterpreter.InterpretedState.ForwardCommand}"); + log.LogWarning("{Name} CombatMode: {CombatMode}, CurrentMotionState: {Stance}.{MotionStateForwardCommand}, Physics: {CurrentStyle}.{InterpretedStateForwardCommand}", Name, CombatMode, CurrentMotionState.Stance, CurrentMotionState.MotionState.ForwardCommand, (MotionStance)PhysicsObj.MovementManager.MotionInterpreter.InterpretedState.CurrentStyle, (MotionCommand)PhysicsObj.MovementManager.MotionInterpreter.InterpretedState.ForwardCommand); ApplyPhysicsMotion(new Motion(MotionStance.Magic)); SendUseDoneEvent(WeenieError.YoureTooBusy); return; @@ -703,8 +704,8 @@ public void DoCastSpell(MagicState _state, bool checkAngle = true) if (state == null) { - log.Warn($"{Name}.DoCastSpell(): null state detected"); - log.Warn(_state); + log.LogWarning("{Name}.DoCastSpell(): null state detected", Name); + log.LogWarning("{Message:l}", _state); // send UseDone? SendUseDoneEvent(WeenieError.BadCast); @@ -726,7 +727,7 @@ public bool IsWithinAngle(WorldObject target) FindObject(target.Guid.Full, SearchLocations.Everywhere, out _, out var rootOwner, out _); if (rootOwner == null) - log.Error($"{Name}.IsWithinAngle({target.Name} ({target.Guid})) - couldn't find rootOwner"); + log.LogError("{Name}.IsWithinAngle({TargetName} ({Guid})) - couldn't find rootOwner", Name, target.Name, target.Guid); else if (rootOwner != this) angle = GetAngle(rootOwner); @@ -1194,7 +1195,7 @@ public void TryBurnComponents(Spell spell) if (!SpellFormula.SpellComponentsTable.SpellComponents.TryGetValue(component, out var spellComponent)) { - log.Error($"{Name}.TryBurnComponents(): Couldn't find SpellComponent {component}"); + log.LogError("{Name}.TryBurnComponents(): Couldn't find SpellComponent {Component}", Name, component); continue; } @@ -1205,7 +1206,7 @@ public void TryBurnComponents(Spell spell) if (item == null) { if (SpellComponentsRequired && PropertyManager.GetBool("require_spell_comps").Item) - log.Warn($"{Name}.TryBurnComponents({spellComponent.Name}): not found in inventory"); + log.LogWarning("{Name}.TryBurnComponents({SpellComponentName}): not found in inventory", Name, spellComponent.Name); else burned.RemoveAt(i); @@ -1423,7 +1424,7 @@ public static bool VerifyNonComponentTargetType(Spell spell, WorldObject target) return target is Lifestone; } - log.Error($"VerifyNonComponentTargetType({spell.Id} - {spell.Name}, {target.Name}) - unexpected NonComponentTargetType {spell.NonComponentTargetType}"); + log.LogError("VerifyNonComponentTargetType({Id} - {SpellName}, {TargetName}) - unexpected NonComponentTargetType {NonComponentTargetType}", spell.Id, spell.Name, target.Name, spell.NonComponentTargetType); return false; } diff --git a/Source/ACE.Server/WorldObjects/Player_Melee.cs b/Source/ACE.Server/WorldObjects/Player_Melee.cs index 57fa1d232b..695b276435 100644 --- a/Source/ACE.Server/WorldObjects/Player_Melee.cs +++ b/Source/ACE.Server/WorldObjects/Player_Melee.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.DatLoader.Entity.AnimationHooks; using ACE.Entity.Enum; using ACE.Server.Entity; @@ -55,7 +56,7 @@ public void HandleActionTargetedMeleeAttack(uint targetGuid, uint attackHeight, if (CombatMode != CombatMode.Melee) { - log.Warn($"{Name}.HandleActionTargetedMeleeAttack({targetGuid:X8}, {attackHeight}, {powerLevel}) - CombatMode mismatch {CombatMode}, LastCombatMode {LastCombatMode}"); + log.LogWarning("{Name}.HandleActionTargetedMeleeAttack({TargetGuid:X8}, {AttackHeight}, {PowerLevel}) - CombatMode mismatch {CombatMode}, LastCombatMode {LastCombatMode}", Name, targetGuid, attackHeight, powerLevel, CombatMode, LastCombatMode); if (LastCombatMode == CombatMode.Melee) CombatMode = CombatMode.Melee; @@ -113,7 +114,7 @@ public void HandleActionTargetedMeleeAttack(uint targetGuid, uint attackHeight, var creatureTarget = target as Creature; if (creatureTarget == null) { - log.Warn($"{Name}.HandleActionTargetedMeleeAttack({targetGuid:X8}, {AttackHeight}, {powerLevel}) - target guid not creature"); + log.LogWarning("{Name}.HandleActionTargetedMeleeAttack({TargetGuid:X8}, {AttackHeight}, {PowerLevel}) - target guid not creature", Name, targetGuid, AttackHeight, powerLevel); OnAttackDone(); return; } diff --git a/Source/ACE.Server/WorldObjects/Player_Missile.cs b/Source/ACE.Server/WorldObjects/Player_Missile.cs index a851c33f1b..054c84acb8 100644 --- a/Source/ACE.Server/WorldObjects/Player_Missile.cs +++ b/Source/ACE.Server/WorldObjects/Player_Missile.cs @@ -1,7 +1,8 @@ using System; using System.Numerics; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Entity.Enum; using ACE.Server.Entity.Actions; using ACE.Server.Network.GameEvent.Events; @@ -44,7 +45,7 @@ public void HandleActionTargetedMissileAttack(uint targetGuid, uint attackHeight if (CombatMode != CombatMode.Missile) { - log.Warn($"{Name}.HandleActionTargetedMissileAttack({targetGuid:X8}, {attackHeight}, {accuracyLevel}) - CombatMode mismatch {CombatMode}, LastCombatMode: {LastCombatMode}"); + log.LogWarning("{Name}.HandleActionTargetedMissileAttack({TargetGuid:X8}, {AttackHeight}, {AccuracyLevel}) - CombatMode mismatch {CombatMode}, LastCombatMode: {LastCombatMode}", Name, targetGuid, attackHeight, accuracyLevel, CombatMode, LastCombatMode); if (LastCombatMode == CombatMode.Missile) CombatMode = CombatMode.Missile; diff --git a/Source/ACE.Server/WorldObjects/Player_Move.cs b/Source/ACE.Server/WorldObjects/Player_Move.cs index 0d38f145a8..5519ebac17 100644 --- a/Source/ACE.Server/WorldObjects/Player_Move.cs +++ b/Source/ACE.Server/WorldObjects/Player_Move.cs @@ -1,7 +1,8 @@ using System; using System.Threading; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Entity; using ACE.Entity.Enum; using ACE.Server.Entity; @@ -49,7 +50,7 @@ public void CreateMoveToChain(WorldObject target, Action callback, float? if (target.Location == null) { StopExistingMoveToChains(); - log.Error($"{Name}.CreateMoveToChain({target.Name}): target.Location is null"); + log.LogError("{Name}.CreateMoveToChain({TargetName}): target.Location is null", Name, target.Name); callback(false); return; diff --git a/Source/ACE.Server/WorldObjects/Player_Move2.cs b/Source/ACE.Server/WorldObjects/Player_Move2.cs index 82732016a4..32c000e1f3 100644 --- a/Source/ACE.Server/WorldObjects/Player_Move2.cs +++ b/Source/ACE.Server/WorldObjects/Player_Move2.cs @@ -1,6 +1,7 @@ using System; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Entity.Enum; using ACE.Server.Entity; using ACE.Server.Physics; @@ -25,7 +26,7 @@ public void CreateMoveToChain2(WorldObject target, Action callback, float? if (target.Location == null) { - log.Error($"{Name}.MoveTo({target.Name}): target.Location is null"); + log.LogError("{Name}.MoveTo({TargetName}): target.Location is null", Name, target.Name); callback(false); return; } @@ -78,7 +79,7 @@ public void CreateTurnToChain2(WorldObject target, Action callback, float? if (rotateTarget.Location == null) { - log.Error($"{Name}.TurnTo({target.Name}): target.Location is null"); + log.LogError("{Name}.TurnTo({TargetName}): target.Location is null", Name, target.Name); callback(false); return; } diff --git a/Source/ACE.Server/WorldObjects/Player_Networking.cs b/Source/ACE.Server/WorldObjects/Player_Networking.cs index 8b37508080..a9908740ea 100644 --- a/Source/ACE.Server/WorldObjects/Player_Networking.cs +++ b/Source/ACE.Server/WorldObjects/Player_Networking.cs @@ -1,8 +1,9 @@ using System; +using Microsoft.Extensions.Logging; + using ACE.Common; using ACE.Common.Extensions; -using ACE.Common.Logging; using ACE.Database.Models.Shard; using ACE.Entity; using ACE.Entity.Enum; @@ -142,7 +143,7 @@ public void PlayerEnterWorld() actionChain.EnqueueChain(); } - log.DebugFormat("[LOGIN] Account {0} entered the world with character {1} (0x{2}) at {3}.", Account.AccountName, Name, Guid, DateTime.Now.ToCommonString()); + log.LogDebug("[LOGIN] Account {AccountName} entered the world with character {Name} (0x{Guid}) at {Now}.", Account.AccountName, Name, Guid, DateTime.Now.ToCommonString()); } public void SendTurbineChatChannels(bool breakAllegiance = false) diff --git a/Source/ACE.Server/WorldObjects/Player_Skills.cs b/Source/ACE.Server/WorldObjects/Player_Skills.cs index 89ee408c7a..f393eed9e8 100644 --- a/Source/ACE.Server/WorldObjects/Player_Skills.cs +++ b/Source/ACE.Server/WorldObjects/Player_Skills.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using System.Linq; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Database; using ACE.DatLoader; using ACE.Entity.Enum; @@ -25,13 +26,13 @@ public bool HandleActionRaiseSkill(Skill skill, uint amount) if (creatureSkill == null || creatureSkill.AdvancementClass < SkillAdvancementClass.Trained) { - log.Warn($"{Name}.HandleActionRaiseSkill({skill}, {amount}) - trained or specialized skill not found"); + log.LogWarning("{Name}.HandleActionRaiseSkill({Skill}, {Amount}) - trained or specialized skill not found", Name, skill, amount); return false; } if (amount > AvailableExperience) { - log.Warn($"{Name}.HandleActionRaiseSkill({skill}, {amount}) - amount > AvailableExperience ({AvailableExperience})"); + log.LogWarning("{Name}.HandleActionRaiseSkill({Skill}, {Amount}) - amount > AvailableExperience ({AvailableExperience})", Name, skill, amount, AvailableExperience); return false; } @@ -72,14 +73,14 @@ private bool SpendSkillXp(CreatureSkill creatureSkill, uint amount, bool sendNet var skillXPTable = GetSkillXPTable(creatureSkill.AdvancementClass); if (skillXPTable == null) { - log.Warn($"{Name}.SpendSkillXp({creatureSkill.Skill}, {amount}) - player tried to raise {creatureSkill.AdvancementClass} skill"); + log.LogWarning("{Name}.SpendSkillXp({Skill}, {Amount}) - player tried to raise {AdvancementClass} skill", Name, creatureSkill.Skill, amount, creatureSkill.AdvancementClass); return false; } // ensure skill is not already max rank if (creatureSkill.IsMaxRank) { - log.Warn($"{Name}.SpendSkillXp({creatureSkill.Skill}, {amount}) - player tried to raise skill beyond max rank"); + log.LogWarning("{Name}.SpendSkillXp({Skill}, {Amount}) - player tried to raise skill beyond max rank", Name, creatureSkill.Skill, amount); return false; } @@ -97,7 +98,7 @@ private bool SpendSkillXp(CreatureSkill creatureSkill, uint amount, bool sendNet // spend xp on skill if (!SpendXP(amount, sendNetworkUpdate)) { - log.Warn($"{Name}.SpendSkillXp({creatureSkill.Skill}, {amount}) - SpendXP failed"); + log.LogWarning("{Name}.SpendSkillXp({Skill}, {Amount}) - SpendXP failed", Name, creatureSkill.Skill, amount); return false; } @@ -116,20 +117,20 @@ public bool HandleActionTrainSkill(Skill skill, int creditsSpent) { if (creditsSpent > AvailableSkillCredits) { - log.Warn($"{Name}.HandleActionTrainSkill({skill}, {creditsSpent}) - not enough skill credits ({AvailableSkillCredits})"); + log.LogWarning("{Name}.HandleActionTrainSkill({Skill}, {CreditsSpent}) - not enough skill credits ({AvailableSkillCredits})", Name, skill, creditsSpent, AvailableSkillCredits); return false; } // get the actual cost to train the skill. if (!DatManager.PortalDat.SkillTable.SkillBaseHash.TryGetValue((uint)skill, out var skillBase)) { - log.Warn($"{Name}.HandleActionTrainSkill({skill}, {creditsSpent}) - couldn't find skill base"); + log.LogWarning("{Name}.HandleActionTrainSkill({Skill}, {CreditsSpent}) - couldn't find skill base", Name, skill, creditsSpent); return false; } if (creditsSpent != skillBase.TrainedCost) { - log.Warn($"{Name}.HandleActionTrainSkill({skill}, {creditsSpent}) - client value differs from skillBase.TrainedCost({skillBase.TrainedCost})"); + log.LogWarning("{Name}.HandleActionTrainSkill({Skill}, {CreditsSpent}) - client value differs from skillBase.TrainedCost({TrainedCost})", Name, skill, creditsSpent, skillBase.TrainedCost); return false; } @@ -158,7 +159,7 @@ public bool TrainSkill(Skill skill) // get the amount of skill credits required to train this skill if (!DatManager.PortalDat.SkillTable.SkillBaseHash.TryGetValue((uint)skill, out var skillBase)) { - log.Error($"{Name}.TrainSkill({skill}) - couldn't find skill base"); + log.LogError("{Name}.TrainSkill({Skill}) - couldn't find skill base", Name, skill); return false; } @@ -203,7 +204,7 @@ public bool SpecializeSkill(Skill skill, bool resetSkill = true) // from trained -> specialized if (!DatManager.PortalDat.SkillTable.SkillBaseHash.TryGetValue((uint)skill, out var skillBase)) { - log.Error($"{Name}.SpecializeSkill({skill}, {resetSkill}) - couldn't find skill base"); + log.LogError("{Name}.SpecializeSkill({Skill}, {ResetSkill}) - couldn't find skill base", Name, skill, resetSkill); return false; } diff --git a/Source/ACE.Server/WorldObjects/Player_Spells.cs b/Source/ACE.Server/WorldObjects/Player_Spells.cs index a44f2792b3..94db51cc32 100644 --- a/Source/ACE.Server/WorldObjects/Player_Spells.cs +++ b/Source/ACE.Server/WorldObjects/Player_Spells.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using System.Linq; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Database; using ACE.Database.Models.Shard; using ACE.DatLoader; @@ -115,7 +116,7 @@ public void HandleActionMagicRemoveSpellId(uint spellId) { if (!Biota.TryRemoveKnownSpell((int)spellId, BiotaDatabaseLock)) { - log.Error("Invalid spellId passed to Player.RemoveSpellFromSpellBook"); + log.LogError("Invalid spellId passed to Player.RemoveSpellFromSpellBook"); return; } @@ -180,7 +181,7 @@ public void DequipItemFromSet(WorldObject item) var addSpells = spells.Except(prevSpells); if (addSpells.Count() != 0) - log.Error($"{Name}.DequipItemFromSet({item.Name}) -- last item in set dequipped, but addSpells still contains {string.Join(", ", addSpells.Select(i => i.Name))} -- this shouldn't happen!"); + log.LogError("{Name}.DequipItemFromSet({ItemName}) -- last item in set dequipped, but addSpells still contains {Join} -- this shouldn't happen!", Name, item.Name, string.Join(", ", addSpells.Select(i => i.Name))); } EquipDequipItemFromSet(item, spells, prevSpells, surrogateItem); @@ -431,7 +432,7 @@ public void HandleSetDesiredComponentLevel(uint component_wcid, uint amount) // ensure wcid is spell component if (!SpellComponent.IsValid(component_wcid)) { - log.Warn($"{Name}.HandleSetDesiredComponentLevel({component_wcid}, {amount}): invalid spell component wcid"); + log.LogWarning("{Name}.HandleSetDesiredComponentLevel({Component_wcid}, {Amount}): invalid spell component wcid", Name, component_wcid, amount); return; } if (amount > 0) @@ -553,7 +554,7 @@ public void AuditItemSpells() if (!table.TryGetValue(new ObjectGuid(enchantment.CasterObjectId), out var item)) { var spell = new Spell(enchantment.SpellId, false); - log.Error($"{Name}.AuditItemSpells(): removing spell {spell.Name} from {(enchantment.HasSpellSetId ? "non-possessed" : "non-equipped")} item"); + log.LogError("{Name}.AuditItemSpells(): removing spell {SpellName} from {ItemState} item", Name, spell.Name, (enchantment.HasSpellSetId ? "non-possessed" : "non-equipped")); EnchantmentManager.Dispel(enchantment); continue; @@ -582,7 +583,7 @@ public void AuditItemSpells() foreach (var removeSpell in removeSpells) { - log.Error($"{Name}.AuditItemSpells(): removing spell {inactiveSpell.Name} from {item.EquipmentSetId}"); + log.LogError("{Name}.AuditItemSpells(): removing spell {InactiveSpellName} from {EquipmentSetId}", Name, inactiveSpell.Name, item.EquipmentSetId); EnchantmentManager.Dispel(removeSpell); } diff --git a/Source/ACE.Server/WorldObjects/Player_Tick.cs b/Source/ACE.Server/WorldObjects/Player_Tick.cs index 431065af0b..0df313d4d7 100644 --- a/Source/ACE.Server/WorldObjects/Player_Tick.cs +++ b/Source/ACE.Server/WorldObjects/Player_Tick.cs @@ -3,8 +3,9 @@ using System.Linq; using System.Numerics; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.Entity.Enum; using ACE.Entity.Enum.Properties; using ACE.Entity.Models; @@ -41,7 +42,7 @@ public void Player_Tick(double currentUnixTime) // Boot the player as their Character object is not saving properly if (!IsLoggingOut) { - log.Error($"{Session.Player.Name} | 0x{Guid} | Account: {Account.AccountName} - disconnected for CharacterSaveFailed"); + log.LogError("{Name} | 0x{Guid} | Account: {AccountName} - disconnected for CharacterSaveFailed", Session.Player.Name, Guid, Account.AccountName); //Session.SendCharacterError(CharacterError.AccountLogin); // forces client to error screen Session.Terminate(SessionTerminationReason.CharacterSaveFailed, new GameMessageCharacterError(CharacterError.AccountLogin)); //Session.LogOffPlayer(true); @@ -55,7 +56,7 @@ public void Player_Tick(double currentUnixTime) // Boot the player as their Biota object is not saving properly if (!IsLoggingOut) { - log.Error($"{Session.Player.Name} | 0x{Guid} | Account: {Account.AccountName} - disconnected for BiotaSaveFailed"); + log.LogError("{Name} | 0x{Guid} | Account: {AccountName} - disconnected for BiotaSaveFailed", Session.Player.Name, Guid, Account.AccountName); //Session.SendCharacterError(CharacterError.AccountLogin); // forces client to error screen Session.Terminate(SessionTerminationReason.BiotaSaveFailed, new GameMessageCharacterError(CharacterError.AccountLogin)); //Session.LogOffPlayer(true); @@ -324,9 +325,9 @@ public override bool UpdateObjectPhysics() var elapsedSeconds = stopwatch.Elapsed.TotalSeconds; ServerPerformanceMonitor.AddToCumulativeEvent(ServerPerformanceMonitor.CumulativeEventHistoryType.Player_Tick_UpdateObjectPhysics, elapsedSeconds); if (elapsedSeconds >= 1) // Yea, that ain't good.... - log.Warn($"[PERFORMANCE][PHYSICS] {Guid}:{Name} took {(elapsedSeconds * 1000):N1} ms to process UpdateObjectPhysics() at loc: {Location}"); + log.LogWarning("[PERFORMANCE][PHYSICS] {Guid}:{Name} took {ElapsedMs:N1} ms to process UpdateObjectPhysics() at loc: {Location}", Guid, Name, (elapsedSeconds * 1000), Location); else if (elapsedSeconds >= 0.010) - log.DebugFormat("[PERFORMANCE][PHYSICS] {0}:{1} took {2:N1} ms to process UpdateObjectPhysics() at loc: {3}", Guid, Name, (elapsedSeconds * 1000), Location); + log.LogDebug("[PERFORMANCE][PHYSICS] {Guid}:{Name} took {ElapsedMs:N1} ms to process UpdateObjectPhysics() at loc: {Location}", Guid, Name, (elapsedSeconds * 1000), Location); } } @@ -420,7 +421,7 @@ public bool UpdatePlayerPosition(ACE.Entity.Position newPosition, bool forceUpda // pre-validate movement if (!ValidateMovement(newPosition)) { - log.Error($"{Name}.UpdatePlayerPosition() - movement pre-validation failed from {Location} to {newPosition}"); + log.LogError("{Name}.UpdatePlayerPosition() - movement pre-validation failed from {Location} to {NewPosition}", Name, Location, newPosition); return false; } @@ -442,7 +443,7 @@ public bool UpdatePlayerPosition(ACE.Entity.Position newPosition, bool forceUpda Console.WriteLine($"Dist: {dist}");*/ if (newPosition.Landblock == 0x18A && Location.Landblock != 0x18A) - log.Info($"{Name} is getting swanky"); + log.LogInformation("{Name} is getting swanky", Name); if (!Teleporting) { @@ -452,7 +453,7 @@ public bool UpdatePlayerPosition(ACE.Entity.Position newPosition, bool forceUpda if (distSq > MaxSpeedSq && blockDist > 1) { //Session.Network.EnqueueSend(new GameMessageSystemChat("Movement error", ChatMessageType.Broadcast)); - log.Warn($"MOVEMENT SPEED: {Name} trying to move from {Location} to {newPosition}, speed: {Math.Sqrt(distSq)}"); + log.LogWarning("MOVEMENT SPEED: {Name} trying to move from {Location} to {NewPosition}, speed: {Sqrt}", Name, Location, newPosition, Math.Sqrt(distSq)); return false; } @@ -484,7 +485,7 @@ public bool UpdatePlayerPosition(ACE.Entity.Position newPosition, bool forceUpda if (blockDist <= 1) { - log.Warn($"z-pos hacking detected for {Name}, lastGroundPos: {LastGroundPos.ToLOCString()} - requestPos: {newPosition.ToLOCString()}"); + log.LogWarning("z-pos hacking detected for {Name}, lastGroundPos: {LastGroundPos} - requestPos: {NewPosition}", Name, LastGroundPos.ToLOCString(), newPosition.ToLOCString()); Location = new ACE.Entity.Position(LastGroundPos); Sequences.GetNextSequence(SequenceType.ObjectForcePosition); SendUpdatePosition(); @@ -528,9 +529,9 @@ public bool UpdatePlayerPosition(ACE.Entity.Position newPosition, bool forceUpda var elapsedSeconds = stopwatch.Elapsed.TotalSeconds; ServerPerformanceMonitor.AddToCumulativeEvent(ServerPerformanceMonitor.CumulativeEventHistoryType.Player_Tick_UpdateObjectPhysics, elapsedSeconds); if (elapsedSeconds >= 0.100) // Yea, that ain't good.... - log.Warn($"[PERFORMANCE][PHYSICS] {Guid}:{Name} took {(elapsedSeconds * 1000):N1} ms to process UpdatePlayerPosition() at loc: {Location}"); + log.LogWarning("[PERFORMANCE][PHYSICS] {Guid}:{Name} took {ElapsedMs:N1} ms to process UpdatePlayerPosition() at loc: {Location}", Guid, Name, (elapsedSeconds * 1000), Location); else if (elapsedSeconds >= 0.010) - log.DebugFormat("[PERFORMANCE][PHYSICS] {0}:{1} took {2:N1} ms to process UpdatePlayerPosition() at loc: {3}", Guid, Name, (elapsedSeconds * 1000), Location); + log.LogDebug("[PERFORMANCE][PHYSICS] {Guid}:{Name} took {ElapsedMs:N1} ms to process UpdatePlayerPosition() at loc: {Location}", Guid, Name, (elapsedSeconds * 1000), Location); } } } diff --git a/Source/ACE.Server/WorldObjects/Player_Trade.cs b/Source/ACE.Server/WorldObjects/Player_Trade.cs index dc6fd9243c..40cde564d2 100644 --- a/Source/ACE.Server/WorldObjects/Player_Trade.cs +++ b/Source/ACE.Server/WorldObjects/Player_Trade.cs @@ -3,7 +3,8 @@ using System.Linq; using System.Threading; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Database; using ACE.Entity; using ACE.Entity.Enum; @@ -262,13 +263,13 @@ private void FinalizeTrade(Player target) foreach (var wo in myEscrow) { if (!TryCreateInInventoryWithNetworking(wo) && !target.TryCreateInInventoryWithNetworking(wo)) - log.WarnFormat("Item 0x{0:X8}:{1} for player {2} lost from FinalizeTrade failure.", wo.Guid.Full, wo.Name, target.Name); + log.LogWarning("Item 0x{Guid:X8}:{WoName} for player {TargetName} lost from FinalizeTrade failure.", wo.Guid.Full, wo.Name, target.Name); } foreach (var wo in targetEscrow) { if (!target.TryCreateInInventoryWithNetworking(wo) && !TryCreateInInventoryWithNetworking(wo)) - log.WarnFormat("Item 0x{0:X8}:{1} for player {2} lost from FinalizeTrade failure.", wo.Guid.Full, wo.Name, Name); + log.LogWarning("Item 0x{Guid:X8}:{WoName} for player {Name} lost from FinalizeTrade failure.", wo.Guid.Full, wo.Name, Name); } Session.Network.EnqueueSend(new GameEventWeenieError(Session, WeenieError.TradeComplete)); diff --git a/Source/ACE.Server/WorldObjects/Player_Use.cs b/Source/ACE.Server/WorldObjects/Player_Use.cs index 653cc51535..8b7662f381 100644 --- a/Source/ACE.Server/WorldObjects/Player_Use.cs +++ b/Source/ACE.Server/WorldObjects/Player_Use.cs @@ -1,6 +1,7 @@ using System; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Entity; using ACE.Entity.Enum; using ACE.Server.Entity; @@ -42,7 +43,7 @@ public void HandleActionUseWithTarget(uint sourceObjectGuid, uint targetObjectGu if (sourceItem == null) { - log.Warn($"{Name}.HandleActionUseWithTarget({sourceObjectGuid:X8}, {targetObjectGuid:X8}): couldn't find {sourceObjectGuid:X8}"); + log.LogWarning("{Name}.HandleActionUseWithTarget({SourceObjectGuid:X8}, {TargetObjectGuid:X8}): couldn't find {SourceObjectGuid:X8}", Name, sourceObjectGuid, targetObjectGuid, sourceObjectGuid); SendUseDoneEvent(); return; } @@ -52,7 +53,7 @@ public void HandleActionUseWithTarget(uint sourceObjectGuid, uint targetObjectGu if (target == null) { - log.Warn($"{Name}.HandleActionUseWithTarget({sourceObjectGuid:X8}, {targetObjectGuid:X8}): couldn't find {targetObjectGuid:X8}"); + log.LogWarning("{Name}.HandleActionUseWithTarget({SourceObjectGuid:X8}, {TargetObjectGuid:X8}): couldn't find {TargetObjectGuid:X8}", Name, sourceObjectGuid, targetObjectGuid, targetObjectGuid); SendUseDoneEvent(); return; } @@ -210,7 +211,7 @@ public void HandleActionUseItem(uint itemGuid) } else { - log.DebugFormat("{0}.HandleActionUseItem({1:X8}): couldn't find object", Name, itemGuid); + log.LogDebug("{Name}.HandleActionUseItem({ItemGuid:X8}): couldn't find object", Name, itemGuid); SendUseDoneEvent(); } } diff --git a/Source/ACE.Server/WorldObjects/Player_Vitals.cs b/Source/ACE.Server/WorldObjects/Player_Vitals.cs index f96a10499a..1863da6475 100644 --- a/Source/ACE.Server/WorldObjects/Player_Vitals.cs +++ b/Source/ACE.Server/WorldObjects/Player_Vitals.cs @@ -1,6 +1,7 @@ using System.Runtime.CompilerServices; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.DatLoader; using ACE.Entity; using ACE.Entity.Enum; @@ -22,7 +23,7 @@ public bool HandleActionRaiseVital(PropertyAttribute2nd vital, uint amount) { if (!Vitals.TryGetValue(vital, out var creatureVital)) { - log.Warn($"{Name}.HandleActionRaiseVital({vital}, {amount}) - invalid vital"); + log.LogWarning("{Name}.HandleActionRaiseVital({Vital}, {Amount}) - invalid vital", Name, vital, amount); return false; } @@ -35,7 +36,7 @@ public bool HandleActionRaiseVital(PropertyAttribute2nd vital, uint amount) ChatPacket.SendServerMessage(Session, $"Your attempt to raise {vital.ToSentence()} has failed.", ChatMessageType.Broadcast); - log.Warn($"{Name}.HandleActionRaiseVital({vital}, {amount}) - amount > AvailableExperience ({AvailableExperience})"); + log.LogWarning("{Name}.HandleActionRaiseVital({Vital}, {Amount}) - amount > AvailableExperience ({AvailableExperience})", Name, vital, amount, AvailableExperience); return false; } @@ -70,7 +71,7 @@ private bool SpendVitalXp(CreatureVital creatureVital, uint amount, bool sendNet // ensure vital is not already max rank if (creatureVital.IsMaxRank) { - log.Warn($"{Name}.SpendVitalXp({creatureVital.Vital}, {amount}) - player tried to raise vital beyond max rank"); + log.LogWarning("{Name}.SpendVitalXp({Vital}, {Amount}) - player tried to raise vital beyond max rank", Name, creatureVital.Vital, amount); return false; } @@ -80,7 +81,7 @@ private bool SpendVitalXp(CreatureVital creatureVital, uint amount, bool sendNet if (amount > amountToEnd) { - log.Warn($"{Name}.SpendVitalXp({creatureVital.Vital}, {amount}) - player tried to raise vital beyond {amountToEnd} experience"); + log.LogWarning("{Name}.SpendVitalXp({Vital}, {Amount}) - player tried to raise vital beyond {AmountToEnd} experience", Name, creatureVital.Vital, amount, amountToEnd); return false; // returning error here, instead of setting amount to amountToEnd } @@ -88,7 +89,7 @@ private bool SpendVitalXp(CreatureVital creatureVital, uint amount, bool sendNet // spend xp on vital if (!SpendXP(amount, sendNetworkUpdate)) { - log.Warn($"{Name}.SpendVitalXp({creatureVital.Vital}, {amount}) - SpendXP failed"); + log.LogWarning("{Name}.SpendVitalXp({Vital}, {Amount}) - SpendXP failed", Name, creatureVital.Vital, amount); return false; } diff --git a/Source/ACE.Server/WorldObjects/Player_Xp.cs b/Source/ACE.Server/WorldObjects/Player_Xp.cs index 06b541bed2..78a2beeb15 100644 --- a/Source/ACE.Server/WorldObjects/Player_Xp.cs +++ b/Source/ACE.Server/WorldObjects/Player_Xp.cs @@ -1,8 +1,9 @@ using System; using System.Linq; +using Microsoft.Extensions.Logging; + using ACE.Common.Extensions; -using ACE.Common.Logging; using ACE.DatLoader; using ACE.Entity.Enum; using ACE.Entity.Enum.Properties; @@ -37,8 +38,8 @@ public void EarnXP(long amount, XpType xpType, ShareType shareType = ShareType.A if (m_amount < 0) { - log.Warn($"{Name}.EarnXP({amount}, {shareType})"); - log.Warn($"modifier: {modifier}, enchantment: {enchantment}, m_amount: {m_amount}"); + log.LogWarning("{Name}.EarnXP({Amount}, {ShareType})", Name, amount, shareType); + log.LogWarning("modifier: {Modifier}, enchantment: {Enchantment}, m_amount: {M_amount}", modifier, enchantment, m_amount); return; } @@ -138,8 +139,8 @@ private void UpdateXpVitae(long amount) if (vitae == null) { - log.Error($"{Name}.UpdateXpVitae({amount}) vitae null, likely due to cross-thread operation or corrupt EnchantmentManager cache. Please report this."); - log.Error(Environment.StackTrace); + log.LogError("{Name}.UpdateXpVitae({Amount}) vitae null, likely due to cross-thread operation or corrupt EnchantmentManager cache. Please report this.", Name, amount); + log.LogError("{Message:l}", Environment.StackTrace); return; } diff --git a/Source/ACE.Server/WorldObjects/Portal.cs b/Source/ACE.Server/WorldObjects/Portal.cs index b934dc409d..ce9957f5f8 100644 --- a/Source/ACE.Server/WorldObjects/Portal.cs +++ b/Source/ACE.Server/WorldObjects/Portal.cs @@ -51,7 +51,7 @@ public override bool EnterWorld() if (!success) { - log.Error($"{Name} ({Guid}) failed to spawn @ {Location?.ToLOCString()}"); + log.LogError("{Name} ({Guid}) failed to spawn @ {Location}", Name, Guid, Location?.ToLOCString()); return false; } diff --git a/Source/ACE.Server/WorldObjects/Storage.cs b/Source/ACE.Server/WorldObjects/Storage.cs index 4904c93b87..5d3224be68 100644 --- a/Source/ACE.Server/WorldObjects/Storage.cs +++ b/Source/ACE.Server/WorldObjects/Storage.cs @@ -62,7 +62,7 @@ public override ActivationResult CheckUseRequirements(WorldObject activator) if (rootHouse == null) { - log.Error($"[HOUSE] {player.Name} tried to use Storage chest @ {Location}, couldn't find RootHouse (this shouldn't happen)"); + log.LogError("[HOUSE] {Name} tried to use Storage chest @ {Location}, couldn't find RootHouse (this shouldn't happen)", player.Name, Location); return new ActivationResult(false); } diff --git a/Source/ACE.Server/WorldObjects/Vendor.cs b/Source/ACE.Server/WorldObjects/Vendor.cs index e02d54e427..d91d36b2e6 100644 --- a/Source/ACE.Server/WorldObjects/Vendor.cs +++ b/Source/ACE.Server/WorldObjects/Vendor.cs @@ -84,37 +84,37 @@ private bool ValidateVendorRequirements() if (currencyWeenie == null) { var errorMsg = $"WCID {currencyWCID}{(AlternateCurrency.HasValue ? ", which comes from PropertyDataId.AlternateCurrency," : "")} is not found in the database, Vendor has been disabled as a result!"; - log.Error($"[VENDOR] {Name} (0x{Guid}:{WeenieClassId}) Currency {errorMsg}"); + log.LogError("[VENDOR] {Name} (0x{Guid}:{WeenieClassId}) Currency {ErrorMsg}", Name, Guid, WeenieClassId, errorMsg); success = false; } if (!MerchandiseItemTypes.HasValue) { - log.Error($"[VENDOR] {Name} (0x{Guid}:{WeenieClassId}) MerchandiseItemTypes is NULL, Vendor has been disabled as a result!"); + log.LogError("[VENDOR] {Name} (0x{Guid}:{WeenieClassId}) MerchandiseItemTypes is NULL, Vendor has been disabled as a result!", Name, Guid, WeenieClassId); success = false; } if (!MerchandiseMinValue.HasValue) { - log.Error($"[VENDOR] {Name} (0x{Guid}:{WeenieClassId}) MerchandiseMinValue is NULL, Vendor has been disabled as a result!"); + log.LogError("[VENDOR] {Name} (0x{Guid}:{WeenieClassId}) MerchandiseMinValue is NULL, Vendor has been disabled as a result!", Name, Guid, WeenieClassId); success = false; } if (!MerchandiseMaxValue.HasValue) { - log.Error($"[VENDOR] {Name} (0x{Guid}:{WeenieClassId}) MerchandiseMaxValue is NULL, Vendor has been disabled as a result!"); + log.LogError("[VENDOR] {Name} (0x{Guid}:{WeenieClassId}) MerchandiseMaxValue is NULL, Vendor has been disabled as a result!", Name, Guid, WeenieClassId); success = false; } if (!BuyPrice.HasValue) { - log.Error($"[VENDOR] {Name} (0x{Guid}:{WeenieClassId}) BuyPrice is NULL, Vendor has been disabled as a result!"); + log.LogError("[VENDOR] {Name} (0x{Guid}:{WeenieClassId}) BuyPrice is NULL, Vendor has been disabled as a result!", Name, Guid, WeenieClassId); success = false; } if (!SellPrice.HasValue) { - log.Error($"[VENDOR] {Name} (0x{Guid}:{WeenieClassId}) SellPrice is NULL, Vendor has been disabled as a result!"); + log.LogError("[VENDOR] {Name} (0x{Guid}:{WeenieClassId}) SellPrice is NULL, Vendor has been disabled as a result!", Name, Guid, WeenieClassId); success = false; } @@ -315,7 +315,7 @@ public void DoVendorEmote(VendorType vendorType, WorldObject player) break; default: - log.Warn($"Vendor.DoVendorEmote - Encountered Unhandled VendorType {vendorType} for {Name} ({WeenieClassId})"); + log.LogWarning("Vendor.DoVendorEmote - Encountered Unhandled VendorType {VendorType} for {Name} ({WeenieClassId})", vendorType, Name, WeenieClassId); break; } } @@ -455,7 +455,7 @@ public bool BuyItems_ValidateTransaction(List itemProfiles, Player if (!requestedGuids.Add(itemProfile.ObjectGuid)) { - log.Warn($"[VENDOR] {player.Name} tried to buy duplicate item {itemProfile.ObjectGuid:X8} from {Name}"); + log.LogWarning("[VENDOR] {PlayerName} tried to buy duplicate item {ObjectGuid:X8} from {Name}", player.Name, itemProfile.ObjectGuid, Name); player.SendTransientError($"Invalid item"); return false; } @@ -655,7 +655,7 @@ public void ProcessItemsForPurchase(Player player, Dictionary if (!UniqueItemsForSale.TryAdd(item.Guid, item)) { var sellItems = string.Join(", ", items.Values.Select(i => $"{i.Name} ({i.Guid})")); - log.Error($"[VENDOR] {Name}.ProcessItemsForPurchase({player.Name}): duplicate item found, sell list: {sellItems}"); + log.LogError("[VENDOR] {Name}.ProcessItemsForPurchase({PlayerName}): duplicate item found, sell list: {SellItems}", Name, player.Name, sellItems); } item.SoldTimestamp = Time.GetUnixTime(); @@ -722,7 +722,7 @@ private void RotUniques() if (soldTime == null) { - log.Warn($"[VENDOR] Vendor {Name} has unique item {uniqueItem.Name} ({uniqueItem.Guid}) without a SoldTimestamp -- this shouldn't happen"); + log.LogWarning("[VENDOR] Vendor {Name} has unique item {UniqueItemName} ({Guid}) without a SoldTimestamp -- this shouldn't happen", Name, uniqueItem.Name, uniqueItem.Guid); continue; // keep in list? } @@ -742,7 +742,7 @@ private void RotUniques() { foreach (var itemToRemove in itemsToRemove) { - log.DebugFormat("[VENDOR] Vendor {0} has discontinued sale of {1} and removed it from its UniqueItemsForSale list.", Name, itemToRemove.Name); + log.LogDebug("[VENDOR] Vendor {Name} has discontinued sale of {ItemToRemoveName} and removed it from its UniqueItemsForSale list.", Name, itemToRemove.Name); UniqueItemsForSale.Remove(itemToRemove.Guid); itemToRemove.Destroy(); // even though it has already been removed from the db at this point, we want to mark as freed in guid manager now diff --git a/Source/ACE.Server/WorldObjects/WorldObject_Database.cs b/Source/ACE.Server/WorldObjects/WorldObject_Database.cs index ec1671c2aa..de3abca5ae 100644 --- a/Source/ACE.Server/WorldObjects/WorldObject_Database.cs +++ b/Source/ACE.Server/WorldObjects/WorldObject_Database.cs @@ -1,8 +1,9 @@ using System; using System.Threading; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.Database; using ACE.Entity.Enum; using ACE.Entity.Models; @@ -166,7 +167,7 @@ public bool IsDynamicThatShouldPersistToShard() var missile = Missile; if (missile.HasValue && missile.Value) { - log.Warn($"Missile: WeenieClassId: {WeenieClassId}, Name: {Name}, WeenieType: {WeenieType}, detected in IsDynamicThatShouldPersistToShard() that wasn't caught by prior check."); + log.LogWarning("Missile: WeenieClassId: {WeenieClassId}, Name: {Name}, WeenieType: {WeenieType}, detected in IsDynamicThatShouldPersistToShard() that wasn't caught by prior check.", WeenieClassId, Name, WeenieType); return false; } diff --git a/Source/ACE.Server/WorldObjects/WorldObject_Decay.cs b/Source/ACE.Server/WorldObjects/WorldObject_Decay.cs index 04e7dd7974..e26e7eb89a 100644 --- a/Source/ACE.Server/WorldObjects/WorldObject_Decay.cs +++ b/Source/ACE.Server/WorldObjects/WorldObject_Decay.cs @@ -1,7 +1,8 @@ using System; using System.Linq; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Entity; using ACE.Entity.Enum; using ACE.Server.Entity.Actions; @@ -61,7 +62,7 @@ public void Decay(TimeSpan elapsed) TimeToRot = DefaultTimeToRot.TotalSeconds; if (this is Corpse && Level.HasValue) - log.InfoFormat("[CORPSE] {0} (0x{1}).Decay: TimeToRot had no value, set to {2}", Name, Guid, TimeToRot); + log.LogInformation("[CORPSE] {Name} (0x{Guid}).Decay: TimeToRot had no value, set to {TimeToRot}", Name, Guid, TimeToRot); return; } @@ -77,7 +78,7 @@ public void Decay(TimeSpan elapsed) { TimeToRot = Corpse.EmptyDecayTime; if (Level.HasValue && PropertyManager.GetBool("corpse_decay_tick_logging").Item) - log.InfoFormat("[CORPSE] {0} (0x{1}).Decay({2}): InventoryLoaded = {3} | Inventory.Count = {4} | previous TimeToRot: {5} | current TimeToRot: {6}", corpse.Name, corpse.Guid, elapsed, corpse.InventoryLoaded, corpse.Inventory.Count, previousTTR, TimeToRot); + log.LogInformation("[CORPSE] {Name} (0x{Guid}).Decay({Elapsed}): InventoryLoaded = {InventoryLoaded} | Inventory.Count = {Count} | previous TimeToRot: {PreviousTTR} | current TimeToRot: {TimeToRot}", corpse.Name, corpse.Guid, elapsed, corpse.InventoryLoaded, corpse.Inventory.Count, previousTTR, TimeToRot); return; } } @@ -87,7 +88,7 @@ public void Decay(TimeSpan elapsed) TimeToRot -= elapsed.TotalSeconds; if (this is Corpse && Level.HasValue && PropertyManager.GetBool("corpse_decay_tick_logging").Item) - log.InfoFormat("[CORPSE] {0} (0x{1}).Decay({2}): previous TimeToRot: {3} | current TimeToRot: {4}", corpse.Name, corpse.Guid, elapsed, previousTTR, TimeToRot); + log.LogInformation("[CORPSE] {Name} (0x{Guid}).Decay({Elapsed}): previous TimeToRot: {PreviousTTR} | current TimeToRot: {TimeToRot}", corpse.Name, corpse.Guid, elapsed, previousTTR, TimeToRot); // Is there still time left? if (TimeToRot > 0) @@ -96,7 +97,7 @@ public void Decay(TimeSpan elapsed) TimeToRot = -2; // We force it to -2 to make sure it doesn't end up at 0 or -1. 0 indicates instant rot. -1 indicates no rot. 0 and -1 can be found in weenie defaults if (this is Corpse && Level.HasValue && PropertyManager.GetBool("corpse_decay_tick_logging").Item) - log.InfoFormat("[CORPSE] {0} (0x{1}).Decay({2}): previous TimeToRot: {3} | current TimeToRot: {4}", corpse.Name, corpse.Guid, elapsed, previousTTR, TimeToRot); + log.LogInformation("[CORPSE] {Name} (0x{Guid}).Decay({Elapsed}): previous TimeToRot: {PreviousTTR} | current TimeToRot: {TimeToRot}", corpse.Name, corpse.Guid, elapsed, previousTTR, TimeToRot); } if (this is Container container && container.IsOpen) @@ -132,7 +133,7 @@ public void Decay(TimeSpan elapsed) if (pukedItems.EndsWith(", ")) pukedItems = pukedItems.Substring(0, pukedItems.Length - 2); - log.Info($"[CORPSE] {corpse.Name} (0x{corpse.Guid}) at {corpse.Location.ToLOCString()} has decayed{((pukedItems == "") ? "" : $" and placed the following items on the landblock: {pukedItems}")}."); + log.LogInformation("[CORPSE] {Name} (0x{Guid}) at {Location} has decayed{PukedItemsNote}.", corpse.Name, corpse.Guid, corpse.Location.ToLOCString(), ((pukedItems == "") ? "" : $" and placed the following items on the landblock: {pukedItems}")); } if (corpse != null) diff --git a/Source/ACE.Server/WorldObjects/WorldObject_Generators.cs b/Source/ACE.Server/WorldObjects/WorldObject_Generators.cs index 7a8ba4dc5b..63eea1e6e1 100644 --- a/Source/ACE.Server/WorldObjects/WorldObject_Generators.cs +++ b/Source/ACE.Server/WorldObjects/WorldObject_Generators.cs @@ -2,8 +2,9 @@ using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.Entity.Enum; using ACE.Entity.Models; using ACE.Server.Entity; @@ -61,7 +62,7 @@ public void InitializeGenerator() // defaulting to Max == Init for our purposes. if ((MaxGeneratedObjects <= 0 || MaxGeneratedObjects < InitGeneratedObjects) && InitGeneratedObjects > 0) { - log.Warn($"[GENERATOR] 0x{Guid.Full} {Name}.InitializeGenerator: {WeenieClassName} ({WeenieClassId}) MaxGeneratedObjects = {MaxGeneratedObjects} | InitGeneratedObjects = {InitGeneratedObjects}. Setting MaxGeneratedObjects = InitGeneratedObjects"); + log.LogWarning("[GENERATOR] 0x{Guid} {Name}.InitializeGenerator: {WeenieClassName} ({WeenieClassId}) MaxGeneratedObjects = {MaxGeneratedObjects} | InitGeneratedObjects = {InitGeneratedObjects}. Setting MaxGeneratedObjects = InitGeneratedObjects", Guid.Full, Name, WeenieClassName, WeenieClassId, MaxGeneratedObjects, InitGeneratedObjects); MaxGeneratedObjects = InitGeneratedObjects; } @@ -140,13 +141,13 @@ public void SelectAProfile() { if (profile.Biota.InitCreate > 1) { - log.Warn($"[GENERATOR] 0x{Guid} {Name}.SelectAProfile(): profile[{i}].RegenLocationType({profile.RegenLocationType}), profile.Biota.WCID({profile.Biota.WeenieClassId}), profile.Biota.InitCreate({profile.Biota.InitCreate}) > 1, set to 1. WCID: {WeenieClassId} - LOC: {Location.ToLOCString()}"); + log.LogWarning("[GENERATOR] 0x{Guid} {Name}.SelectAProfile(): profile[{I}].RegenLocationType({RegenLocationType}), profile.Biota.WCID({BiotaWeenieClassId}), profile.Biota.InitCreate({InitCreate}) > 1, set to 1. WCID: {WeenieClassId} - LOC: {Location}", Guid, Name, i, profile.RegenLocationType, profile.Biota.WeenieClassId, profile.Biota.InitCreate, WeenieClassId, Location.ToLOCString()); profile.Biota.InitCreate = 1; } if (profile.Biota.MaxCreate > 1) { - log.Warn($"[GENERATOR] 0x{Guid} {Name}.SelectAProfile(): profile[{i}].RegenLocationType({profile.RegenLocationType}), profile.Biota.WCID({profile.Biota.WeenieClassId}), profile.Biota.MaxCreate({profile.Biota.MaxCreate}) > 1, set to 1. WCID: {WeenieClassId} - LOC: {Location.ToLOCString()}"); + log.LogWarning("[GENERATOR] 0x{Guid} {Name}.SelectAProfile(): profile[{I}].RegenLocationType({RegenLocationType}), profile.Biota.WCID({BiotaWeenieClassId}), profile.Biota.MaxCreate({MaxCreate}) > 1, set to 1. WCID: {WeenieClassId} - LOC: {Location}", Guid, Name, i, profile.RegenLocationType, profile.Biota.WeenieClassId, profile.Biota.MaxCreate, WeenieClassId, Location.ToLOCString()); profile.Biota.MaxCreate = 1; } } @@ -307,9 +308,9 @@ public int GetSpawnObjectsForProfile(GeneratorProfile profile) numObjects = profileSlotsAvailable; if (numObjects == 0 && initCreate == 0) - log.Warn($"[GENERATOR] 0x{Guid}:{WeenieClassId} {Name}.GetSpawnObjectsForProfile(profile[{profile.LinkId}]): profile.InitCreate = {profile.InitCreate} | profile.MaxCreate = {profile.MaxCreate} | profile.WeenieClassId = {profile.WeenieClassId} | Profile Init invalid, cannot spawn."); + log.LogWarning("[GENERATOR] 0x{Guid}:{WeenieClassId} {Name}.GetSpawnObjectsForProfile(profile[{LinkId}]): profile.InitCreate = {InitCreate} | profile.MaxCreate = {MaxCreate} | profile.WeenieClassId = {ProfileWeenieClassId} | Profile Init invalid, cannot spawn.", Guid, WeenieClassId, Name, profile.LinkId, profile.InitCreate, profile.MaxCreate, profile.WeenieClassId); else if (numObjects == 0) - log.Warn($"[GENERATOR] 0x{Guid}:{WeenieClassId} {Name}.GetSpawnObjectsForProfile(profile[{profile.LinkId}]): profile.InitCreate = {profile.InitCreate} | profile.MaxCreate = {profile.MaxCreate} | profile.WeenieClassId = {profile.WeenieClassId} | genSlotsAvailable = {genSlotsAvailable} | profileSlotsAvailable = {profileSlotsAvailable} | numObjects = {numObjects}, cannot spawn."); + log.LogWarning("[GENERATOR] 0x{Guid}:{WeenieClassId} {Name}.GetSpawnObjectsForProfile(profile[{LinkId}]): profile.InitCreate = {InitCreate} | profile.MaxCreate = {MaxCreate} | profile.WeenieClassId = {ProfileWeenieClassId} | genSlotsAvailable = {GenSlotsAvailable} | profileSlotsAvailable = {ProfileSlotsAvailable} | numObjects = {NumObjects}, cannot spawn.", Guid, WeenieClassId, Name, profile.LinkId, profile.InitCreate, profile.MaxCreate, profile.WeenieClassId, genSlotsAvailable, profileSlotsAvailable, numObjects); return numObjects; } @@ -670,7 +671,7 @@ public void Generator_Generate() if (genLoopCount > 1000) { - log.Error($"[GENERATOR] 0x{Guid} {Name}.Generator_Generate(): genLoopCount > 1000, aborted init spawn. GenStopSelectProfileConditions: {GenStopSelectProfileConditions} | InitCreate: {InitCreate} | CurrentCreate: {CurrentCreate} | WCID: {WeenieClassId} - LOC: {Location.ToLOCString()}"); + log.LogError("[GENERATOR] 0x{Guid} {Name}.Generator_Generate(): genLoopCount > 1000, aborted init spawn. GenStopSelectProfileConditions: {GenStopSelectProfileConditions} | InitCreate: {InitCreate} | CurrentCreate: {CurrentCreate} | WCID: {WeenieClassId} - LOC: {Location}", Guid, Name, GenStopSelectProfileConditions, InitCreate, CurrentCreate, WeenieClassId, Location.ToLOCString()); break; } } diff --git a/Source/ACE.Server/WorldObjects/WorldObject_Magic.cs b/Source/ACE.Server/WorldObjects/WorldObject_Magic.cs index 8cc35f3b32..bfe8d0502a 100644 --- a/Source/ACE.Server/WorldObjects/WorldObject_Magic.cs +++ b/Source/ACE.Server/WorldObjects/WorldObject_Magic.cs @@ -5,8 +5,9 @@ using System.Numerics; using System.Text; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.Database; using ACE.DatLoader; using ACE.DatLoader.FileTypes; @@ -930,7 +931,7 @@ private void HandleCastSpell_Projectile(Spell spell, WorldObject target, WorldOb } else { - log.Warn($"Unknown DamageType ({spell.DamageType}) for LifeProjectile {spell.Name} - {spell.Id}"); + log.LogWarning("Unknown DamageType ({DamageType}) for LifeProjectile {Name} - {Id}", spell.DamageType, spell.Name, spell.Id); return; } } @@ -1511,7 +1512,7 @@ public List CreateSpellProjectiles(Spell spell, WorldObject tar { if (spell.NumProjectiles == 0) { - log.Error($"{Name} ({Guid}).CreateSpellProjectiles({spell.Id} - {spell.Name}) - spell.NumProjectiles == 0"); + log.LogError("{Name} ({Guid}).CreateSpellProjectiles({Id} - {SpellName}) - spell.NumProjectiles == 0", Name, Guid, spell.Id, spell.Name); return new List(); } @@ -1776,7 +1777,7 @@ public List LaunchSpellProjectiles(Spell spell, WorldObject tar if (sp == null) { - log.Error($"{Name} ({Guid}).LaunchSpellProjectiles({spell.Id} - {spell.Name}) - failed to create spell projectile from wcid {spell.Wcid}"); + log.LogError("{Name} ({Guid}).LaunchSpellProjectiles({Id} - {SpellName}) - failed to create spell projectile from wcid {Wcid}", Name, Guid, spell.Id, spell.Name, spell.Wcid); break; } @@ -1864,13 +1865,13 @@ private float GetProjectileRadius(Spell spell) if (weenie == null) { - log.Error($"{Name} ({Guid}).GetSetupRadius({spell.Id} - {spell.Name}): couldn't find weenie {projectileWcid}"); + log.LogError("{Name} ({Guid}).GetSetupRadius({Id} - {SpellName}): couldn't find weenie {ProjectileWcid}", Name, Guid, spell.Id, spell.Name, projectileWcid); return 0.0f; } if (!weenie.PropertiesDID.TryGetValue(PropertyDataId.Setup, out var setupId)) { - log.Error($"{Name} ({Guid}).GetSetupRadius({spell.Id} - {spell.Name}): couldn't find setup ID for {weenie.WeenieClassId} - {weenie.ClassName}"); + log.LogError("{Name} ({Guid}).GetSetupRadius({Id} - {SpellName}): couldn't find setup ID for {WeenieClassId} - {ClassName}", Name, Guid, spell.Id, spell.Name, weenie.WeenieClassId, weenie.ClassName); return 0.0f; } @@ -1906,13 +1907,13 @@ private float GetProjectileSpeed(Spell spell, float? distance = null) if (weenie == null) { - log.Error($"{Name} ({Guid}).GetSpellProjectileSpeed({spell.Id} - {spell.Name}, {distance}): couldn't find weenie {projectileWcid}"); + log.LogError("{Name} ({Guid}).GetSpellProjectileSpeed({Id} - {SpellName}, {Distance}): couldn't find weenie {ProjectileWcid}", Name, Guid, spell.Id, spell.Name, distance, projectileWcid); return 0.0f; } if (!weenie.PropertiesFloat.TryGetValue(PropertyFloat.MaximumVelocity, out var maxVelocity)) { - log.Error($"{Name} ({Guid}).GetSpellProjectileSpeed({spell.Id} - {spell.Name}, {distance}): couldn't find MaxVelocity for {weenie.WeenieClassId} - {weenie.ClassName}"); + log.LogError("{Name} ({Guid}).GetSpellProjectileSpeed({Id} - {SpellName}, {Distance}): couldn't find MaxVelocity for {WeenieClassId} - {ClassName}", Name, Guid, spell.Id, spell.Name, distance, weenie.WeenieClassId, weenie.ClassName); return 0.0f; } @@ -2025,7 +2026,7 @@ public float CalculateDotEnchantment_StatModValue(Spell spell, WorldObject targe if (spell.Category != SpellCategory.NetherDamageOverTimeRaising && spell.Category != SpellCategory.NetherDamageOverTimeRaising2 && spell.Category != SpellCategory.NetherDamageOverTimeRaising3) { - log.Error($"{Name}.CalculateDamageOverTimeBase({spell.Id} - {spell.Name}, {target?.Name}) - unknown dot spell category {spell.Category}"); + log.LogError("{Name}.CalculateDamageOverTimeBase({Id} - {SpellName}, {TargetName}) - unknown dot spell category {Category}", Name, spell.Id, spell.Name, target?.Name, spell.Category); return enchantment_statModVal; } diff --git a/Source/ACE.Server/WorldObjects/WorldObject_Networking.cs b/Source/ACE.Server/WorldObjects/WorldObject_Networking.cs index 9899f86bea..7afa877129 100644 --- a/Source/ACE.Server/WorldObjects/WorldObject_Networking.cs +++ b/Source/ACE.Server/WorldObjects/WorldObject_Networking.cs @@ -4,7 +4,8 @@ using System.Linq; using System.Numerics; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.DatLoader; using ACE.DatLoader.Entity; using ACE.DatLoader.FileTypes; @@ -449,7 +450,7 @@ public virtual void SendPartialUpdates(Session targetSession, List 0)) - log.WarnFormat("Item 0x{0:X8}:{1} has enqueued an action but is not attached to a landblock.", Guid.Full, Name); + log.LogWarning("Item 0x{Guid:X8}:{Name} has enqueued an action but is not attached to a landblock.", Guid.Full, Name); } WorldManager.EnqueueAction(action); @@ -346,7 +347,7 @@ public virtual bool UpdateObjectPhysics() spellProjectile.DebugVelocity++; if (spellProjectile.DebugVelocity == 30) - log.Error($"Spell projectile w/ zero velocity detected @ {spellProjectile.Location.ToLOCString()}, launched by {spellProjectile.ProjectileSource?.Name} ({spellProjectile.ProjectileSource?.Guid}), spell ID {spellProjectile.Spell?.Id} - {spellProjectile.Spell?.Name}"); + log.LogError("Spell projectile w/ zero velocity detected @ {Location}, launched by {ProjectileSourceName} ({Guid}), spell ID {Id} - {SpellName}", spellProjectile.Location.ToLOCString(), spellProjectile.ProjectileSource?.Name, spellProjectile.ProjectileSource?.Guid, spellProjectile.Spell?.Id, spellProjectile.Spell?.Name); } if (spellProjectile.SpellType == ProjectileSpellType.Ring) @@ -375,7 +376,7 @@ public virtual bool UpdateObjectPhysics() if (elapsedSeconds >= 0.100) // Yea, that ain't good.... { slowUpdateObjectPhysicsHits++; - log.Warn($"[PERFORMANCE][PHYSICS] {Guid}:{Name} took {(elapsedSeconds * 1000):N1} ms to process UpdateObjectPhysics() at loc: {Location}"); + log.LogWarning("[PERFORMANCE][PHYSICS] {Guid}:{Name} took {ElapsedMs:N1} ms to process UpdateObjectPhysics() at loc: {Location}", Guid, Name, (elapsedSeconds * 1000), Location); // Destroy laggy projectiles if (slowUpdateObjectPhysicsHits >= 5 && this is SpellProjectile spellProjectile) @@ -394,10 +395,10 @@ public virtual bool UpdateObjectPhysics() PhysicsObj.set_active(false); spellProjectile.ProjectileImpact(); - log.Warn($"[PERFORMANCE][PHYSICS] {Guid}:{Name} took {(elapsedSeconds * 1000):N1} ms to process UpdateObjectPhysics() at loc: {Location}. SpellProjectile destroyed."); + log.LogWarning("[PERFORMANCE][PHYSICS] {Guid}:{Name} took {ElapsedMs:N1} ms to process UpdateObjectPhysics() at loc: {Location}. SpellProjectile destroyed.", Guid, Name, (elapsedSeconds * 1000), Location); } else - log.DebugFormat("[PERFORMANCE][PHYSICS] {0}:{1} took {2:N1} ms to process UpdateObjectPhysics() at loc: {3}", Guid, Name, (elapsedSeconds * 1000), Location); + log.LogDebug("[PERFORMANCE][PHYSICS] {Guid}:{Name} took {ElapsedMs:N1} ms to process UpdateObjectPhysics() at loc: {Location}", Guid, Name, (elapsedSeconds * 1000), Location); } } } diff --git a/Source/ACE.Server/WorldObjects/WorldObject_Use.cs b/Source/ACE.Server/WorldObjects/WorldObject_Use.cs index 9dae4e28fb..7b74760e43 100644 --- a/Source/ACE.Server/WorldObjects/WorldObject_Use.cs +++ b/Source/ACE.Server/WorldObjects/WorldObject_Use.cs @@ -1,6 +1,7 @@ using System; -using ACE.Common.Logging; +using Microsoft.Extensions.Logging; + using ACE.Entity; using ACE.Entity.Enum; using ACE.Entity.Enum.Properties; @@ -137,7 +138,7 @@ public virtual void OnActivate(WorldObject activator) activationTarget.OnActivate(activator); else { - log.Warn($"{Name}.OnActivate({activator.Name}): couldn't find activation target {ActivationTarget:X8}"); + log.LogWarning("{Name}.OnActivate({ActivatorName}): couldn't find activation target {ActivationTarget:X8}", Name, activator.Name, ActivationTarget); } } } @@ -147,7 +148,7 @@ public virtual void ActOnUse(WorldObject activator) // empty base - individual WorldObject types should override var msg = $"{Name}.ActOnUse({activator.Name}) - undefined for wcid {WeenieClassId} type {WeenieType}"; - log.Error(msg); + log.LogError("{Message:l}", msg); if (activator is Player _player) _player.Session.Network.EnqueueSend(new GameMessageSystemChat(msg, ChatMessageType.Broadcast)); @@ -196,7 +197,7 @@ public virtual ActivationResult CheckUseRequirements(WorldObject activator) if (activator == null) { - log.Error($"0x{Guid}:{Name}.CheckUseRequirements() (wcid: {WeenieClassId}): activator is null"); + log.LogError("0x{Guid}:{Name}.CheckUseRequirements() (wcid: {WeenieClassId}): activator is null", Guid, Name, WeenieClassId); return new ActivationResult(false); } diff --git a/Source/ACE.Server/WorldObjects/WorldObject_Weapon.cs b/Source/ACE.Server/WorldObjects/WorldObject_Weapon.cs index f13734c5bb..e1b969305b 100644 --- a/Source/ACE.Server/WorldObjects/WorldObject_Weapon.cs +++ b/Source/ACE.Server/WorldObjects/WorldObject_Weapon.cs @@ -1,7 +1,8 @@ using System; +using Microsoft.Extensions.Logging; + using ACE.Common; -using ACE.Common.Logging; using ACE.Entity.Enum; using ACE.Entity.Enum.Properties; using ACE.Server.Entity; @@ -474,7 +475,7 @@ public static float GetWeaponResistanceModifier(WorldObject weapon, Creature wie var rendDamageType = GetRendDamageType(damageType); if (rendDamageType == ImbuedEffectType.Undef) - log.DebugFormat("{0}.GetRendDamageType({1}) unexpected damage type for {2} ({3})", wielder.Name, damageType, weapon.Name, weapon.Guid); + log.LogDebug("{WielderName}.GetRendDamageType({DamageType}) unexpected damage type for {WeaponName} ({Guid})", wielder.Name, damageType, weapon.Name, weapon.Guid); if (rendDamageType != ImbuedEffectType.Undef && weapon.HasImbuedEffect(rendDamageType) && skill != null) { @@ -871,7 +872,7 @@ public static ImbuedSkillType GetImbuedSkillType(CreatureSkill skill) return ImbuedSkillType.Magic; default: - log.DebugFormat("WorldObject_Weapon.GetImbuedSkillType({0}): unexpected skill", skill?.Skill); + log.LogDebug("WorldObject_Weapon.GetImbuedSkillType({Skill}): unexpected skill", skill?.Skill); return ImbuedSkillType.Undef; } } @@ -1057,7 +1058,7 @@ public AttackType GetAttackType(MotionStance stance, float powerLevel, bool offh if ((attackType & AttackType.Offhand) != 0) { - log.Warn($"{Name} ({Guid}, {WeenieClassId}).GetAttackType(): {attackType}"); + log.LogWarning("{Name} ({Guid}, {WeenieClassId}).GetAttackType(): {AttackType}", Name, Guid, WeenieClassId, attackType); attackType &= ~AttackType.Offhand; } @@ -1169,7 +1170,7 @@ public AttackType GetOffhandAttackType(MotionStance stance, float powerLevel) if ((attackType & AttackType.Offhand) != 0) { - log.Warn($"{Name} ({Guid}, {WeenieClassId}).GetOffhandAttackType(): {attackType}"); + log.LogWarning("{Name} ({Guid}, {WeenieClassId}).GetOffhandAttackType(): {AttackType}", Name, Guid, WeenieClassId, attackType); attackType &= ~AttackType.Offhand; }