Skip to content

Commit

Permalink
added trace logs for sending/receiving packets and give the user the …
Browse files Browse the repository at this point in the history
…ability to enable logs with MineSharpBot.EnableDebugLogs()
  • Loading branch information
psu-de committed Jul 27, 2024
1 parent 5703cd5 commit cfd78ca
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
4 changes: 3 additions & 1 deletion Components/MineSharp.Protocol/MinecraftClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,7 @@ private void DispatchPacket(IPacket packet)

lock (streamLock)
{
Logger.Trace("Sending packet {packetType}", packet.Type);
stream!.WritePacket(buffer);
}
}
Expand All @@ -453,7 +454,8 @@ private async Task HandleIncomingPacket(PacketType packetType, PacketBuffer buff
// - MinecraftClient.WaitForPacket<T>()
// - MinecraftClient.OnPacketReceived <-- Forces all packets to be parsed
// - The internal IPacketHandler


Logger.Trace("Received packet {packetType}", packetType);
var factory = PacketPalette.GetFactory(packetType);
if (factory == null)
{
Expand Down
19 changes: 19 additions & 0 deletions MineSharp.Bot/MineSharpBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -180,4 +180,23 @@ private Task OnClientDisconnected(MinecraftClient sender, ChatComponent.Chat rea
{
return OnBotDisconnected.Dispatch(this, reason);
}

/// <summary>
/// Enable debug logs of minesharp to be written to the console and a log file.
/// Trace logs are only written to the logfile.
/// </summary>
/// <param name="trace">if true, also log trace messages.</param>
public static void EnableDebugLogs(bool trace = false)
{
var configuration = new NLog.Config.LoggingConfiguration();

var logfile = new NLog.Targets.FileTarget("customfile") { FileName = $"{DateTime.Now:dd.MM.yyyy hh:mm:ss}.log" };
var logconsole = new NLog.Targets.ConsoleTarget("logconsole");

var level = trace ? LogLevel.Trace : LogLevel.Debug;
configuration.AddRule(level, LogLevel.Fatal, logfile);
configuration.AddRule(LogLevel.Debug, LogLevel.Fatal, logconsole);

LogManager.Configuration = configuration;
}
}

0 comments on commit cfd78ca

Please sign in to comment.