Skip to content

Commit

Permalink
Merge pull request #4 from biplovkc/biplovkc-patch-1
Browse files Browse the repository at this point in the history
Update HttpContextEnricher.cs
  • Loading branch information
biplovkc authored Jun 2, 2023
2 parents f2776cb + 3da0972 commit 1e58c4e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
1 change: 1 addition & 0 deletions src/Biplov.Serilog.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
<PackageReference Include="Serilog.Expressions" Version="3.4.1" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />
<PackageReference Include="UAParser" Version="3.1.47" />
</ItemGroup>

</Project>
25 changes: 21 additions & 4 deletions src/HttpContextEnricher.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Routing;
using System.Security.Principal;

using UAParser;

namespace Biplov.Serilog;

public static class HttpContextEnricher
Expand All @@ -20,9 +22,24 @@ public static void HttpRequestEnricher(IDiagnosticContext diagnosticContext, Htt
};
var userAgent = httpContext.Request.Headers?.FirstOrDefault(s => "user-agent".Equals(s.Key, StringComparison.OrdinalIgnoreCase)).Value;
httpContextInfo.UserAgent = userAgent is not null ? userAgent.ToString() : "";

diagnosticContext.Set("HttpContext", httpContextInfo, true);
// get a parser with the embedded regex patterns
var uaParser = Parser.GetDefault();

// get a parser using externally supplied yaml definitions
// var uaParser = Parser.FromYaml(yamlString);

var clientInfo = uaParser.Parse(userAgent);

diagnosticContext.Set("Route", httpContextInfo.Route);
diagnosticContext.Set("User", httpContextInfo.User);
diagnosticContext.Set("Host", httpContextInfo.Host);
diagnosticContext.Set("IpAddress", httpContextInfo.IpAddress);
diagnosticContext.Set("Protocol", httpContextInfo.Protocol);
diagnosticContext.Set("Scheme", httpContextInfo.Scheme);
diagnosticContext.Set("Device", clientInfo.Device.Family);
diagnosticContext.Set("OperatingSystem", clientInfo.OS.Family);
diagnosticContext.Set("Browser", clientInfo.UA.Family);
}

private static string GetUserInfo(IPrincipal user) => user.Identity is { IsAuthenticated: true } ? user.Identity.Name : Environment.UserName;
}
}

0 comments on commit 1e58c4e

Please sign in to comment.