Skip to content

Commit

Permalink
feat: change serilog to zlogger
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu1537 committed Nov 27, 2024
1 parent f306323 commit 19f6736
Show file tree
Hide file tree
Showing 16 changed files with 126 additions and 75 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -402,4 +402,5 @@ FodyWeavers.xsd
appsettings.local.json
CHANGELOG.md
Plugins/
Canvas/
Canvas/
Zones/
7 changes: 5 additions & 2 deletions WFDS.Common/Helpers/ConsoleHelper.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
using Serilog;
using Microsoft.Extensions.Logging;
using ZLogger;

namespace WFDS.Common.Helpers;

public static class ConsoleHelper
{
private static readonly ILogger Logger = Log.Factory.CreateLogger(typeof(ConsoleHelper).FullName ?? nameof(ConsoleHelper));

public static void UpdateConsoleTitle(string name, string code, int cur, int cap)
{
var title = $"[{cur}/{cap - 1}] {name} [{code}]";
Console.Title = title;
Log.Logger.Information("update console title : {0}", title);
Logger.ZLogInformation($"update console title : {title}");
}
}
9 changes: 6 additions & 3 deletions WFDS.Common/Helpers/SteamNetworkingHelper.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
using Serilog;
using Microsoft.Extensions.Logging;
using Steamworks;
using WFDS.Common.Steam;
using WFDS.Common.Types;
using WFDS.Godot.Binary;
using ZLogger;

namespace WFDS.Common.Helpers;

public static class SteamNetworkingHelper
{
private static readonly ILogger Logger = Log.Factory.CreateLogger(typeof(SteamNetworkingHelper).FullName ?? nameof(SteamNetworkingHelper));

public static bool SendP2PPacket(CSteamID steamId, NetChannel channel, byte[] bytes)
{
if (steamId == SteamManager.Inst.SteamId)
Expand All @@ -27,7 +30,7 @@ public static bool SendP2PPacket(CSteamID steamId, NetChannel channel, byte[] by
}
catch (Exception ex)
{
Log.Logger.Error(ex, "Failed to send P2P packet");
Logger.ZLogError(ex, $"failed to rent bytes for P2P packet");
return false;
}
}
Expand Down Expand Up @@ -60,7 +63,7 @@ public static void BroadcastP2PPacket(CSteamID lobbyId, NetChannel channel, obje
}
catch (Exception ex)
{
Log.Logger.Error(ex, "Failed to rent bytes for broadcast P2P packet");
Logger.ZLogError($"failed to rent bytes for broadcast P2P packet : \n{ex}");
}
}
}
41 changes: 41 additions & 0 deletions WFDS.Common/Log.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System.Globalization;
using Microsoft.Extensions.Logging;
using ZLogger;
using ZLogger.Providers;

namespace WFDS.Common;

public static class Log
{
public static readonly ILoggerFactory Factory = LoggerFactory.Create(logging =>
{
#if DEBUG
logging.SetMinimumLevel(LogLevel.Debug);
#else
logging.SetMinimumLevel(LogLevel.Information);
#endif

logging.AddZLoggerConsole(options =>
{
options.IncludeScopes = true;
options.UsePlainTextFormatter(formatter =>
{
formatter.SetPrefixFormatter($"[{0}] [{1:short}] [{2}] [{3}:{4}] ", (in MessageTemplate template, in LogInfo info) => template.Format(info.Timestamp.Utc.ToString("O"), info.LogLevel, info.Category, info.MemberName, info.LineNumber));
formatter.SetExceptionFormatter((writer, ex) => Utf8StringInterpolation.Utf8String.Format(writer, $"{ex.Message}"));
});
});

logging.AddZLoggerFile("Logs/latest.log", options =>
{
options.UseJsonFormatter();
});
logging.AddZLoggerRollingFile(options =>
{
options.FilePathSelector = (DateTimeOffset timestamp, int sequenceNumber) => $"logs/{timestamp.ToLocalTime():yyyyMMdd}_{sequenceNumber:000}.log";
options.RollingInterval = RollingInterval.Day;
options.RollingSizeKB = 1024;
});
});

public static readonly ILogger Logger = Factory.CreateLogger("");
}
7 changes: 4 additions & 3 deletions WFDS.Common/Network/Packets/ChalkPacket.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
using System.Numerics;
using Serilog;
using Microsoft.Extensions.Logging;
using WFDS.Common.Extensions;
using ZLogger;

