Logging with TimeStampFormat; rest improvement, etc.

This commit is contained in:
Lucca Faria Ferri 2023-02-10 09:56:30 -08:00
parent b8c68c3db8
commit d9328a69e4
11 changed files with 47 additions and 28 deletions

View File

@ -13,12 +13,13 @@ public class AnsiTarget : LogTarget
private static CancellationTokenSource CancellationTokenSource { get; } = new CancellationTokenSource(); private static CancellationTokenSource CancellationTokenSource { get; } = new CancellationTokenSource();
private static bool _shutdown = true; private static bool _shutdown = true;
public AnsiTarget(Logger.Level minLevel, Logger.Level maxLevel, bool includeTimeStamps) public AnsiTarget(Logger.Level minLevel, Logger.Level maxLevel, bool includeTimeStamps, string timeStampFormat)
{ {
_shutdown = false; _shutdown = false;
MinimumLevel = minLevel; MinimumLevel = minLevel;
MaximumLevel = maxLevel; MaximumLevel = maxLevel;
IncludeTimeStamps = includeTimeStamps; IncludeTimeStamps = includeTimeStamps;
TimeStampFormat = timeStampFormat;
_table = new Table().Expand().ShowFooters().ShowHeaders().Border(TableBorder.Rounded); _table = new Table().Expand().ShowFooters().ShowHeaders().Border(TableBorder.Rounded);
@ -78,7 +79,6 @@ public class AnsiTarget : LogTarget
const string less = "deepskyblue2"; const string less = "deepskyblue2";
const string diablo = "red3_1"; const string diablo = "red3_1";
const string d3 = "red"; const string d3 = "red";
const string mpq = "underline deepskyblue2";
const string sql = "underline dodgerblue1"; const string sql = "underline dodgerblue1";
const string discord = "underline blue"; const string discord = "underline blue";
const string notNull = "green"; const string notNull = "green";
@ -89,14 +89,12 @@ public class AnsiTarget : LogTarget
.Replace("Diablo III", $"[{diablo}]Diablo[/] [{d3}]III[/]", StringComparison.CurrentCultureIgnoreCase) .Replace("Diablo III", $"[{diablo}]Diablo[/] [{d3}]III[/]", StringComparison.CurrentCultureIgnoreCase)
.Replace(@"D3\.", $"[{diablo}]D[/][{d3}]3[/]", StringComparison.CurrentCultureIgnoreCase) //D3.* .Replace(@"D3\.", $"[{diablo}]D[/][{d3}]3[/]", StringComparison.CurrentCultureIgnoreCase) //D3.*
.Replace("MPQ", $"[{mpq}]MPQ[/]")
.Replace("SQL", $"[{sql}]SQL[/]") .Replace("SQL", $"[{sql}]SQL[/]")
.Replace("Discord", $"[{discord}]Discord[/]", StringComparison.CurrentCultureIgnoreCase) .Replace("Discord", $"[{discord}]Discord[/]", StringComparison.CurrentCultureIgnoreCase)
.Replace("not null", $"[{notNull}]is not null[/]", StringComparison.CurrentCultureIgnoreCase)
.Replace("!= null", $"[{notNull}]!= null[/]", StringComparison.CurrentCultureIgnoreCase) .Replace("null", $"[{unkNull}]null[/]", StringComparison.CurrentCultureIgnoreCase)
.Replace("is null", $"[{@null}]is null[/]", StringComparison.CurrentCultureIgnoreCase) .Replace($"not [{unkNull}]null[/]", $"[{notNull}]is not null[/]", StringComparison.CurrentCultureIgnoreCase)
.Replace("= null", $"[{@null}]= null[/]", StringComparison.CurrentCultureIgnoreCase) .Replace($"is [{unkNull}]null[/]", $"[{@null}]is null[/]", StringComparison.CurrentCultureIgnoreCase);
.Replace("null", $"[{unkNull}]null[/]", StringComparison.CurrentCultureIgnoreCase);
} }
@ -121,7 +119,7 @@ public class AnsiTarget : LogTarget
{ {
if (IncludeTimeStamps) if (IncludeTimeStamps)
_table.AddRow( _table.AddRow(
new Markup(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.fff"), GetStyleByLevel(level)), new Markup(DateTime.Now.ToString(TimeStampFormat), GetStyleByLevel(level)),
new Markup(level.ToString(), GetStyleByLevel(level)).RightJustified(), new Markup(level.ToString(), GetStyleByLevel(level)).RightJustified(),
new Markup(logger, GetStyleByLevel(level)).LeftJustified(), new Markup(logger, GetStyleByLevel(level)).LeftJustified(),
new Markup(Cleanup(message), GetStyleByLevel(level)).LeftJustified(), new Markup(Cleanup(message), GetStyleByLevel(level)).LeftJustified(),
@ -145,7 +143,7 @@ public class AnsiTarget : LogTarget
if (IncludeTimeStamps) if (IncludeTimeStamps)
{ {
_table.AddRow( _table.AddRow(
new Markup(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.fff"), GetStyleByLevel(level)), new Markup(DateTime.Now.ToString(TimeStampFormat), GetStyleByLevel(level)),
new Markup(level.ToString(), GetStyleByLevel(level)).RightJustified(), new Markup(level.ToString(), GetStyleByLevel(level)).RightJustified(),
new Markup(logger, GetStyleByLevel(level)).LeftJustified(), new Markup(logger, GetStyleByLevel(level)).LeftJustified(),
new Markup(Cleanup(message), GetStyleByLevel(level)).LeftJustified(), new Markup(Cleanup(message), GetStyleByLevel(level)).LeftJustified(),
@ -170,7 +168,7 @@ public class AnsiTarget : LogTarget
{ {
if (IncludeTimeStamps) if (IncludeTimeStamps)
_table.AddRow( _table.AddRow(
new Markup(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.fff"), GetStyleByLevel(level)), new Markup(DateTime.Now.ToString(TimeStampFormat), GetStyleByLevel(level)),
new Markup(level.ToString(), GetStyleByLevel(level)).RightJustified(), new Markup(level.ToString(), GetStyleByLevel(level)).RightJustified(),
new Markup(logger, GetStyleByLevel(level)).LeftJustified(), new Markup(logger, GetStyleByLevel(level)).LeftJustified(),
new Markup(Cleanup(message), GetStyleByLevel(level)).LeftJustified(), new Markup(Cleanup(message), GetStyleByLevel(level)).LeftJustified(),
@ -198,7 +196,7 @@ public class AnsiTarget : LogTarget
if (IncludeTimeStamps) if (IncludeTimeStamps)
{ {
_table.AddRow( _table.AddRow(
new Markup(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.fff"), GetStyleByLevel(level)), new Markup(DateTime.Now.ToString(TimeStampFormat), GetStyleByLevel(level)),
new Markup(level.ToString(), GetStyleByLevel(level)).RightJustified(), new Markup(level.ToString(), GetStyleByLevel(level)).RightJustified(),
new Markup(logger, GetStyleByLevel(level)).LeftJustified(), new Markup(logger, GetStyleByLevel(level)).LeftJustified(),
new Markup(Cleanup(message), GetStyleByLevel(level)).LeftJustified(), new Markup(Cleanup(message), GetStyleByLevel(level)).LeftJustified(),

View File

@ -11,11 +11,12 @@ namespace DiIiS_NA.Core.Logging
/// <param name="minLevel">Minimum level of messages to emit</param> /// <param name="minLevel">Minimum level of messages to emit</param>
/// <param name="maxLevel">Maximum level of messages to emit</param> /// <param name="maxLevel">Maximum level of messages to emit</param>
/// <param name="includeTimeStamps">Include timestamps in log?</param> /// <param name="includeTimeStamps">Include timestamps in log?</param>
public ConsoleTarget(Logger.Level minLevel, Logger.Level maxLevel, bool includeTimeStamps) public ConsoleTarget(Logger.Level minLevel, Logger.Level maxLevel, bool includeTimeStamps, string timeStampFormat)
{ {
MinimumLevel = minLevel; MinimumLevel = minLevel;
MaximumLevel = maxLevel; MaximumLevel = maxLevel;
IncludeTimeStamps = includeTimeStamps; IncludeTimeStamps = includeTimeStamps;
TimeStampFormat = timeStampFormat;
} }
@ -24,7 +25,7 @@ namespace DiIiS_NA.Core.Logging
/// <param name="message">Log message.</param> /// <param name="message">Log message.</param>
public override void LogMessage(Logger.Level level, string logger, string message) public override void LogMessage(Logger.Level level, string logger, string message)
{ {
var timeStamp = IncludeTimeStamps ? "[[" + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.fff") + "]] " : ""; var timeStamp = IncludeTimeStamps ? "[[" + DateTime.Now.ToString(TimeStampFormat) + "]] " : "";
AnsiConsole.MarkupLine($"{timeStamp}{SetColor(level, true)}[[{level.ToString(),8}]][/] {SetColor(level)}[[{Cleanup(logger),20}]]: {Cleanup(message)}[/]"); AnsiConsole.MarkupLine($"{timeStamp}{SetColor(level, true)}[[{level.ToString(),8}]][/] {SetColor(level)}[[{Cleanup(logger),20}]]: {Cleanup(message)}[/]");
} }
@ -34,10 +35,11 @@ namespace DiIiS_NA.Core.Logging
/// <param name="exception">Exception to be included with log message.</param> /// <param name="exception">Exception to be included with log message.</param>
public override void LogException(Logger.Level level, string logger, string message, Exception exception) public override void LogException(Logger.Level level, string logger, string message, Exception exception)
{ {
var timeStamp = IncludeTimeStamps ? "[[" + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.fff") + "]] " : ""; var timeStamp = IncludeTimeStamps ? "[[" + DateTime.Now.ToString(TimeStampFormat) + "]] " : "";
AnsiConsole.MarkupLine( AnsiConsole.MarkupLine(
$"{timeStamp}{SetColor(level, true)}[[{level.ToString(),8}]][/] {SetColor(level)}[[{Cleanup(logger),20}]]: {Cleanup(message)}[/] - [underline red on white][[{exception.GetType().Name}]][/][red] {Cleanup(exception.Message)}[/]"); $"{timeStamp}{SetColor(level, true)}[[{level.ToString(),8}]][/] {SetColor(level)}[[{Cleanup(logger),20}]]: {Cleanup(message)}[/] - [underline red on white][[{exception.GetType().Name}]][/][red] {Cleanup(exception.Message)}[/]");
AnsiConsole.WriteException(exception);
} }
@ -54,6 +56,7 @@ namespace DiIiS_NA.Core.Logging
/// <returns></returns> /// <returns></returns>
string Cleanup(string x) => AnsiTarget.Beautify(x.Replace("[", "[[").Replace("]", "]]").Replace("$[[/]]$", "[/]").Replace("$[[", "[").Replace("]]$", "]")); string Cleanup(string x) => AnsiTarget.Beautify(x.Replace("[", "[[").Replace("]", "]]").Replace("$[[/]]$", "[/]").Replace("$[[", "[").Replace("]]$", "]"));
/// <param name="level"></param> /// <param name="level"></param>
private static string SetColor(Logger.Level level, bool withBackground = false) private static string SetColor(Logger.Level level, bool withBackground = false)
{ {

View File

@ -22,11 +22,12 @@ namespace DiIiS_NA.Core.Logging
/// <param name="maxLevel">Maximum level of messages to emit</param> /// <param name="maxLevel">Maximum level of messages to emit</param>
/// <param name="includeTimeStamps">Include timestamps in log?</param> /// <param name="includeTimeStamps">Include timestamps in log?</param>
/// <param name="reset">Reset log file on application startup?</param> /// <param name="reset">Reset log file on application startup?</param>
public FileTarget(string fileName, Logger.Level minLevel, Logger.Level maxLevel, bool includeTimeStamps, bool reset = false) public FileTarget(string fileName, Logger.Level minLevel, Logger.Level maxLevel, bool includeTimeStamps, string timeStampFormat, bool reset = false)
{ {
MinimumLevel = minLevel; MinimumLevel = minLevel;
MaximumLevel = maxLevel; MaximumLevel = maxLevel;
IncludeTimeStamps = includeTimeStamps; IncludeTimeStamps = includeTimeStamps;
TimeStampFormat = timeStampFormat;
_fileName = fileName; _fileName = fileName;
_fileTimestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm"); _fileTimestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm");
_filePath = $"{LogConfig.Instance.LoggingRoot}/{_fileTimestamp}/{_fileName}"; _filePath = $"{LogConfig.Instance.LoggingRoot}/{_fileTimestamp}/{_fileName}";
@ -61,7 +62,7 @@ namespace DiIiS_NA.Core.Logging
/// </summary> /// </summary>
/// <param name="message"></param> /// <param name="message"></param>
/// <returns></returns> /// <returns></returns>
private string NoColors(string message) => Regex.Replace(message, @"\$\[\[?[\w\W\d\s_\-\/]+\]\]?\$", ""); private string NoColors(string message) => Regex.Replace(message, @"\$\[\[?([\w\W\d\s_\-\/]+)\]\]?\$", "$1");
/// <param name="level">Log level.</param> /// <param name="level">Log level.</param>
/// <param name="logger">Source of the log message.</param> /// <param name="logger">Source of the log message.</param>

View File

@ -22,7 +22,7 @@
base(nameof(Logging)) base(nameof(Logging))
{ } { }
public static LogConfig Instance = new(); public static readonly LogConfig Instance = new();
} }
public class LogTargetConfig : Config.Config public class LogTargetConfig : Config.Config
{ {
@ -68,6 +68,12 @@
set => Set(nameof(ResetOnStartup), value); set => Set(nameof(ResetOnStartup), value);
} }
public string TimeStampFormat
{
get => GetString(nameof(TimeStampFormat), "dd/MM/yyyy HH:mm:ss");
set => Set(nameof(TimeStampFormat), value);
}
public LogTargetConfig(string loggerName) : base(loggerName) { } public LogTargetConfig(string loggerName) : base(loggerName) { }
} }
} }

View File

@ -16,7 +16,7 @@ namespace DiIiS_NA.Core.Logging
if (LogManager.Targets.Count == 0) // if we don't have any active log-targets, if (LogManager.Targets.Count == 0) // if we don't have any active log-targets,
{ {
var t = new FileTarget(@"log.txt", Logger.Level.PacketDump, var t = new FileTarget(@"log.txt", Logger.Level.PacketDump,
Logger.Level.PacketDump, false, true); Logger.Level.PacketDump, false, "dd/MM/yyyy HH:mm:ss", true);
LogManager.Targets.Add(t); LogManager.Targets.Add(t);
}// return; // just skip }// return; // just skip

View File

@ -7,6 +7,7 @@ namespace DiIiS_NA.Core.Logging
public Logger.Level MinimumLevel { get; protected set; } public Logger.Level MinimumLevel { get; protected set; }
public Logger.Level MaximumLevel { get; protected set; } public Logger.Level MaximumLevel { get; protected set; }
public bool IncludeTimeStamps { get; protected set; } public bool IncludeTimeStamps { get; protected set; }
public string TimeStampFormat { get; protected set; }
public virtual void LogMessage(Logger.Level level, string logger, string message) public virtual void LogMessage(Logger.Level level, string logger, string message)
{ {

View File

@ -98,7 +98,7 @@ namespace DiIiS_NA.GameServer.ClientSystem
else if (message is ISelfHandler) (message as ISelfHandler).Handle(this); // if message is able to handle itself, let it do so. else if (message is ISelfHandler) (message as ISelfHandler).Handle(this); // if message is able to handle itself, let it do so.
else if (message.Id != 217) else if (message.Id != 217)
Logger.Warn("{0} - ID:{1} has no consumer or self-handler.", message.GetType(), message.Id); Logger.Warn("{0} - ID:{1} has no consumer or self-handler.", message.GetType().Name, message.Id);
} }
catch (NotImplementedException) catch (NotImplementedException)

View File

@ -917,7 +917,7 @@ namespace DiIiS_NA.GameServer.GSSystem.ActorSystem
}); });
// Reveal actor (creates actor and makes it visible to the player) // Reveal actor (creates actor and makes it visible to the player)
if (this is Player || this is NPC || this is Goblin) if (this is Player or NPC or Goblin)
player.InGameClient.SendMessage(new ACDCreateActorMessage(objId)); player.InGameClient.SendMessage(new ACDCreateActorMessage(objId));
TrickleMessage trickle = new TrickleMessage() TrickleMessage trickle = new TrickleMessage()

View File

@ -8,8 +8,10 @@ using DiIiS_NA.GameServer.GSSystem.ActorSystem.Implementations;
using DiIiS_NA.GameServer.GSSystem.MapSystem; using DiIiS_NA.GameServer.GSSystem.MapSystem;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
namespace DiIiS_NA.GameServer.GSSystem.ActorSystem namespace DiIiS_NA.GameServer.GSSystem.ActorSystem
{ {
@ -35,11 +37,12 @@ namespace DiIiS_NA.GameServer.GSSystem.ActorSystem
OnCreate.Invoke(actor, spawn); OnCreate.Invoke(actor, spawn);
} }
public static Actor Create(World world, ActorSno sno, TagMap tags) public static Actor Create(World world, ActorSno sno, TagMap tags, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0)
{ {
if (!MPQStorage.Data.Assets[SNOGroup.Actor].ContainsKey((int)sno)) if (!MPQStorage.Data.Assets[SNOGroup.Actor].ContainsKey((int)sno))
{ {
Logger.Error("$[underline on white]$Actor asset not found$[/]$, Id: $[underline white]${0}$[/]$ - $[underline white]${1}$[/]$", (int)sno, sno.ToString()); var path = Path.GetFileName(filePath);
Logger.Trace($"$[underline red on white]$Actor asset not found$[/]$, Method: $[olive]${memberName}()$[/]$ - $[underline white]${memberName}() in {path}:{lineNumber}$[/]$");
return null; return null;
} }

View File

@ -351,15 +351,21 @@ namespace DiIiS_NA
switch (targetConfig.Target.ToLower()) switch (targetConfig.Target.ToLower())
{ {
case "ansi": case "ansi":
target = new AnsiTarget(targetConfig.MinimumLevel, targetConfig.MaximumLevel, targetConfig.IncludeTimeStamps); target = new AnsiTarget(
targetConfig.MinimumLevel,
targetConfig.MaximumLevel,
targetConfig.IncludeTimeStamps,
targetConfig.TimeStampFormat);
break; break;
case "console": case "console":
target = new ConsoleTarget(targetConfig.MinimumLevel, targetConfig.MaximumLevel, target = new ConsoleTarget(targetConfig.MinimumLevel, targetConfig.MaximumLevel,
targetConfig.IncludeTimeStamps); targetConfig.IncludeTimeStamps,
targetConfig.TimeStampFormat);
break; break;
case "file": case "file":
target = new FileTarget(targetConfig.FileName, targetConfig.MinimumLevel, target = new FileTarget(targetConfig.FileName, targetConfig.MinimumLevel,
targetConfig.MaximumLevel, targetConfig.IncludeTimeStamps, targetConfig.MaximumLevel, targetConfig.IncludeTimeStamps,
targetConfig.TimeStampFormat,
targetConfig.ResetOnStartup); targetConfig.ResetOnStartup);
break; break;
} }

View File

@ -15,6 +15,7 @@ using System.IO;
using System.Net; using System.Net;
using System.Net.Security; using System.Net.Security;
using System.Web; using System.Web;
using DiIiS_NA.Core.Logging;
using DiIiS_NA.GameServer.MessageSystem; using DiIiS_NA.GameServer.MessageSystem;
using DiIiS_NA.REST.Data.Forms; using DiIiS_NA.REST.Data.Forms;
using DiIiS_NA.REST.Manager; using DiIiS_NA.REST.Manager;
@ -42,7 +43,7 @@ namespace DiIiS_NA.REST
} }
else else
{ {
Logger.Debug($"$[yellow]$REST Request: $[/]$ {httpRequest.Method} {httpRequest.Path}"); Logger.Debug($"$[yellow]$REST Request: $[/]$ {httpRequest.Method.SafeAnsi()} {httpRequest.Path.SafeAnsi()}");
if (httpRequest.Path == "200") if (httpRequest.Path == "200")
{ {
@ -66,11 +67,11 @@ namespace DiIiS_NA.REST
else else
{ {
#if DEBUG #if DEBUG
Logger.Info($"$[red]$[404] REST Request: $[/]$ {httpRequest.Method} {httpRequest.Path}"); Logger.Info($"$[red]$[404] REST Request: $[/]$ {httpRequest.Method.SafeAnsi()} {httpRequest.Path.SafeAnsi()}");
SendResponseHtml(HttpCode.NotFound, "404 Not Found"); SendResponseHtml(HttpCode.NotFound, "404 Not Found");
#else #else
// sends 502 Bad Gateway to the client to prevent the client from trying to connect to the server again - in case it's a crawler or bad bot. // sends 502 Bad Gateway to the client to prevent the client from trying to connect to the server again - in case it's a crawler or bad bot.
Logger.Info($"$[red]$[404/502] REST Request: $[/]$ {httpRequest.Method} {httpRequest.Path}"); Logger.Info($"$[red]$[404/502] REST Request: $[/]$ {httpRequest.Method.SafeAnsi()} {httpRequest.Path.SafeAnsi()}");
SendResponseHtml(HttpCode.BadGateway, "502 Bad Gateway"); SendResponseHtml(HttpCode.BadGateway, "502 Bad Gateway");
return; return;
#endif #endif