![]() |
VOOZH | about |
dotnet add package Serilog.Enrichers.ClientInfo --version 2.9.0
NuGet\Install-Package Serilog.Enrichers.ClientInfo -Version 2.9.0
<PackageReference Include="Serilog.Enrichers.ClientInfo" Version="2.9.0" />
<PackageVersion Include="Serilog.Enrichers.ClientInfo" Version="2.9.0" />Directory.Packages.props
<PackageReference Include="Serilog.Enrichers.ClientInfo" />Project file
paket add Serilog.Enrichers.ClientInfo --version 2.9.0
#r "nuget: Serilog.Enrichers.ClientInfo, 2.9.0"
#:package Serilog.Enrichers.ClientInfo@2.9.0
#addin nuget:?package=Serilog.Enrichers.ClientInfo&version=2.9.0Install as a Cake Addin
#tool nuget:?package=Serilog.Enrichers.ClientInfo&version=2.9.0Install as a Cake Tool
Enrich logs with client IP, Correlation Id, HTTP request headers, and user claims.
Install the Serilog.Enrichers.ClientInfo NuGet package
Install-Package Serilog.Enrichers.ClientInfo
or
dotnet add package Serilog.Enrichers.ClientInfo
Apply the enricher to your LoggerConfiguration in code:
Log.Logger = new LoggerConfiguration()
.Enrich.WithClientIp()
.Enrich.WithCorrelationId()
.Enrich.WithRequestHeader("Header-Name1")
.Enrich.WithUserClaims(ClaimTypes.NameIdentifier, ClaimTypes.Email)
// ...other configuration...
.CreateLogger();
or in appsettings.json file:
{
"Serilog": {
"MinimumLevel": "Debug",
"Using": [ "Serilog.Enrichers.ClientInfo" ],
"Enrich": [
"WithClientIp",
"WithCorrelationId",
{
"Name": "WithRequestHeader",
"Args": { "headerName": "User-Agent"}
},
{
"Name": "WithUserClaims",
"Args": { "claimNames": ["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"] }
}
],
"WriteTo": [
{ "Name": "Console" }
]
}
}
ClientIp enricher reads client IP from HttpContext.Connection.RemoteIpAddress. Since version 2.1, for security reasons, it no longer reads the x-forwarded-for header. To handle forwarded headers, configure ForwardedHeadersOptions. If you still want to log x-forwarded-for, you can use the RequestHeader enricher.
Log.Logger = new LoggerConfiguration()
.Enrich.WithClientIp()
...
or
{
"Serilog": {
"MinimumLevel": "Debug",
"Using": [ "Serilog.Enrichers.ClientInfo" ],
"Enrich": [
{
"Name": "WithClientIp"
}
],
}
}
You can configure the enricher to prefer or filter specific IP versions (IPv4 or IPv6):
Log.Logger = new LoggerConfiguration()
.Enrich.WithClientIp(IpVersionPreference.Ipv4Only)
...
Available IP version preferences:
None (default): No preference - use whatever IP version is availablePreferIpv4: Prefer IPv4 addresses when multiple are available, fallback to IPv6PreferIpv6: Prefer IPv6 addresses when multiple are available, fallback to IPv4Ipv4Only: Only log IPv4 addresses, ignore IPv6 addressesIpv6Only: Only log IPv6 addresses, ignore IPv4 addressesYou can customize the property name for the logged IP address (default is ClientIp). This is useful for following conventions like OpenTelemetry semantic conventions which recommend client.address:
Log.Logger = new LoggerConfiguration()
.Enrich.WithClientIp("client.address")
...
You can also combine custom property names with IP version preferences:
Log.Logger = new LoggerConfiguration()
.Enrich.WithClientIp(IpVersionPreference.Ipv4Only, "client.address")
...
or in appsettings.json file:
{
"Serilog": {
"MinimumLevel": "Debug",
"Using": [ "Serilog.Enrichers.ClientInfo" ],
"Enrich": [
{
"Name": "WithClientIp",
"Args": {
"ipVersionPreference": "Ipv4Only",
"ipAddressPropertyName": "client.address"
}
}
]
}
}
For CorrelationId enricher you can:
x-correlation-idLog.Logger = new LoggerConfiguration()
.Enrich.WithCorrelationId(headerName: "correlation-id", addValueIfHeaderAbsence: true)
...
or
{
"Serilog": {
"MinimumLevel": "Debug",
"Using": [ "Serilog.Enrichers.ClientInfo" ],
"Enrich": [
{
"Name": "WithCorrelationId",
"Args": {
"headerName": "correlation-id"
"addValueIfHeaderAbsence": true
}
}
],
}
}
You can easily retrieve the correlation ID from HttpContext using the GetCorrelationId() extension method:
public void SomeControllerAction()
{
// This will return the correlation ID that was enriched by the CorrelationIdEnricher
var correlationId = HttpContext.GetCorrelationId();
if (!string.IsNullOrEmpty(correlationId))
{
// You can use it for additional logging/tracing, etc
}
}
This eliminates the need for manual casting and provides a clean API for accessing correlation IDs.
You can use multiple WithRequestHeader to log different request headers. WithRequestHeader accepts two parameters; The first parameter headerName is the header name to log
and the second parameter is propertyName which is the log property name.
Log.Logger = new LoggerConfiguration()
.Enrich.WithRequestHeader(headerName: "header-name-1")
.Enrich.WithRequestHeader(headerName: "header-name-2", propertyName: "SomeHeaderName")
...
or
{
"Serilog": {
"MinimumLevel": "Debug",
"Using": [ "Serilog.Enrichers.ClientInfo" ],
"Enrich": [
{
"Name": "WithRequestHeader",
"Args": {
"headerName": "User-Agent"
}
},
{
"Name": "WithRequestHeader",
"Args": {
"headerName": "Connection"
}
},
{
"Name": "WithRequestHeader",
"Args": {
"headerName": "Content-Length",
"propertyName": "RequestLength"
}
}
],
}
}
To include logged headers in OutputTemplate, the header name without - should be used if you haven't set the log property name. For example, if the header name is User-Agent, you should use UserAgent.
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.Enrich.WithRequestHeader("User-Agent")
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] {Level:u3} {UserAgent} {Message:lj}{NewLine}{Exception}")
The UserClaims enricher allows you to log specific user claim values from authenticated users. This is useful for tracking user-specific information in your logs.
using System.Security.Claims;
Log.Logger = new LoggerConfiguration()
.Enrich.WithUserClaims(ClaimTypes.NameIdentifier, ClaimTypes.Email)
...
or in appsettings.json file:
{
"Serilog": {
"MinimumLevel": "Debug",
"Using": [ "Serilog.Enrichers.ClientInfo" ],
"Enrich": [
{
"Name": "WithUserClaims",
"Args": {
"claimNames": [
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"
]
}
}
]
}
}
null instead of throwing an error.Log.Logger = new LoggerConfiguration()
.Enrich.WithUserClaims(
ClaimTypes.NameIdentifier,
ClaimTypes.Email,
ClaimTypes.Name,
ClaimTypes.Role)
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] User: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier} {Message:lj}{NewLine}{Exception}")
...
You can also log custom claim types:
Log.Logger = new LoggerConfiguration()
.Enrich.WithUserClaims("tenant_id", "organization_id")
...
You need to register the IHttpContextAccessor singleton so the enrichers have access to the requests HttpContext to extract client IP and client agent.
This is what your Startup class should contain in order for this enricher to work as expected:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace MyWebApp
{
public class Startup
{
public Startup()
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] {Level:u3} CLient IP: {ClientIp} Correlation Id: {CorrelationId} header-name: {headername} {Message:lj}{NewLine}{Exception}")
.Enrich.WithClientIp()
.Enrich.WithCorrelationId()
.Enrich.WithRequestHeader("header-name")
.Enrich.WithRequestHeader("another-header-name", "SomePropertyName")
.CreateLogger();
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddHttpContextAccessor();
// ...
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// ...
loggerFactory.AddSerilog();
// ...
}
}
}
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 net8.0 is compatible. net8.0-android net8.0-android was computed. net8.0-browser net8.0-browser was computed. net8.0-ios net8.0-ios was computed. net8.0-maccatalyst net8.0-maccatalyst was computed. net8.0-macos net8.0-macos was computed. net8.0-tvos net8.0-tvos was computed. net8.0-windows net8.0-windows was computed. net9.0 net9.0 is compatible. net9.0-android net9.0-android was computed. net9.0-browser net9.0-browser was computed. net9.0-ios net9.0-ios was computed. net9.0-maccatalyst net9.0-maccatalyst was computed. net9.0-macos net9.0-macos was computed. net9.0-tvos net9.0-tvos was computed. net9.0-windows net9.0-windows was computed. net10.0 net10.0 is compatible. net10.0-android net10.0-android was computed. net10.0-browser net10.0-browser was computed. net10.0-ios net10.0-ios was computed. net10.0-maccatalyst net10.0-maccatalyst was computed. net10.0-macos net10.0-macos was computed. net10.0-tvos net10.0-tvos was computed. net10.0-windows net10.0-windows was computed. |
Showing the top 5 NuGet packages that depend on Serilog.Enrichers.ClientInfo:
| Package | Downloads |
|---|---|
|
Farsica.Framework
Asp.net Core Application Framework |
|
|
SuchenExpert.Core.Common
This package for SuchenExpert projects |
|
|
AIC.Core.Logging.Extensions.Serilog
Shared .NET library for Aerospace, Intelligence, and Cyber solutions. |
|
|
KAM.Aether.SharedLibraries
KAM.Aether.SharedLibraries and SharedModels |
|
|
Services.Common
Package Description |
Showing the top 5 popular GitHub repositories that depend on Serilog.Enrichers.ClientInfo:
| Repository | Stars |
|---|---|
|
featbit/featbit
Enterprise-grade feature flag platform that you can self-host. Get started - free.
|
|
|
CodeMazeBlog/CodeMazeGuides
The main repository for all the Code Maze guides
|
|
|
neozhu/visitormanagement
helps in managing visitors visiting the institutions for various reasons. It allows visitors to check-in digitally to eliminate the tedious registeration and other paperwork. Additionally, it also keeps a track of every individual inside the campus and their timings. Institutions has guards who enter their detail in some notebooks to keep a log which are practically impossible to reconcile. It is really unpleasent and hectic for visitor to stand at the gate and give details about the visit. To ease the process of registeration, Entry-In, Entry-Out, time tracking and logging the history, this VMS can be of great use!!
|
|
|
netcorepal/d3shop
An online shop project based on Domain-Driven Design
|
|
|
samanazadi1996/Sam.CleanArchitecture
The purpose of this template is to provide a robust and streamlined methodology for enterprise application development, capitalizing on the strengths of Clean Architecture and ASP.NET Core.
|
- Update dependencies and add .NET 10 support.