namespace WFDS.Common.Network.Packets;

public class ChalkPacket : Packet
{
private static readonly ILogger Logger = Log.ForContext<ChalkPacket>();
private static readonly ILogger Logger = Log.Factory.CreateLogger<ChalkPacket>();

public long CanvasId { get; set; }
public List<object> Data { get; set; } = [];
Expand All @@ -31,7 +32,7 @@ public override void Serialize(Dictionary<object, object> data)
{
if (item.Count != 2)
{
Logger.Error("invalid chalk packet data");
Logger.ZLogError($"Invalid chalk data item");
continue;
}

Expand Down
4 changes: 2 additions & 2 deletions WFDS.Common/Network/Session.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using System.Collections.Concurrent;
using Serilog;
using Microsoft.Extensions.Logging;
using Steamworks;
using WFDS.Common.Helpers;
using WFDS.Common.Types;
Expand All @@ -8,7 +8,7 @@ namespace WFDS.Common.Network;

public sealed class Session(CSteamID steamId)
{
private ILogger Logger { get; } = Log.ForContext<Session>();
private ILogger Logger { get; } = Log.Factory.CreateLogger<Session>();
public CSteamID SteamId { get; init; } = steamId;
public string Name { get; set; } = SteamFriends.GetFriendPersonaName(steamId);
public bool HandshakeReceived { get; set; }
Expand Down
7 changes: 5 additions & 2 deletions WFDS.Common/Plugin/PluginManager.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
using System.Reflection;
using Serilog;
using Microsoft.Extensions.Logging;
using ZLogger;

namespace WFDS.Common.Plugin;

public static class PluginManager
{
private static readonly ILogger Logger = Log.Factory.CreateLogger("PluginManager");

private static void MakeDirectory()
{
var path = Path.Join(Directory.GetCurrentDirectory(), "Plugins");
Expand Down Expand Up @@ -48,7 +51,7 @@ private static IEnumerable<Plugin> LoadAssembly(string pluginFile)
var instance = Activator.CreateInstance(type);
if (instance is not Plugin plugin) return null;

Log.Logger.Information("loading plugin {Name} {Version} by {Author}", plugin.Name, plugin.Version, plugin.Author);
Logger.ZLogInformation($"loading plugin {plugin.Name} {plugin.Version} by {plugin.Author}");
plugin.Load();

return plugin;
Expand Down
17 changes: 9 additions & 8 deletions WFDS.Common/Steam/LobbyManager.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
using System.Globalization;
using Serilog;
using Microsoft.Extensions.Logging;
using Steamworks;
using WFDS.Common.Helpers;
using WFDS.Common.Types;
using ZLogger;

namespace WFDS.Common.Steam;

Expand All @@ -29,7 +30,7 @@ public class LobbyManager : Singleton<LobbyManager>, IDisposable

public LobbyManager()
{
_logger = Log.ForContext<LobbyManager>();
_logger = Log.Factory.CreateLogger<LobbyManager>();

_lobbyEnterCallback = Callback<LobbyEnter_t>.Create(OnLobbyEntered);
_lobbyCreatedCallback = Callback<LobbyCreated_t>.Create(OnLobbyCreated);
Expand Down Expand Up @@ -62,7 +63,7 @@ public void Initialize(string name, GameLobbyType lobbyType, int cap, bool adult
_code = RandomHelper.RandomRoomCode(RoomCodeLength);
}

_logger.Information("lobby initialized: {Name} {LobbyType} {Cap} {Adult} {Code}", _name, _lobbyType, _cap, _adult, _code);
_logger.ZLogInformation($"lobby initialized: {_name}, {_lobbyType}, {_cap}, {_adult}, {_code}");
}

public bool LeaveLobby(out CSteamID lobbyId)
Expand Down Expand Up @@ -223,31 +224,31 @@ private void OnLobbyCreated(LobbyCreated_t param)
{
if (param.m_eResult != EResult.k_EResultOK)
{
_logger.Error("failed to create lobby: {Result}", param.m_eResult);
_logger.ZLogError($"failed to create lobby: {param.m_eResult}");
return;
}

var lobbyId = new CSteamID(param.m_ulSteamIDLobby);
_logger.Information("lobby created: {LobbyId}", param.m_ulSteamIDLobby);
_logger.ZLogInformation($"lobby created: {param.m_ulSteamIDLobby}");
UpdateLobbyData(lobbyId);
}

private void OnLobbyEntered(LobbyEnter_t param)
{
if (param.m_EChatRoomEnterResponse != 1) // not success
{
_logger.Error("failed to enter lobby: {Result}", param.m_EChatRoomEnterResponse);
_logger.ZLogError($"failed to enter lobby: {param.m_EChatRoomEnterResponse}");
return;
}

_lobbyId = new CSteamID(param.m_ulSteamIDLobby);
_logger.Information("lobby entered: {LobbyId}", _lobbyId);
_logger.ZLogInformation($"lobby entered: {_lobbyId}");
}

private void OnLobbyDataChanged(LobbyDataUpdate_t param)
{
var lobbyId = new CSteamID(param.m_ulSteamIDLobby);
_logger.Debug("lobby data updated: {LobbyId}", lobbyId);
_logger.ZLogDebug($"lobby data updated: {lobbyId}");
}

#endregion
Expand Down
31 changes: 16 additions & 15 deletions WFDS.Common/Steam/SessionManager.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System.Collections.Concurrent;
using System.Globalization;
using Serilog;
using Microsoft.Extensions.Logging;
using Steamworks;
using WFDS.Common.GameEvents;
using WFDS.Common.GameEvents.Events;
Expand All @@ -9,6 +9,7 @@
using WFDS.Common.Network.Packets;
using WFDS.Common.Types;
using WFDS.Godot.Binary;
using ZLogger;

namespace WFDS.Common.Steam;

Expand All @@ -25,7 +26,7 @@ public sealed class SessionManager : Singleton<SessionManager>, IDisposable

public SessionManager()
{
_logger = Log.ForContext<SessionManager>();
_logger = Log.Factory.CreateLogger<SessionManager>();
_lobbyChatUpdateCallback = Callback<LobbyChatUpdate_t>.Create(OnLobbyChatUpdate);
_p2pSessionRequestCallback = Callback<P2PSessionRequest_t>.Create(OnP2PSessionRequest);
}
Expand Down Expand Up @@ -66,7 +67,7 @@ public void ServerClose(CSteamID target)
return;
}

_logger.Information("try server close player: {SteamId}", target);
_logger.ZLogInformation($"try server close player: {target.m_SteamID.ToString(CultureInfo.InvariantCulture)}");
SendP2PPacket(target, NetChannel.GameState, new ServerClosePacket(), false);
}

Expand Down Expand Up @@ -95,35 +96,35 @@ private bool TryCreateSession(CSteamID steamId)
{
if (_sessions.TryGetValue(steamId.m_SteamID, out _))
{
_logger.Warning("session already exists: {Member}", steamId);
_logger.ZLogWarning($"session already exists: {steamId.m_SteamID.ToString(CultureInfo.InvariantCulture)}");
return false;
}

if (_banned.Contains(steamId.m_SteamID.ToString(CultureInfo.InvariantCulture)))
{
_logger.Warning("banned player: {Member}", steamId);
_logger.ZLogWarning($"banned player: {steamId.m_SteamID.ToString(CultureInfo.InvariantCulture)}");
return false;
}

_logger.Information("try create session: {Member}", steamId);
_logger.ZLogInformation($"try create session: {steamId.m_SteamID.ToString(CultureInfo.InvariantCulture)}");
var session = new Session(steamId);
if (_sessions.TryAdd(steamId.m_SteamID, session))
{
return true;
}

_logger.Warning("failed to create session: {Member}", steamId);
_logger.ZLogWarning($"failed to create session: {steamId.m_SteamID.ToString(CultureInfo.InvariantCulture)}");
return false;
}

private void RemoveSession(CSteamID steamId)
{
_logger.Warning("try remove session: {Member}", steamId);
_logger.ZLogWarning($"try remove session: {steamId.m_SteamID.ToString(CultureInfo.InvariantCulture)}");
SteamNetworking.CloseP2PSessionWithUser(steamId);

if (!_sessions.TryRemove(steamId.m_SteamID, out _))
{
_logger.Warning("failed to remove session: {Member}", steamId);
_logger.ZLogWarning($"failed to remove session: {steamId.m_SteamID.ToString(CultureInfo.InvariantCulture)}");
return;
}

Expand All @@ -138,7 +139,7 @@ public void KickPlayer(CSteamID target)
return;
}

_logger.Information("try kick player: {Member}", target);
_logger.ZLogInformation($"try kick player: {target.m_SteamID.ToString(CultureInfo.InvariantCulture)}");
SendP2PPacket(target, NetChannel.GameState, new KickPacket(), false);
}

Expand All @@ -150,7 +151,7 @@ public bool IsBannedPlayer(CSteamID target)

public void TempBanPlayer(CSteamID lobbyId, CSteamID target)
{
_logger.Information("try ban player: {Member}", target);
_logger.ZLogInformation($"try ban player: {target.m_SteamID.ToString(CultureInfo.InvariantCulture)}");
SendP2PPacket(target, NetChannel.GameState, new BanPacket(), false);
BroadcastP2PPacket(lobbyId, NetChannel.GameState, new ForceDisconnectPlayerPacket { UserId = target }, false);

Expand Down Expand Up @@ -262,7 +263,7 @@ private void OnLobbyChatUpdate(LobbyChatUpdate_t param)
var makingChange = new CSteamID(param.m_ulSteamIDMakingChange);

var stateChange = (EChatMemberStateChange)param.m_rgfChatMemberStateChange;
_logger.Debug("lobby member state changed: {LobbyId} {ChangedUser} {MakingChange} {StateChange}", lobbyId, changedUser, makingChange, stateChange);
_logger.ZLogDebug($"lobby member state changed: {lobbyId} {changedUser} {makingChange} {stateChange}");

if (stateChange == EChatMemberStateChange.k_EChatMemberStateChangeEntered)
{
Expand All @@ -283,18 +284,18 @@ private void OnLobbyChatUpdate(LobbyChatUpdate_t param)

private void OnP2PSessionRequest(P2PSessionRequest_t param)
{
_logger.Warning("p2p session request: {SteamId}", param.m_steamIDRemote);
_logger.ZLogWarning($"p2p session request: {param.m_steamIDRemote}");

if (_banned.Contains(param.m_steamIDRemote.m_SteamID.ToString(CultureInfo.InvariantCulture)))
{
_logger.Warning("banned player request: {SteamId}", param.m_steamIDRemote);
_logger.ZLogWarning($"banned player request: {param.m_steamIDRemote}");
SteamNetworking.CloseP2PSessionWithUser(param.m_steamIDRemote);
return;
}

if (IsServerClosed())
{
_logger.Warning("server closed: {SteamId}", param.m_steamIDRemote);
_logger.ZLogWarning($"server closed: {param.m_steamIDRemote}");
ServerClose(param.m_steamIDRemote);
return;
}
Expand Down
9 changes: 5 additions & 4 deletions WFDS.Common/Steam/SteamManager.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Serilog;
using Microsoft.Extensions.Logging;
using Steamworks;
using WFDS.Common.Types;
using ZLogger;

namespace WFDS.Common.Steam;

Expand All @@ -9,7 +10,7 @@ public class SteamManager : Singleton<SteamManager>
public bool Initialized { get; private set; }
public CSteamID SteamId => Initialized ? _steamId : CSteamID.Nil;

private readonly ILogger _logger = Log.ForContext<SteamManager>();
private readonly ILogger _logger = Log.Factory.CreateLogger<SteamManager>();
private CSteamID _steamId;

public bool Init()
Expand All @@ -19,13 +20,13 @@ public bool Init()
var result = SteamAPI.InitEx(out var errMsg);
if (result != ESteamAPIInitResult.k_ESteamAPIInitResult_OK)
{
_logger.Error("SteamAPI.Init failed: {Result} {Error}", result, errMsg);
_logger.ZLogError($"SteamAPI.Init failed: {result} {errMsg}");
return false;
}

Initialized = true;
_steamId = SteamUser.GetSteamID();
_logger.Information("SteamAPI.Init success");
_logger.ZLogInformation($"SteamAPI.Init success");
return true;
}

Expand Down
Loading

0 comments on commit 19f6736

Please sign in to comment.