Skip to content

Commit

Permalink
Reduce logging and make it single line for better searchability
Browse files Browse the repository at this point in the history
  • Loading branch information
JustAman62 committed Sep 2, 2024
1 parent 549155d commit 053c3d1
Show file tree
Hide file tree
Showing 8 changed files with 50 additions and 16 deletions.
26 changes: 13 additions & 13 deletions server/GridBattle.Api/Api/TimerBattleHub.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using GridBattle.Api;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Polly;
Expand All @@ -9,9 +10,6 @@ public sealed class TimerBattleHub(
ILogger<TimerBattleHub> logger
) : Hub
{
private const string USERNAME = "USERNAME";
private const string ROOM_ID = "ROOM_ID";

// Using a simple retry policy for DB operations so that we can safely use Optimistic locking
// In the future, we should investigate better locking methods.
private readonly ResiliencePipeline<TimerBattleRoom> _retryPipeline =
Expand Down Expand Up @@ -60,8 +58,10 @@ public async Task<TimerBattleRoom> CreateBattle(string name)
await db.SaveChangesAsync();

await Groups.AddToGroupAsync(Context.ConnectionId, newBattle.RoomId);
Context.Items[USERNAME] = name;
Context.Items[ROOM_ID] = newBattle.RoomId;

Context.SetUsername(name);
Context.SetRoomId(newBattle.RoomId);

logger.LogInformation(
"{Username} has created a new battle room {RoomId}",
name,
Expand Down Expand Up @@ -115,8 +115,8 @@ public async Task<TimerBattleRoom> JoinBattle(string roomId, string name)
);

await Groups.AddToGroupAsync(Context.ConnectionId, roomId);
Context.Items[USERNAME] = name;
Context.Items[ROOM_ID] = roomId;
Context.SetUsername(name);
Context.SetRoomId(roomId);

logger.LogInformation("{Username} has joined battle room {RoomId}", name, roomId);
return battle;
Expand All @@ -138,8 +138,8 @@ public async Task<bool> LeaveBattle()
}
);

Context.Items.Remove(USERNAME);
Context.Items.Remove(ROOM_ID);
Context.RemoveRoomId();
Context.RemoveUsername();
logger.LogInformation("{Username} has left the battle room {RoomId}", name, roomId);
return true;
}
Expand Down Expand Up @@ -287,7 +287,7 @@ public override async Task OnDisconnectedAsync(Exception? exception)
{
try
{
var username = Context.Items[USERNAME];
var username = Context.GetUsername();
if (username is not null)
{
logger.LogWarning("Player {Username} disconnected", username);
Expand Down Expand Up @@ -415,10 +415,10 @@ await db
}

private string GetRoomId() =>
Context.Items[ROOM_ID]?.ToString()
Context.GetRoomId()
?? throw new InvalidOperationException("Unexpected error, Room ID not in context");

private string GetUsername() =>
Context.Items[USERNAME]?.ToString()
?? throw new InvalidOperationException("Unexpected error, Room ID not in context");
Context.GetUsername()
?? throw new InvalidOperationException("Unexpected error, Username not in context");
}
7 changes: 5 additions & 2 deletions server/GridBattle.Api/DataCleanupService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,16 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
logger.LogInformation("Searching for stale Timer Battles to remove");
using var db = dbContextFactory.CreateDbContext();
var modifiedBefore = DateTimeOffset.UtcNow.AddHours(-1);
var staleBattleCount = await db
.TimerBattleRooms.Where(x => x.ModifiedDateTime < modifiedBefore)
.ExecuteDeleteAsync(stoppingToken);
logger.LogWarning("Deleted {Count} TimerBattleRooms", staleBattleCount);

if (staleBattleCount > 0)
{
logger.LogWarning("Deleted {Count} TimerBattleRooms", staleBattleCount);
}
}
catch (Exception e)
{
Expand Down
4 changes: 4 additions & 0 deletions server/GridBattle.Api/HubFilter.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using GridBattle.Data;
using Microsoft.AspNetCore.SignalR;

namespace GridBattle.Api;
Expand All @@ -13,6 +14,9 @@ private sealed record ResponseWrapper(object? Resource, ResponseWrapperError? Er
Func<HubInvocationContext, ValueTask<object?>> next
)
{
using var usernameScope = logger.BeginScope("Username:{Username}", invocationContext.Context.GetUsername());
using var roomIdScope = logger.BeginScope("RoomId:{RoomId}", invocationContext.Context.GetRoomId());

logger.LogInformation("Calling hub method '{MethodName}'", invocationContext.HubMethodName);
try
{
Expand Down
26 changes: 26 additions & 0 deletions server/GridBattle.Api/Infrastructure/HubCallerContextExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using Microsoft.AspNetCore.SignalR;

namespace GridBattle.Api;

public static class HubCallerContextExtensions
{
private const string USERNAME = "USERNAME";
private const string ROOM_ID = "ROOM_ID";

public static string? GetUsername(this HubCallerContext context) =>
context.Items[USERNAME]?.ToString();

public static string? GetRoomId(this HubCallerContext context) =>
context.Items[ROOM_ID]?.ToString();

public static void RemoveUsername(this HubCallerContext context) =>
context.Items.Remove(USERNAME);

public static void RemoveRoomId(this HubCallerContext context) => context.Items.Remove(ROOM_ID);

public static void SetUsername(this HubCallerContext context, string username) =>
context.Items[USERNAME] = username;

public static void SetRoomId(this HubCallerContext context, string roomId) =>
context.Items[ROOM_ID] = roomId;
}
File renamed without changes.
1 change: 1 addition & 0 deletions server/GridBattle.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
{
opt.IncludeScopes = true;
opt.UseUtcTimestamp = true;
opt.SingleLine = true;
opt.TimestampFormat = "yyyy-MM-dd'T'HH:mm:ss.fff'Z' ";
});

Expand Down
2 changes: 1 addition & 1 deletion server/GridBattle.Api/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore.Routing.EndpointMiddleware": "Warning"
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
Expand Down

0 comments on commit 053c3d1

Please sign in to comment.