Centralize local-player prefixed logging

Introduce GetLocalPlayerLogMessage, LogInfoWithLocalPlayerPrefix and LogWarningWithLocalPlayerPrefix to avoid repeating the local-player log prefix. Replace many REX::INFO/REX::WARN usages with these helpers and switch to std::format for message construction. Added <format> and <string_view> includes in both F4TNetworking.cpp and main.cpp. This is a refactor-only change to DRY logging and keep log prefix handling consistent.
This commit is contained in:
2026-05-31 21:05:23 +12:00
parent c35659bc30
commit 13420ee2c2
2 changed files with 73 additions and 72 deletions
+46 -50
View File
@@ -12,11 +12,13 @@
#include <chrono> #include <chrono>
#include <cstddef> #include <cstddef>
#include <cstdio> #include <cstdio>
#include <format>
#include <limits> #include <limits>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <optional> #include <optional>
#include <string> #include <string>
#include <string_view>
#include <thread> #include <thread>
#include <unordered_map> #include <unordered_map>
@@ -44,6 +46,23 @@ namespace
using Json = nlohmann::json; using Json = nlohmann::json;
std::string GetLocalPlayerLogMessage(std::string_view a_message)
{
return F4T::Networking::GetLocalPlayerLogPrefix() + " " + std::string(a_message);
}
void LogInfoWithLocalPlayerPrefix(std::string_view a_message)
{
const auto message = GetLocalPlayerLogMessage(a_message);
REX::INFO(std::string_view{ message });
}
void LogWarningWithLocalPlayerPrefix(std::string_view a_message)
{
const auto message = GetLocalPlayerLogMessage(a_message);
REX::WARN(std::string_view{ message });
}
void CloseSocket() void CloseSocket()
{ {
const std::scoped_lock lock(g_socketMutex); const std::scoped_lock lock(g_socketMutex);
@@ -68,9 +87,7 @@ namespace
WSADATA winsockData{}; WSADATA winsockData{};
const auto startupResult = WSAStartup(MAKEWORD(2, 2), std::addressof(winsockData)); const auto startupResult = WSAStartup(MAKEWORD(2, 2), std::addressof(winsockData));
if (startupResult != 0) { if (startupResult != 0) {
REX::WARN( LogWarningWithLocalPlayerPrefix("Could not initialize Winsock for Fallout 4 Together local networking.");
"{} Could not initialize Winsock for Fallout 4 Together local networking.",
F4T::Networking::GetLocalPlayerLogPrefix());
return false; return false;
} }
@@ -139,7 +156,7 @@ namespace
void LogThrottledWarning(const std::string& a_key, const char* a_message) void LogThrottledWarning(const std::string& a_key, const char* a_message)
{ {
if (ShouldLogWarning(a_key)) { if (ShouldLogWarning(a_key)) {
REX::WARN("{} {}", F4T::Networking::GetLocalPlayerLogPrefix(), a_message); LogWarningWithLocalPlayerPrefix(a_message);
} }
} }
@@ -240,7 +257,7 @@ namespace
} }
F4T::RemotePlayerState::SetAssignedPlayerId(*playerId); F4T::RemotePlayerState::SetAssignedPlayerId(*playerId);
REX::INFO("{} Assigned server playerId: {}", F4T::Networking::GetLocalPlayerLogPrefix(), *playerId); LogInfoWithLocalPlayerPrefix(std::format("Assigned server playerId: {}", *playerId));
} }
void HandleTransformPacket(const Json& a_packet) void HandleTransformPacket(const Json& a_packet)
@@ -282,16 +299,15 @@ namespace
// TODO: A later milestone can read this plain state from the game thread and // TODO: A later milestone can read this plain state from the game thread and
// spawn or move remote actors. The networking thread must not touch actors. // spawn or move remote actors. The networking thread must not touch actors.
if (ShouldLogRemoteUpdate(*playerId)) { if (ShouldLogRemoteUpdate(*playerId)) {
REX::INFO( LogInfoWithLocalPlayerPrefix(std::format(
"{} Remote player {} updated: X={:.2f}, Y={:.2f}, Z={:.2f}, AngleZ={:.2f}, Cell={}, Worldspace={}", "Remote player {} updated: X={:.2f}, Y={:.2f}, Z={:.2f}, AngleZ={:.2f}, Cell={}, Worldspace={}",
F4T::Networking::GetLocalPlayerLogPrefix(),
remoteState.playerId, remoteState.playerId,
remoteState.x, remoteState.x,
remoteState.y, remoteState.y,
remoteState.z, remoteState.z,
remoteState.angleZ, remoteState.angleZ,
remoteState.cellId, remoteState.cellId,
remoteState.worldspaceId); remoteState.worldspaceId));
} }
} }
@@ -306,15 +322,9 @@ namespace
g_lastRemoteUpdateLogTimes.erase(*playerId); g_lastRemoteUpdateLogTimes.erase(*playerId);
if (F4T::RemotePlayerState::RemoveRemotePlayer(*playerId)) { if (F4T::RemotePlayerState::RemoveRemotePlayer(*playerId)) {
REX::INFO( LogInfoWithLocalPlayerPrefix(std::format("Remote player {} disconnected and was removed.", *playerId));
"{} Remote player {} disconnected and was removed.",
F4T::Networking::GetLocalPlayerLogPrefix(),
*playerId);
} else { } else {
REX::INFO( LogInfoWithLocalPlayerPrefix(std::format("Received disconnect for unknown remote player {}.", *playerId));
"{} Received disconnect for unknown remote player {}.",
F4T::Networking::GetLocalPlayerLogPrefix(),
*playerId);
} }
} }
@@ -322,7 +332,7 @@ namespace
{ {
const auto type = ReadString(a_packet, "type").value_or("<missing>"); const auto type = ReadString(a_packet, "type").value_or("<missing>");
if (ShouldLogWarning("unknown_" + type)) { if (ShouldLogWarning("unknown_" + type)) {
REX::WARN("{} Ignoring unknown server packet type: {}", F4T::Networking::GetLocalPlayerLogPrefix(), type); LogWarningWithLocalPlayerPrefix(std::format("Ignoring unknown server packet type: {}", type));
} }
} }
@@ -337,10 +347,7 @@ namespace
packet = Json::parse(a_line); packet = Json::parse(a_line);
} catch (const std::exception& a_error) { } catch (const std::exception& a_error) {
if (ShouldLogWarning("json_parse")) { if (ShouldLogWarning("json_parse")) {
REX::WARN( LogWarningWithLocalPlayerPrefix(std::format("Ignoring invalid JSON packet from server: {}", a_error.what()));
"{} Ignoring invalid JSON packet from server: {}",
F4T::Networking::GetLocalPlayerLogPrefix(),
a_error.what());
} }
return; return;
} }
@@ -406,9 +413,7 @@ namespace
} }
if (bytesReceived == 0) { if (bytesReceived == 0) {
REX::WARN( LogWarningWithLocalPlayerPrefix("Fallout 4 Together local server closed the connection.");
"{} Fallout 4 Together local server closed the connection.",
F4T::Networking::GetLocalPlayerLogPrefix());
CloseSocket(); CloseSocket();
break; break;
} }
@@ -420,9 +425,7 @@ namespace
} }
if (g_receiveThreadRunning.load()) { if (g_receiveThreadRunning.load()) {
REX::WARN( LogWarningWithLocalPlayerPrefix("Lost connection to Fallout 4 Together local server while receiving.");
"{} Lost connection to Fallout 4 Together local server while receiving.",
F4T::Networking::GetLocalPlayerLogPrefix());
} }
CloseSocket(); CloseSocket();
break; break;
@@ -484,15 +487,14 @@ namespace F4T::Networking
// packet path without exposing any gameplay state to a remote server. // packet path without exposing any gameplay state to a remote server.
const auto localSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); const auto localSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (localSocket == INVALID_SOCKET) { if (localSocket == INVALID_SOCKET) {
REX::WARN("{} Could not create socket for Fallout 4 Together local server connection.", GetLocalPlayerLogPrefix()); LogWarningWithLocalPlayerPrefix("Could not create socket for Fallout 4 Together local server connection.");
return false; return false;
} }
if (!SetNonBlocking(localSocket)) { if (!SetNonBlocking(localSocket)) {
closesocket(localSocket); closesocket(localSocket);
REX::WARN( LogWarningWithLocalPlayerPrefix(
"{} Could not configure non-blocking socket for Fallout 4 Together local server connection.", "Could not configure non-blocking socket for Fallout 4 Together local server connection.");
GetLocalPlayerLogPrefix());
return false; return false;
} }
@@ -501,7 +503,7 @@ namespace F4T::Networking
serverAddress.sin_port = htons(kLocalServerPort); serverAddress.sin_port = htons(kLocalServerPort);
if (inet_pton(AF_INET, kLocalServerHost, std::addressof(serverAddress.sin_addr)) != 1) { if (inet_pton(AF_INET, kLocalServerHost, std::addressof(serverAddress.sin_addr)) != 1) {
closesocket(localSocket); closesocket(localSocket);
REX::WARN("{} Could not parse Fallout 4 Together local server address.", GetLocalPlayerLogPrefix()); LogWarningWithLocalPlayerPrefix("Could not parse Fallout 4 Together local server address.");
return false; return false;
} }
@@ -514,11 +516,10 @@ namespace F4T::Networking
closesocket(localSocket); closesocket(localSocket);
// The server is a developer tool, not a runtime requirement. A failed // The server is a developer tool, not a runtime requirement. A failed
// connection should leave Fallout 4 running and simply disable packet sends. // connection should leave Fallout 4 running and simply disable packet sends.
REX::WARN( LogWarningWithLocalPlayerPrefix(std::format(
"{} Could not connect to Fallout 4 Together local server at {}:{}", "Could not connect to Fallout 4 Together local server at {}:{}",
GetLocalPlayerLogPrefix(),
kLocalServerHost, kLocalServerHost,
kLocalServerPort); kLocalServerPort));
return false; return false;
} }
@@ -532,11 +533,8 @@ namespace F4T::Networking
g_lastRemoteUpdateLogTimes.clear(); g_lastRemoteUpdateLogTimes.clear();
StartReceiveThread(); StartReceiveThread();
REX::INFO( LogInfoWithLocalPlayerPrefix(
"{} Connected to Fallout 4 Together local server at {}:{}.", std::format("Connected to Fallout 4 Together local server at {}:{}.", kLocalServerHost, kLocalServerPort));
GetLocalPlayerLogPrefix(),
kLocalServerHost,
kLocalServerPort);
return true; return true;
} }
@@ -589,7 +587,7 @@ namespace F4T::Networking
clientTime); clientTime);
if (packetSize <= 0 || static_cast<std::size_t>(packetSize) >= packet.size()) { if (packetSize <= 0 || static_cast<std::size_t>(packetSize) >= packet.size()) {
REX::WARN("{} Could not format Fallout 4 Together transform packet.", GetLocalPlayerLogPrefix()); LogWarningWithLocalPlayerPrefix("Could not format Fallout 4 Together transform packet.");
return false; return false;
} }
@@ -602,7 +600,7 @@ namespace F4T::Networking
a_cellId); a_cellId);
if (appended <= 0 || static_cast<std::size_t>(appended) >= remaining) { if (appended <= 0 || static_cast<std::size_t>(appended) >= remaining) {
REX::WARN("{} Could not format Fallout 4 Together transform packet cell ID.", GetLocalPlayerLogPrefix()); LogWarningWithLocalPlayerPrefix("Could not format Fallout 4 Together transform packet cell ID.");
return false; return false;
} }
@@ -618,9 +616,7 @@ namespace F4T::Networking
a_worldspaceId); a_worldspaceId);
if (appended <= 0 || static_cast<std::size_t>(appended) >= remaining) { if (appended <= 0 || static_cast<std::size_t>(appended) >= remaining) {
REX::WARN( LogWarningWithLocalPlayerPrefix("Could not format Fallout 4 Together transform packet worldspace ID.");
"{} Could not format Fallout 4 Together transform packet worldspace ID.",
GetLocalPlayerLogPrefix());
return false; return false;
} }
@@ -630,7 +626,7 @@ namespace F4T::Networking
const auto remaining = packet.size() - static_cast<std::size_t>(packetSize); const auto remaining = packet.size() - static_cast<std::size_t>(packetSize);
const auto appended = std::snprintf(packet.data() + packetSize, remaining, "}\n"); const auto appended = std::snprintf(packet.data() + packetSize, remaining, "}\n");
if (appended <= 0 || static_cast<std::size_t>(appended) >= remaining) { if (appended <= 0 || static_cast<std::size_t>(appended) >= remaining) {
REX::WARN("{} Could not finish Fallout 4 Together transform packet.", GetLocalPlayerLogPrefix()); LogWarningWithLocalPlayerPrefix("Could not finish Fallout 4 Together transform packet.");
return false; return false;
} }
@@ -649,7 +645,7 @@ namespace F4T::Networking
if (bytesSent == SOCKET_ERROR) { if (bytesSent == SOCKET_ERROR) {
const auto error = WSAGetLastError(); const auto error = WSAGetLastError();
if (error != WSAEWOULDBLOCK) { if (error != WSAEWOULDBLOCK) {
REX::WARN("{} Lost connection to Fallout 4 Together local server.", GetLocalPlayerLogPrefix()); LogWarningWithLocalPlayerPrefix("Lost connection to Fallout 4 Together local server.");
CloseSocket(); CloseSocket();
} }
@@ -657,7 +653,7 @@ namespace F4T::Networking
} }
if (bytesSent != packetSize) { if (bytesSent != packetSize) {
REX::WARN("{} Could not send full Fallout 4 Together transform packet.", GetLocalPlayerLogPrefix()); LogWarningWithLocalPlayerPrefix("Could not send full Fallout 4 Together transform packet.");
CloseSocket(); CloseSocket();
return false; return false;
} }
+27 -22
View File
@@ -2,6 +2,7 @@
#include <cstdlib> #include <cstdlib>
#include <cstdint> #include <cstdint>
#include <format>
#include <string_view> #include <string_view>
namespace namespace
@@ -28,6 +29,23 @@ namespace
constexpr auto kMinimumLogInterval = 1s; constexpr auto kMinimumLogInterval = 1s;
constexpr auto kTeleportDistanceThreshold = 5000.0F; constexpr auto kTeleportDistanceThreshold = 5000.0F;
std::string GetLocalPlayerLogMessage(std::string_view a_message)
{
return F4T::Networking::GetLocalPlayerLogPrefix() + " " + std::string(a_message);
}
void LogInfoWithLocalPlayerPrefix(std::string_view a_message)
{
const auto message = GetLocalPlayerLogMessage(a_message);
REX::INFO(std::string_view{ message });
}
void LogWarningWithLocalPlayerPrefix(std::string_view a_message)
{
const auto message = GetLocalPlayerLogMessage(a_message);
REX::WARN(std::string_view{ message });
}
RE::PlayerCharacter* TryGetLocalPlayer() RE::PlayerCharacter* TryGetLocalPlayer()
{ {
return RE::PlayerCharacter::GetSingleton(); return RE::PlayerCharacter::GetSingleton();
@@ -120,12 +138,11 @@ namespace
void LogPlayerTransform(const PlayerTransform& a_transform) void LogPlayerTransform(const PlayerTransform& a_transform)
{ {
REX::INFO("{} Sent transform: X={:.2f}, Y={:.2f}, Z={:.2f}, AngleZ={:.2f}", LogInfoWithLocalPlayerPrefix(std::format("Player position: X={:.2f}, Y={:.2f}, Z={:.2f}, AngleZ={:.2f}",
F4T::Networking::GetLocalPlayerLogPrefix(),
a_transform.x, a_transform.x,
a_transform.y, a_transform.y,
a_transform.z, a_transform.z,
a_transform.angleZ); a_transform.angleZ));
} }
void CheckAndLogPlayerPositionChange() void CheckAndLogPlayerPositionChange()
@@ -134,9 +151,7 @@ namespace
if (!player) { if (!player) {
static bool playerUnavailableWarningLogged = false; static bool playerUnavailableWarningLogged = false;
if (!playerUnavailableWarningLogged) { if (!playerUnavailableWarningLogged) {
REX::WARN( LogWarningWithLocalPlayerPrefix("Player position unavailable: local player reference is not available yet.");
"{} Player position unavailable: local player reference is not available yet.",
F4T::Networking::GetLocalPlayerLogPrefix());
playerUnavailableWarningLogged = true; playerUnavailableWarningLogged = true;
} }
return; return;
@@ -158,19 +173,13 @@ namespace
const char* movementType = "normal"; const char* movementType = "normal";
if (HasWorldspaceChanged(lastKnownLocation, currentLocation)) { if (HasWorldspaceChanged(lastKnownLocation, currentLocation)) {
REX::INFO( LogInfoWithLocalPlayerPrefix("Detected worldspace change. Sending immediate transform update.");
"{} Detected worldspace change. Sending immediate transform update.",
F4T::Networking::GetLocalPlayerLogPrefix());
movementType = "worldspace_change"; movementType = "worldspace_change";
} else if (HasCellChanged(lastKnownLocation, currentLocation)) { } else if (HasCellChanged(lastKnownLocation, currentLocation)) {
REX::INFO( LogInfoWithLocalPlayerPrefix("Detected cell change. Sending immediate transform update.");
"{} Detected cell change. Sending immediate transform update.",
F4T::Networking::GetLocalPlayerLogPrefix());
movementType = "cell_change"; movementType = "cell_change";
} else if (HasTeleportDistance(lastSentTransform, currentTransform)) { } else if (HasTeleportDistance(lastSentTransform, currentTransform)) {
REX::INFO( LogInfoWithLocalPlayerPrefix("Detected teleport/large position jump. Sending immediate transform update.");
"{} Detected teleport/large position jump. Sending immediate transform update.",
F4T::Networking::GetLocalPlayerLogPrefix());
movementType = "teleport"; movementType = "teleport";
} }
@@ -214,9 +223,7 @@ namespace
const auto* taskInterface = F4SE::GetTaskInterface(); const auto* taskInterface = F4SE::GetTaskInterface();
if (!taskInterface) { if (!taskInterface) {
REX::WARN( LogWarningWithLocalPlayerPrefix("Failed to get F4SE task interface; player position changes will not be logged.");
"{} Failed to get F4SE task interface; player position changes will not be logged.",
F4T::Networking::GetLocalPlayerLogPrefix());
return; return;
} }
@@ -253,7 +260,7 @@ F4SE_PLUGIN_LOAD(const F4SE::LoadInterface* a_f4se)
{ {
F4SE::Init(a_f4se); F4SE::Init(a_f4se);
REX::INFO("{} Fallout 4 Together plugin loaded successfully.", F4T::Networking::GetLocalPlayerLogPrefix()); LogInfoWithLocalPlayerPrefix("Fallout 4 Together plugin loaded successfully.");
// TODO: Consider separate per-instance log files once launcher/profile support exists. // TODO: Consider separate per-instance log files once launcher/profile support exists.
// Networking is intentionally localhost-only for the first milestone. If the // Networking is intentionally localhost-only for the first milestone. If the
@@ -264,9 +271,7 @@ F4SE_PLUGIN_LOAD(const F4SE::LoadInterface* a_f4se)
const auto* messaging = F4SE::GetMessagingInterface(); const auto* messaging = F4SE::GetMessagingInterface();
if (!messaging || !messaging->RegisterListener(OnF4SEMessage)) { if (!messaging || !messaging->RegisterListener(OnF4SEMessage)) {
REX::WARN( LogWarningWithLocalPlayerPrefix("Failed to register F4SE message listener; player position will not be logged.");
"{} Failed to register F4SE message listener; player position will not be logged.",
F4T::Networking::GetLocalPlayerLogPrefix());
} }
return true; return true;