@@ -13,7 +13,9 @@ namespace Serilog.Enrichers
1313{
1414 public class ClientAgentEnricher : ILogEventEnricher
1515 {
16- private const string IpAddressPropertyName = "ClientAgent" ;
16+ private const string ClientAgentPropertyName = "ClientAgent" ;
17+ private const string ClientAgentItemKey = "Serilog_ClientAgent" ;
18+
1719 private readonly IHttpContextAccessor _contextAccessor ;
1820
1921 public ClientAgentEnricher ( ) : this ( new HttpContextAccessor ( ) )
@@ -27,17 +29,27 @@ internal ClientAgentEnricher(IHttpContextAccessor contextAccessor)
2729
2830 public void Enrich ( LogEvent logEvent , ILogEventPropertyFactory propertyFactory )
2931 {
30- if ( _contextAccessor . HttpContext == null )
32+ var httpContext = _contextAccessor . HttpContext ;
33+ if ( httpContext == null )
34+ return ;
35+
36+ if ( httpContext . Items [ ClientAgentItemKey ] is LogEventProperty logEventProperty )
37+ {
38+ logEvent . AddPropertyIfAbsent ( logEventProperty ) ;
3139 return ;
40+ }
41+
3242#if NETFULL
33- var agentName = _contextAccessor . HttpContext . Request . Headers [ "User-Agent" ] ;
43+ var agentName = httpContext . Request . Headers [ "User-Agent" ] ;
3444#else
35- var agentName = _contextAccessor . HttpContext . Request . Headers [ "User-Agent" ] ;
45+ var agentName = httpContext . Request . Headers [ "User-Agent" ] ;
3646#endif
3747
38- var ipAddressProperty = new LogEventProperty ( IpAddressPropertyName , new ScalarValue ( agentName ) ) ;
3948
40- logEvent . AddPropertyIfAbsent ( ipAddressProperty ) ;
49+ var clientAgentProperty = new LogEventProperty ( ClientAgentPropertyName , new ScalarValue ( agentName ) ) ;
50+ httpContext . Items . Add ( ClientAgentItemKey , clientAgentProperty ) ;
51+
52+ logEvent . AddPropertyIfAbsent ( clientAgentProperty ) ;
4153 }
4254 }
4355}
0 commit comments