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 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;
MinimumLevel = minLevel;
MaximumLevel = maxLevel;
IncludeTimeStamps = includeTimeStamps;
TimeStampFormat = timeStampFormat;
_table = new Table().Expand().ShowFooters().ShowHeaders().Border(TableBorder.Rounded);
@ -78,7 +79,6 @@ public class AnsiTarget : LogTarget
const string less = "deepskyblue2";
const string diablo = "red3_1";
const string d3 = "red";
const string mpq = "underline deepskyblue2";
const string sql = "underline dodgerblue1";
const string discord = "underline blue";
const string notNull = "green";
@ -89,14 +89,12 @@ public class AnsiTarget : LogTarget
.Replace("Diablo III", $"[{diablo}]Diablo[/] [{d3}]III[/]", StringComparison.CurrentCultureIgnoreCase)
.Replace(@"D3\.", $"[{diablo}]D[/][{d3}]3[/]", StringComparison.CurrentCultureIgnoreCase) //D3.*
.Replace("MPQ", $"[{mpq}]MPQ[/]")
.Replace("SQL", $"[{sql}]SQL[/]")
.Replace("Discord", $"[{discord}]Discord[/]", StringComparison.CurrentCultureIgnoreCase)
.Replace("not null", $"[{notNull}]is not null[/]", StringComparison.CurrentCultureIgnoreCase)
.Replace("!= null", $"[{notNull}]!= null[/]", StringComparison.CurrentCultureIgnoreCase)
.Replace("is null", $"[{@null}]is null[/]", StringComparison.CurrentCultureIgnoreCase)
.Replace("= null", $"[{@null}]= null[/]", StringComparison.CurrentCultureIgnoreCase)
.Replace("null", $"[{unkNull}]null[/]", StringComparison.CurrentCultureIgnoreCase);
.Replace("null", $"[{unkNull}]null[/]", StringComparison.CurrentCultureIgnoreCase)
.Replace($"not [{unkNull}]null[/]", $"[{notNull}]is not null[/]", StringComparison.CurrentCultureIgnoreCase)
.Replace($"is [{unkNull}]null[/]", $"[{@null}]is null[/]", StringComparison.CurrentCultureIgnoreCase);
}
@ -121,7 +119,7 @@ public class AnsiTarget : LogTarget
{
if (IncludeTimeStamps)
_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(logger, GetStyleByLevel(level)).LeftJustified(),
new Markup(Cleanup(message), GetStyleByLevel(level)).LeftJustified(),
@ -145,7 +143,7 @@ public class AnsiTarget : LogTarget
if (IncludeTimeStamps)
{
_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(logger, GetStyleByLevel(level)).LeftJustified(),
new Markup(Cleanup(message), GetStyleByLevel(level)).LeftJustified(),
@ -170,7 +168,7 @@ public class AnsiTarget : LogTarget
{
if (IncludeTimeStamps)
_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(logger, GetStyleByLevel(level)).LeftJustified(),
new Markup(Cleanup(message), GetStyleByLevel(level)).LeftJustified(),
@ -198,7 +196,7 @@ public class AnsiTarget : LogTarget
if (IncludeTimeStamps)
{
_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(logger, 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="maxLevel">Maximum level of messages to emit</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;
MaximumLevel = maxLevel;
IncludeTimeStamps = includeTimeStamps;
TimeStampFormat = timeStampFormat;
}
@ -24,7 +25,7 @@ namespace DiIiS_NA.Core.Logging
/// <param name="message">Log message.</param>
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)}[/]");
}
@ -34,10 +35,11 @@ namespace DiIiS_NA.Core.Logging
/// <param name="exception">Exception to be included with log message.</param>
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(
$"{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);
}
@ -53,6 +55,7 @@ namespace DiIiS_NA.Core.Logging
/// <param name="x"></param>
/// <returns></returns>
string Cleanup(string x) => AnsiTarget.Beautify(x.Replace("[", "[[").Replace("]", "]]").Replace("$[[/]]$", "[/]").Replace("$[[", "[").Replace("]]$", "]"));
/// <param name="level"></param>
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="includeTimeStamps">Include timestamps in log?</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;
MaximumLevel = maxLevel;
IncludeTimeStamps = includeTimeStamps;
TimeStampFormat = timeStampFormat;
_fileName = fileName;
_fileTimestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm");
_filePath = $"{LogConfig.Instance.LoggingRoot}/{_fileTimestamp}/{_fileName}";
@ -61,7 +62,7 @@ namespace DiIiS_NA.Core.Logging
/// </summary>
/// <param name="message"></param>
/// <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="logger">Source of the log message.</param>

View File

@ -22,7 +22,7 @@
base(nameof(Logging))
{ }
public static LogConfig Instance = new();
public static readonly LogConfig Instance = new();
}
public class LogTargetConfig : Config.Config
{
@ -67,6 +67,12 @@
get => GetBoolean(nameof(ResetOnStartup), false);
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) { }
}

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,
{
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);
}// return; // just skip

View File

@ -7,6 +7,7 @@ namespace DiIiS_NA.Core.Logging
public Logger.Level MinimumLevel { get; protected set; }
public Logger.Level MaximumLevel { 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)
{

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.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)

View File

@ -917,7 +917,7 @@ namespace DiIiS_NA.GameServer.GSSystem.ActorSystem
});
// 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));
TrickleMessage trickle = new TrickleMessage()

View File

@ -8,8 +8,10 @@ using DiIiS_NA.GameServer.GSSystem.ActorSystem.Implementations;
using DiIiS_NA.GameServer.GSSystem.MapSystem;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace DiIiS_NA.GameServer.GSSystem.ActorSystem
{
@ -35,11 +37,12 @@ namespace DiIiS_NA.GameServer.GSSystem.ActorSystem
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))
{
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;
}

View File

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

View File

@ -15,6 +15,7 @@ using System.IO;
using System.Net;
using System.Net.Security;
using System.Web;
using DiIiS_NA.Core.Logging;
using DiIiS_NA.GameServer.MessageSystem;
using DiIiS_NA.REST.Data.Forms;
using DiIiS_NA.REST.Manager;
@ -42,7 +43,7 @@ namespace DiIiS_NA.REST
}
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")
{
@ -66,11 +67,11 @@ namespace DiIiS_NA.REST
else
{
#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");
#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.
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");
return;
#endif