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 <cstddef>
#include <cstdio>
#include <format>
#include <limits>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <thread>
#include <unordered_map>
@@ -44,6 +46,23 @@ namespace
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()
{
const std::scoped_lock lock(g_socketMutex);
@@ -68,9 +87,7 @@ namespace
WSADATA winsockData{};
const auto startupResult = WSAStartup(MAKEWORD(2, 2), std::addressof(winsockData));
if (startupResult != 0) {
REX::WARN(
"{} Could not initialize Winsock for Fallout 4 Together local networking.",
F4T::Networking::GetLocalPlayerLogPrefix());
LogWarningWithLocalPlayerPrefix("Could not initialize Winsock for Fallout 4 Together local networking.");
return false;
}
@@ -139,7 +156,7 @@ namespace
void LogThrottledWarning(const std::string& a_key, const char* a_message)
{
if (ShouldLogWarning(a_key)) {
REX::WARN("{} {}", F4T::Networking::GetLocalPlayerLogPrefix(), a_message);
LogWarningWithLocalPlayerPrefix(a_message);
}
}
@@ -240,7 +257,7 @@ namespace
}
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)
@@ -282,16 +299,15 @@ namespace
// 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.
if (ShouldLogRemoteUpdate(*playerId)) {
REX::INFO(
"{} Remote player {} updated: X={:.2f}, Y={:.2f}, Z={:.2f}, AngleZ={:.2f}, Cell={}, Worldspace={}",
F4T::Networking::GetLocalPlayerLogPrefix(),
LogInfoWithLocalPlayerPrefix(std::format(
"Remote player {} updated: X={:.2f}, Y={:.2f}, Z={:.2f}, AngleZ={:.2f}, Cell={}, Worldspace={}",
remoteState.playerId,
remoteState.x,
remoteState.y,
remoteState.z,
remoteState.angleZ,
remoteState.cellId,
remoteState.worldspaceId);
remoteState.worldspaceId));
}
}
@@ -306,15 +322,9 @@ namespace
g_lastRemoteUpdateLogTimes.erase(*playerId);
if (F4T::RemotePlayerState::RemoveRemotePlayer(*playerId)) {
REX::INFO(
"{} Remote player {} disconnected and was removed.",
F4T::Networking::GetLocalPlayerLogPrefix(),
*playerId);
LogInfoWithLocalPlayerPrefix(std::format("Remote player {} disconnected and was removed.", *playerId));
} else {
REX::INFO(
"{} Received disconnect for unknown remote player {}.",
F4T::Networking::GetLocalPlayerLogPrefix(),
*playerId);
LogInfoWithLocalPlayerPrefix(std::format("Received disconnect for unknown remote player {}.", *playerId));
}
}
@@ -322,7 +332,7 @@ namespace
{
const auto type = ReadString(a_packet, "type").value_or("<missing>");
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);
} catch (const std::exception& a_error) {
if (ShouldLogWarning("json_parse")) {
REX::WARN(
"{} Ignoring invalid JSON packet from server: {}",
F4T::Networking::GetLocalPlayerLogPrefix(),
a_error.what());
LogWarningWithLocalPlayerPrefix(std::format("Ignoring invalid JSON packet from server: {}", a_error.what()));
}
return;
}
@@ -406,9 +413,7 @@ namespace
}
if (bytesReceived == 0) {
REX::WARN(
"{} Fallout 4 Together local server closed the connection.",
F4T::Networking::GetLocalPlayerLogPrefix());
LogWarningWithLocalPlayerPrefix("Fallout 4 Together local server closed the connection.");
CloseSocket();
break;
}
@@ -420,9 +425,7 @@ namespace
}
if (g_receiveThreadRunning.load()) {
REX::WARN(
"{} Lost connection to Fallout 4 Together local server while receiving.",
F4T::Networking::GetLocalPlayerLogPrefix());
LogWarningWithLocalPlayerPrefix("Lost connection to Fallout 4 Together local server while receiving.");
}
CloseSocket();
break;
@@ -484,15 +487,14 @@ namespace F4T::Networking
// packet path without exposing any gameplay state to a remote server.
const auto localSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
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;
}
if (!SetNonBlocking(localSocket)) {
closesocket(localSocket);
REX::WARN(
"{} Could not configure non-blocking socket for Fallout 4 Together local server connection.",
GetLocalPlayerLogPrefix());
LogWarningWithLocalPlayerPrefix(
"Could not configure non-blocking socket for Fallout 4 Together local server connection.");
return false;
}
@@ -501,7 +503,7 @@ namespace F4T::Networking
serverAddress.sin_port = htons(kLocalServerPort);
if (inet_pton(AF_INET, kLocalServerHost, std::addressof(serverAddress.sin_addr)) != 1) {
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;
}
@@ -514,11 +516,10 @@ namespace F4T::Networking
closesocket(localSocket);
// The server is a developer tool, not a runtime requirement. A failed
// connection should leave Fallout 4 running and simply disable packet sends.
REX::WARN(
"{} Could not connect to Fallout 4 Together local server at {}:{}",
GetLocalPlayerLogPrefix(),
LogWarningWithLocalPlayerPrefix(std::format(
"Could not connect to Fallout 4 Together local server at {}:{}",
kLocalServerHost,
kLocalServerPort);
kLocalServerPort));
return false;
}
@@ -532,11 +533,8 @@ namespace F4T::Networking
g_lastRemoteUpdateLogTimes.clear();
StartReceiveThread();
REX::INFO(
"{} Connected to Fallout 4 Together local server at {}:{}.",
GetLocalPlayerLogPrefix(),
kLocalServerHost,
kLocalServerPort);
LogInfoWithLocalPlayerPrefix(
std::format("Connected to Fallout 4 Together local server at {}:{}.", kLocalServerHost, kLocalServerPort));
return true;
}
@@ -589,7 +587,7 @@ namespace F4T::Networking
clientTime);
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;
}
@@ -602,7 +600,7 @@ namespace F4T::Networking
a_cellId);
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;
}
@@ -618,9 +616,7 @@ namespace F4T::Networking
a_worldspaceId);
if (appended <= 0 || static_cast<std::size_t>(appended) >= remaining) {
REX::WARN(
"{} Could not format Fallout 4 Together transform packet worldspace ID.",
GetLocalPlayerLogPrefix());
LogWarningWithLocalPlayerPrefix("Could not format Fallout 4 Together transform packet worldspace ID.");
return false;
}
@@ -630,7 +626,7 @@ namespace F4T::Networking
const auto remaining = packet.size() - static_cast<std::size_t>(packetSize);
const auto appended = std::snprintf(packet.data() + packetSize, remaining, "}\n");
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;
}
@@ -649,7 +645,7 @@ namespace F4T::Networking
if (bytesSent == SOCKET_ERROR) {
const auto error = WSAGetLastError();
if (error != WSAEWOULDBLOCK) {
REX::WARN("{} Lost connection to Fallout 4 Together local server.", GetLocalPlayerLogPrefix());
LogWarningWithLocalPlayerPrefix("Lost connection to Fallout 4 Together local server.");
CloseSocket();
}
@@ -657,7 +653,7 @@ namespace F4T::Networking
}
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();
return false;
}
+27 -22
View File
@@ -2,6 +2,7 @@
#include <cstdlib>
#include <cstdint>
#include <format>
#include <string_view>
namespace
@@ -28,6 +29,23 @@ namespace
constexpr auto kMinimumLogInterval = 1s;
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()
{
return RE::PlayerCharacter::GetSingleton();
@@ -120,12 +138,11 @@ namespace
void LogPlayerTransform(const PlayerTransform& a_transform)
{
REX::INFO("{} Sent transform: X={:.2f}, Y={:.2f}, Z={:.2f}, AngleZ={:.2f}",
F4T::Networking::GetLocalPlayerLogPrefix(),
LogInfoWithLocalPlayerPrefix(std::format("Player position: X={:.2f}, Y={:.2f}, Z={:.2f}, AngleZ={:.2f}",
a_transform.x,
a_transform.y,
a_transform.z,
a_transform.angleZ);
a_transform.angleZ));
}
void CheckAndLogPlayerPositionChange()
@@ -134,9 +151,7 @@ namespace
if (!player) {
static bool playerUnavailableWarningLogged = false;
if (!playerUnavailableWarningLogged) {
REX::WARN(
"{} Player position unavailable: local player reference is not available yet.",
F4T::Networking::GetLocalPlayerLogPrefix());
LogWarningWithLocalPlayerPrefix("Player position unavailable: local player reference is not available yet.");
playerUnavailableWarningLogged = true;
}
return;
@@ -158,19 +173,13 @@ namespace
const char* movementType = "normal";
if (HasWorldspaceChanged(lastKnownLocation, currentLocation)) {
REX::INFO(
"{} Detected worldspace change. Sending immediate transform update.",
F4T::Networking::GetLocalPlayerLogPrefix());
LogInfoWithLocalPlayerPrefix("Detected worldspace change. Sending immediate transform update.");
movementType = "worldspace_change";
} else if (HasCellChanged(lastKnownLocation, currentLocation)) {
REX::INFO(
"{} Detected cell change. Sending immediate transform update.",
F4T::Networking::GetLocalPlayerLogPrefix());
LogInfoWithLocalPlayerPrefix("Detected cell change. Sending immediate transform update.");
movementType = "cell_change";
} else if (HasTeleportDistance(lastSentTransform, currentTransform)) {
REX::INFO(
"{} Detected teleport/large position jump. Sending immediate transform update.",
F4T::Networking::GetLocalPlayerLogPrefix());
LogInfoWithLocalPlayerPrefix("Detected teleport/large position jump. Sending immediate transform update.");
movementType = "teleport";
}
@@ -214,9 +223,7 @@ namespace
const auto* taskInterface = F4SE::GetTaskInterface();
if (!taskInterface) {
REX::WARN(
"{} Failed to get F4SE task interface; player position changes will not be logged.",
F4T::Networking::GetLocalPlayerLogPrefix());
LogWarningWithLocalPlayerPrefix("Failed to get F4SE task interface; player position changes will not be logged.");
return;
}
@@ -253,7 +260,7 @@ F4SE_PLUGIN_LOAD(const F4SE::LoadInterface* 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.
// 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();
if (!messaging || !messaging->RegisterListener(OnF4SEMessage)) {
REX::WARN(
"{} Failed to register F4SE message listener; player position will not be logged.",
F4T::Networking::GetLocalPlayerLogPrefix());
LogWarningWithLocalPlayerPrefix("Failed to register F4SE message listener; player position will not be logged.");
}
return true;