Implement log to file logger (#1494)

* Implement log to file

Logger moved to it's own namespace

* Add lock to log file
This commit is contained in:
ReinforceZwei 2021-03-07 14:23:26 +08:00 committed by GitHub
parent 62c985376e
commit 240468ad22
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 306 additions and 144 deletions

View file

@ -0,0 +1,113 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace MinecraftClient.Logger
{
public class FileLogLogger : FilteredLogger
{
private string logFile;
private bool prependTimestamp;
private object logFileLock = new object();
public FileLogLogger(string file, bool prependTimestamp = false)
{
logFile = file;
this.prependTimestamp = prependTimestamp;
Save("### Log started at " + GetTimestamp() + " ###");
}
private void LogAndSave(string msg)
{
Log(msg);
Save(msg);
}
private void Save(string msg)
{
try
{
msg = ChatBot.GetVerbatim(msg);
if (prependTimestamp)
msg = GetTimestamp() + ' ' + msg;
string directory = Path.GetDirectoryName(logFile);
if (!String.IsNullOrEmpty(directory) && !Directory.Exists(directory))
Directory.CreateDirectory(directory);
lock (logFileLock)
{
FileStream stream = new FileStream(logFile, FileMode.OpenOrCreate);
StreamWriter writer = new StreamWriter(stream);
stream.Seek(0, SeekOrigin.End);
writer.WriteLine(msg);
writer.Dispose();
stream.Close();
}
}
catch (Exception e)
{
// Must use base since we already failed to write log
base.Error("Cannot write to log file: " + e.Message);
base.Debug("Stack trace: \n" + e.StackTrace);
}
}
private static string GetTimestamp()
{
DateTime time = DateTime.Now;
return String.Format("{0}-{1}-{2} {3}:{4}:{5}",
time.Year.ToString("0000"),
time.Month.ToString("00"),
time.Day.ToString("00"),
time.Hour.ToString("00"),
time.Minute.ToString("00"),
time.Second.ToString("00"));
}
public override void Chat(string msg)
{
if (ChatEnabled)
{
if (ShouldDisplay(FilterChannel.Chat, msg))
{
LogAndSave(msg);
}
else Debug("[Logger] One Chat message filtered: " + msg);
}
}
public override void Debug(string msg)
{
if (DebugEnabled)
{
if (ShouldDisplay(FilterChannel.Debug, msg))
{
LogAndSave("§8[DEBUG] " + msg);
}
}
}
public override void Error(string msg)
{
base.Error(msg);
if (ErrorEnabled)
Save(msg);
}
public override void Info(string msg)
{
base.Info(msg);
if (InfoEnabled)
Save(msg);
}
public override void Warn(string msg)
{
base.Warn(msg);
if (WarnEnabled)
Save(msg);
}
}
}

View file

@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace MinecraftClient.Logger
{
public class FilteredLogger : LoggerBase
{
protected enum FilterChannel { Debug, Chat }
protected bool ShouldDisplay(FilterChannel channel, string msg)
{
Regex regexToUse = null;
// Convert to bool for XOR later. Whitelist = 0, Blacklist = 1
bool filterMode = Settings.FilterMode == Settings.FilterModeEnum.Blacklist ? true : false;
switch (channel)
{
case FilterChannel.Chat: regexToUse = Settings.ChatFilter; break;
case FilterChannel.Debug: regexToUse = Settings.DebugFilter; break;
}
if (regexToUse != null)
{
// IsMatch and white/blacklist result can be represented using XOR
// e.g. matched(true) ^ blacklist(true) => shouldn't log(false)
return regexToUse.IsMatch(msg) ^ filterMode;
}
else return true;
}
public override void Debug(string msg)
{
if (DebugEnabled)
{
if (ShouldDisplay(FilterChannel.Debug, msg))
{
Log("§8[DEBUG] " + msg);
}
// Don't write debug lines here as it could cause a stack overflow
}
}
public override void Info(string msg)
{
if (InfoEnabled)
ConsoleIO.WriteLogLine(msg);
}
public override void Warn(string msg)
{
if (WarnEnabled)
Log("§6[WARN] " + msg);
}
public override void Error(string msg)
{
if (ErrorEnabled)
Log("§c[ERROR] " + msg);
}
public override void Chat(string msg)
{
if (ChatEnabled)
{
if (ShouldDisplay(FilterChannel.Chat, msg))
{
Log(msg);
}
else Debug("[Logger] One Chat message filtered: " + msg);
}
}
}
}

View file

@ -3,7 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient
namespace MinecraftClient.Logger
{
public interface ILogger
{

View file

@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Logger
{
/// <summary>
/// Abstract class providing basic implementation of the ILogger interface
/// </summary>
public abstract class LoggerBase : ILogger
{
private bool debugEnabled = false;
private bool warnEnabled = true;
private bool infoEnabled = true;
private bool errorEnabled = true;
private bool chatEnabled = true;
public bool DebugEnabled { get { return debugEnabled; } set { debugEnabled = value; } }
public bool WarnEnabled { get { return warnEnabled; } set { warnEnabled = value; } }
public bool InfoEnabled { get { return infoEnabled; } set { infoEnabled = value; } }
public bool ErrorEnabled { get { return errorEnabled; } set { errorEnabled = value; } }
public bool ChatEnabled { get { return chatEnabled; } set { chatEnabled = value; } }
public abstract void Chat(string msg);
public void Chat(string msg, params object[] args)
{
Chat(string.Format(msg, args));
}
public void Chat(object msg)
{
Chat(msg.ToString());
}
public abstract void Debug(string msg);
public void Debug(string msg, params object[] args)
{
Debug(string.Format(msg, args));
}
public void Debug(object msg)
{
Debug(msg.ToString());
}
public abstract void Error(string msg);
public void Error(string msg, params object[] args)
{
Error(string.Format(msg, args));
}
public void Error(object msg)
{
Error(msg.ToString());
}
public abstract void Info(string msg);
public void Info(string msg, params object[] args)
{
Info(string.Format(msg, args));
}
public void Info(object msg)
{
Info(msg.ToString());
}
public abstract void Warn(string msg);
public void Warn(string msg, params object[] args)
{
Warn(string.Format(msg, args));
}
public void Warn(object msg)
{
Warn(msg.ToString());
}
protected virtual void Log(object msg)
{
ConsoleIO.WriteLineFormatted(msg.ToString());
}
protected virtual void Log(string msg)
{
ConsoleIO.WriteLineFormatted(msg);
}
protected virtual void Log(string msg, params object[] args)
{
ConsoleIO.WriteLineFormatted(string.Format(msg, args));
}
}
}

View file

@ -1,140 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient
{
public class MCLogger : ILogger
{
private bool debugEnabled = false;
private bool warnEnabled = true;
private bool infoEnabled = true;
private bool errorEnabled = true;
private bool chatEnabled = true;
public bool DebugEnabled { get { return debugEnabled; } set { debugEnabled = value; } }
public bool WarnEnabled { get { return warnEnabled; } set { warnEnabled = value; } }
public bool InfoEnabled { get { return infoEnabled; } set { infoEnabled = value; } }
public bool ErrorEnabled { get { return errorEnabled; } set { errorEnabled = value; } }
public bool ChatEnabled { get { return chatEnabled; } set { chatEnabled = value; } }
public void Debug(string msg)
{
if (debugEnabled)
{
if (Settings.DebugFilter != null)
{
var shouldLog = Settings.DebugFilter.IsMatch(msg); // assumed whitelist mode
if (Settings.FilterMode == Settings.FilterModeEnum.Blacklist)
shouldLog = !shouldLog; // blacklist mode so flip result
if (!shouldLog)
return;
// Don't write debug lines here as it could cause a stack overflow
}
Log("§8[DEBUG] " + msg);
}
}
public void Debug(string msg, params object[] args)
{
Debug(string.Format(msg, args));
}
public void Debug(object msg)
{
Debug(msg.ToString());
}
public void Info(object msg)
{
if (infoEnabled)
ConsoleIO.WriteLogLine(msg.ToString());
}
public void Info(string msg)
{
if (infoEnabled)
ConsoleIO.WriteLogLine(msg);
}
public void Info(string msg, params object[] args)
{
if (infoEnabled)
ConsoleIO.WriteLogLine(string.Format(msg, args));
}
public void Warn(string msg)
{
if (warnEnabled)
Log("§6[WARN] " + msg);
}
public void Warn(string msg, params object[] args)
{
Warn(string.Format(msg, args));
}
public void Warn(object msg)
{
Warn(msg.ToString());
}
public void Error(string msg)
{
if (errorEnabled)
Log("§c[ERROR] " + msg);
}
public void Error(string msg, params object[] args)
{
Error(string.Format(msg, args));
}
public void Error(object msg)
{
Error(msg.ToString());
}
public void Chat(string msg)
{
if (chatEnabled)
{
if (Settings.ChatFilter != null)
{
var shouldLog = Settings.ChatFilter.IsMatch(msg); // assumed whitelist mode
if (Settings.FilterMode == Settings.FilterModeEnum.Blacklist)
shouldLog = !shouldLog; // blacklist mode so flip result
if (shouldLog)
Log(msg);
else Debug("[Logger] One Chat message filtered: " + msg);
}
else Log(msg);
}
}
public void Chat(string msg, params object[] args)
{
Chat(string.Format(msg, args));
}
public void Chat(object msg)
{
Chat(msg.ToString());
}
private void Log(object msg)
{
ConsoleIO.WriteLineFormatted(msg.ToString());
}
private void Log(string msg)
{
ConsoleIO.WriteLineFormatted(msg);
}
private void Log(string msg, params object[] args)
{
ConsoleIO.WriteLineFormatted(string.Format(msg, args));
}
}
}

View file

@ -12,6 +12,7 @@ using MinecraftClient.Proxy;
using MinecraftClient.Protocol.Handlers.Forge;
using MinecraftClient.Mapping;
using MinecraftClient.Inventory;
using MinecraftClient.Logger;
namespace MinecraftClient
{
@ -176,7 +177,9 @@ namespace MinecraftClient
this.port = port;
this.protocolversion = protocolversion;
this.Log = new MCLogger();
this.Log = Settings.LogToFile
? new FileLogLogger(Settings.ExpandVars(Settings.LogFile), Settings.PrependTimestamp)
: new FilteredLogger();
Log.DebugEnabled = Settings.DebugMessages;
Log.InfoEnabled = Settings.InfoMessages;
Log.ChatEnabled = Settings.ChatMessages;

View file

@ -119,7 +119,8 @@
<DesignTime>True</DesignTime>
<DependentUpon>DefaultConfigResource.resx</DependentUpon>
</Compile>
<Compile Include="ILogger.cs" />
<Compile Include="Logger\FileLogLogger.cs" />
<Compile Include="Logger\ILogger.cs" />
<Compile Include="INIFile.cs" />
<Compile Include="Inventory\Container.cs" />
<Compile Include="Inventory\ContainerType.cs" />
@ -136,6 +137,7 @@
<Compile Include="Inventory\ItemType.cs" />
<Compile Include="Inventory\ItemTypeExtensions.cs" />
<Compile Include="Inventory\WindowActionType.cs" />
<Compile Include="Logger\LoggerBase.cs" />
<Compile Include="Mapping\BlockPalettes\Palette112.cs" />
<Compile Include="Mapping\BlockPalettes\Palette113.cs" />
<Compile Include="Mapping\BlockPalettes\Palette114.cs" />
@ -158,7 +160,7 @@
<Compile Include="Mapping\EntityPalettes\EntityPaletteGenerator.cs" />
<Compile Include="Mapping\EntityTypeExtensions.cs" />
<Compile Include="Mapping\MaterialExtensions.cs" />
<Compile Include="MCLogger.cs" />
<Compile Include="Logger\FilteredLogger.cs" />
<Compile Include="Protocol\EntityActionType.cs" />
<Compile Include="Protocol\GuidExtensions.cs" />
<Compile Include="Protocol\Handlers\Compression\DeflateStream.cs" />

View file

@ -17,6 +17,7 @@ using System.Data.SqlClient;
using System.Diagnostics;
using MinecraftClient.Inventory.ItemPalettes;
using MinecraftClient.Protocol.Handlers.PacketPalettes;
using MinecraftClient.Logger;
namespace MinecraftClient.Protocol.Handlers
{

View file

@ -4,6 +4,7 @@ using System.Linq;
using System.Text;
using MinecraftClient.Mapping;
using MinecraftClient.Inventory;
using MinecraftClient.Logger;
namespace MinecraftClient.Protocol
{

View file

@ -50,6 +50,9 @@ infomessages=true # Informative messages (i.e Most of the messa
#chatfilter= # Regex for filtering chat message
#debugfilter= # Regex for filtering debug message
filtermode=blacklist # blacklist OR whitelist. Blacklist hide message match regex. Whitelist show message match regex
logtofile=false # Write log messages to file
logfile=console-log-%username%-%serverip%.txt # Log file name
prependtimestamp=false # Prepend timestamp to messages in log file
[AppVars]
# yourvar=yourvalue

View file

@ -110,6 +110,9 @@ namespace MinecraftClient
public static Regex ChatFilter = null;
public static Regex DebugFilter = null;
public static FilterModeEnum FilterMode = FilterModeEnum.Blacklist;
public static bool LogToFile = false;
public static string LogFile = "console-log.txt";
public static bool PrependTimestamp = false;
//AntiAFK Settings
public static bool AntiAFK_Enabled = false;
@ -428,6 +431,9 @@ namespace MinecraftClient
else
FilterMode = FilterModeEnum.Blacklist;
break;
case "logtofile": LogToFile = str2bool(argValue); break;
case "logfile": LogFile = argValue; break;
case "prependtimestamp": PrependTimestamp = str2bool(argValue); break;
}
break;