Skip to content

Commit

Permalink
Improve log and errors (#2747)
Browse files Browse the repository at this point in the history
* Rename SerilogHelper to SerilogWebRequestHelper

* Move LoggedUser property to every log (instead of just WebRequestLogging)

* Add ProjectId to logs

* Improve naming on error page
  • Loading branch information
leotsarev authored Aug 14, 2024
1 parent 5a34c3b commit 3c8db64
Show file tree
Hide file tree
Showing 9 changed files with 34 additions and 33 deletions.
4 changes: 2 additions & 2 deletions src/JoinRpg.Portal/Controllers/ErrorPageController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ public IActionResult Error(int statusCode)
return View(
new ErrorViewModel
{
RequestId = Activity.Current?.Id ?? "",
AspNetTrace = HttpContext.TraceIdentifier,
ActivityId = Activity.Current?.Id,
RequestId = HttpContext.TraceIdentifier,
Path = feature?.RawTarget ?? "NO PATH",
}
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using Serilog.Context;

namespace JoinRpg.Portal.Infrastructure.DiscoverFilters;

/// <summary>
Expand All @@ -12,15 +14,12 @@ public class DiscoverProjectMiddleware
/// <inheritedoc />
public async Task InvokeAsync(HttpContext context)
{
var httpContextItems = context.Items;
HttpRequest request = context.Request;

if (context.Request.Path.TryExtractFromPath() is int projectIdFromPath)
{
httpContextItems[Constants.ProjectIdName] = projectIdFromPath;
}
else if (context.Request.Query.TryExtractFromQuery() is int projectIdFromQuery)
if ((request.Path.TryExtractFromPath() ?? request.Query.TryExtractFromQuery()) is int projectId)
{
httpContextItems[Constants.ProjectIdName] = projectIdFromQuery;
context.Items[Constants.ProjectIdName] = projectId;
_ = LogContext.PushProperty(Constants.ProjectIdName, projectId);
}

await nextDelegate(context);
Expand Down
16 changes: 16 additions & 0 deletions src/JoinRpg.Portal/Infrastructure/Logging/LoggedUserEnricher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System.Security.Claims;
using Serilog.Core;
using Serilog.Events;

namespace JoinRpg.Portal.Infrastructure.Logging;

internal class LoggedUserEnricher(IHttpContextAccessor httpContextAccessor) : ILogEventEnricher
{
public LoggedUserEnricher() : this(new HttpContextAccessor()) { }
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(
"LoggedUser", httpContextAccessor.HttpContext?.User.FindFirst(ClaimTypes.Email)?.Value));
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public static void ConfigureLogger(this LoggerConfiguration loggerConfiguration,
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.Enrich.With<YcLevelEnricher>()
.Enrich.With<LoggedUserEnricher>()
.Enrich.WithProperty("AppName", "JoinRpg.Portal");

foreach (var (@namespace, logLevel) in serilogOptions.LogLevel)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
using System.Security.Claims;
using Serilog;
using Serilog.Events;

namespace JoinRpg.Portal.Infrastructure.Logging;

public static class SerilogHelper
public static class SerilogWebRequestHelper
{
public static void EnrichFromRequest(IDiagnosticContext diagnosticContext, HttpContext httpContext)
{
Expand All @@ -30,15 +29,6 @@ public static void EnrichFromRequest(IDiagnosticContext diagnosticContext, HttpC
{
diagnosticContext.Set("EndpointName", endpoint.DisplayName);
}

if (httpContext.User.Identity?.IsAuthenticated == true)
{
diagnosticContext.Set("LoggedUser", httpContext.User.FindFirst(ClaimTypes.Email)!.Value);
}
else
{
diagnosticContext.Set("LoggedUser", "null");
}
}
private static bool IsHealthCheckEndpoint(HttpContext ctx)
{
Expand Down
6 changes: 2 additions & 4 deletions src/JoinRpg.Portal/Models/ErrorViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@ namespace JoinRpg.Portal.Models;

public class ErrorViewModel
{
public required string RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public required string? ActivityId { get; set; }

public required string Path { get; set; }

public required string AspNetTrace { get; set; }
public required string RequestId { get; set; }
}
2 changes: 1 addition & 1 deletion src/JoinRpg.Portal/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public static IHostBuilder CreateHostBuilder(string[] args) =>
.UseSerilog((context, _, configuration) =>
{
var loggerOptions = context.Configuration.GetSection("Logging").Get<SerilogOptions>();
configuration.ConfigureLogger(loggerOptions);
configuration.ConfigureLogger(loggerOptions!);
})
.ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
}
4 changes: 2 additions & 2 deletions src/JoinRpg.Portal/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,8 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

_ = app.UseSerilogRequestLogging(opts =>
{
opts.EnrichDiagnosticContext = SerilogHelper.EnrichFromRequest;
opts.GetLevel = SerilogHelper.ExcludeHealthChecks;
opts.EnrichDiagnosticContext = SerilogWebRequestHelper.EnrichFromRequest;
opts.GetLevel = SerilogWebRequestHelper.ExcludeHealthChecks;
});

_ = app
Expand Down
9 changes: 3 additions & 6 deletions src/JoinRpg.Portal/Views/Shared/Error.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,12 @@
Обратитесь в техподдержку!
</p>

@if (Model.ShowRequestId)
@if (Model.ActivityId is not null)
{
<p> RequestId: @Model.RequestId </p>
<p> Activity: @Model.ActivityId </p>
}

@if (Model.AspNetTrace is not null)
{
<p>TraceIdentifier: @Model.AspNetTrace</p>
}
<p>RequestId: @Model.RequestId</p>

@if (!string.IsNullOrWhiteSpace(Model.Path))
{
Expand Down

0 comments on commit 3c8db64

Please sign in to comment.