Enriches Serilog events with information from the ClaimsPrincipal.
Install the Serilog.Enrichers.AzureClaims NuGet package
Install-Package Serilog.Enrichers.AzureClaims
Then, apply the enricher to your LoggerConfiguration
:
Log.Logger = new LoggerConfiguration()
.Enrich.WithUpn()
.Enrich.WithDisplayName()
.Enrich.WithTenantId()
.Enrich.WithObjectId()
.Enrich.WithAppId()
// ...other configuration...
.CreateLogger();
The package includes:
WithUpn()
- addsUserPrincipalName
based on the ClaimTypehttp://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn
WithDisplayName()
- addsDisplayName
based on the ClaimTypehttp://schemas.xmlsoap.org/ws/2005/05/identity/claims/name
orname
orpreferred_username
WithTenantId()
- addsTenantId
based on the ClaimTypehttp://schemas.microsoft.com/identity/claims/tenantid
ortid
WithObjectId()
- addsObjectId
based on the ClaimTypehttp://schemas.microsoft.com/identity/claims/objectidentifier
oroid
WithAppId
- addsAppId
based on the CLaimTypeappid
orazp
You need to register the IHttpContextAccessor
singleton so the enrichers have access to the requests HttpContext
to extract the data.
This is what your Program
class should contain in order for this enricher to work as expected:
// ...
using Serilog;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddSerilog(new LoggerConfiguration()
.Enrich.WithUpn()
.Enrich.WithDisplayName()
.Enrich.WithTenantId()
.Enrich.WithObjectId()
.Enrich.WithAppId()
.CreateLogger());
// ...
builder.Services.AddHttpContextAccessor();
// ...
var app = builder.Build();
app.UseSerilogRequestLogging();
// ...