├── .gitignore ├── LICENSE ├── README.md ├── Serilog.Enrichers.AspnetcoreHttpcontext.sln ├── samples └── SerilogAspnetcoreHttpcontextSample │ ├── Program.cs │ ├── SerilogAspnetcoreHttpcontextSample.csproj │ ├── Startup.cs │ ├── console.png │ └── elastic.png └── src └── Serilog.Enrichers.AspnetcoreHttpcontext ├── AspnetcoreHttpcontextEnricher.cs ├── HttpContextCache.cs ├── LoggerEnrichmentConfigurationExtensions.cs ├── Serilog.Enrichers.AspnetcoreHttpcontext.csproj └── WebhostBuilderExtensions.cs /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Thibaut Renoncourt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # serilog-enrichers-aspnetcore-httpcontext · [![NuGet](https://img.shields.io/nuget/v/Serilog.Enrichers.AspnetcoreHttpcontext.svg?style=flat-square)](https://www.nuget.org/packages/Serilog.Enrichers.AspnetcoreHttpcontext) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com) [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](https://github.com/trenoncourt/serilog-enrichers-aspnetcore-httpcontext/blob/master/LICENSE) 2 | 3 | > Enriches Serilog events with Aspnetcore HttpContext. By default logs all information about the Http Request. Provides access to log whatever you want from the HttpContext, 4 | including Session, Cookies, Request, Connection, User - basically anything from the HttpContext object. 5 | 6 | ## Installation 7 | 8 | ```powershell 9 | Install-Package Serilog.Enrichers.AspnetcoreHttpcontext 10 | ``` 11 | 12 | ## Usage example 13 | 14 | ```c# 15 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 16 | WebHost.CreateDefaultBuilder(args) 17 | .UseStartup() 18 | .UseSerilog((provider, context, loggerConfiguration) => 19 | { 20 | loggerConfiguration.MinimumLevel.Debug() 21 | .MinimumLevel.Override("Microsoft", LogEventLevel.Information) 22 | .Enrich.WithAspnetcoreHttpcontext(provider) 23 | .WriteTo.Console( 24 | outputTemplate: 25 | "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {NewLine}{HttpContext}") 26 | .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200")) 27 | { 28 | IndexFormat = "serilog-enrichers-aspnetcore-httpcontext-{0:yyyy.MM}" 29 | }); 30 | }); 31 | ``` 32 | 33 | You'll have enriched log event like pictures listed bellow 34 | 35 | ![alt text](https://raw.githubusercontent.com/trenoncourt/serilog-enrichers-aspnetcore-httpcontext/master/samples/SerilogAspnetcoreHttpcontextSample/console.png) 36 | 37 | ![alt text](https://raw.githubusercontent.com/trenoncourt/serilog-enrichers-aspnetcore-httpcontext/master/samples/SerilogAspnetcoreHttpcontextSample/elastic.png) 38 | 39 | ## The Basics 40 | 41 | ### Move LoggerConfiguration to the UseSerilog method 42 | The reason for this move is becuase within ASP.NET Core the HttpContext is only available 43 | after the dependency injection engine is established. The ``LogggerConfiguration`` setup 44 | is the same as you would do elsewhere, just the location has moved. 45 | 46 | ### Use the ``WithAspnetcoreHttpcontext`` extension method 47 | Using the method as shown above (with only the ``providers`` parameter passed) will use the default enrichment method. It will format the [HttpContextCache](./src/Serilog.Enrichers.AspnetcoreHttpcontext/HttpContextCache.cs) object from this 48 | project, which contains mostly information from the ``Request`` object of the ``HttpContext``. 49 | 50 | ### Provide your own method that returns what you want from HttpContext 51 | If you want different items from the ``HttpContext`` in your log entries, you can provide your own method to do this. A full working example can be seen in the [samples folder](./samples). 52 | 53 | You provide a second argument to the ``WithAspnetcoreHttpcontext`` method, which is the name of a method with a signature like this: 54 | 55 | ``` 56 | SomeClassYouDefine WhateverNameYouWant(IHttpConextAccessor hca) 57 | ``` 58 | 59 | ``SomeClassYouDefine`` is a simple class that you would create that contains properties for the information from the ``HttpContext`` you want in the log entry. Then inside the method you "new up" the class into an actual object, and use the ``hca`` parameter's ``HttpContext`` 60 | property to fill your object with whatever you want and then return the object. 61 | 62 | Here's the example from the samples folder: 63 | ``` 64 | ... 65 | .Enrich.WithAspnetcoreHttpcontext(provider, 66 | customMethod: CustomEnricherLogic) 67 | ... 68 | 69 | private static MyObject CustomEnricherLogic(IHttpContextAccessor ctx) 70 | { 71 | var context = ctx.HttpContext; 72 | if (context == null) return null; 73 | 74 | var myInfo = new MyObject 75 | { 76 | Path = context.Request.Path.ToString(), 77 | Host = context.Request.Host.ToString(), 78 | Method = context.Request.Method 79 | }; 80 | 81 | var user = context.User; 82 | if (user != null && user.Identity != null && user.Identity.IsAuthenticated) 83 | { 84 | myInfo.UserClaims = user.Claims.Select(a => new KeyValuePair(a.Type, a.Value)).ToList(); 85 | } 86 | return myInfo; 87 | } 88 | 89 | public class MyObject 90 | { 91 | public string Path { get; set; } 92 | public string Host { get; set; } 93 | public string Method { get; set; } 94 | 95 | public List> UserClaims { get; set; } 96 | } 97 | 98 | ``` 99 | 100 | ### Format (or don't) your log entries 101 | Either the standard ``HttpContextCache`` class or your own custom class will be added to the log entry as the ``HttpContext`` property. You can use this in your custom formatting logic or just leave it to the built-in formatters to handle. 102 | 103 | ## Contributing 104 | 105 | 1. Fork it 106 | 2. Create your feature branch (`git checkout -b feature/fooBar`) 107 | 3. Commit your changes (`git commit -am 'Add some fooBar'`) 108 | 4. Push to the branch (`git push origin feature/fooBar`) 109 | 5. Create a new Pull Request 110 | -------------------------------------------------------------------------------- /Serilog.Enrichers.AspnetcoreHttpcontext.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{9D474F06-F098-4C3D-B0CF-BECA1AB485BF}" 4 | EndProject 5 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Serilog.Enrichers.AspnetcoreHttpcontext", "src\Serilog.Enrichers.AspnetcoreHttpcontext\Serilog.Enrichers.AspnetcoreHttpcontext.csproj", "{879C056C-583E-4F73-BEE3-D0C6176C9BE6}" 6 | EndProject 7 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{CC1ECD8E-0F77-414D-8275-11180C429323}" 8 | EndProject 9 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SerilogAspnetcoreHttpcontextSample", "samples\SerilogAspnetcoreHttpcontextSample\SerilogAspnetcoreHttpcontextSample.csproj", "{75AAD085-C4D9-4C21-A67E-F9205134E129}" 10 | EndProject 11 | Global 12 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 13 | Debug|Any CPU = Debug|Any CPU 14 | Release|Any CPU = Release|Any CPU 15 | EndGlobalSection 16 | GlobalSection(NestedProjects) = preSolution 17 | {879C056C-583E-4F73-BEE3-D0C6176C9BE6} = {9D474F06-F098-4C3D-B0CF-BECA1AB485BF} 18 | {75AAD085-C4D9-4C21-A67E-F9205134E129} = {CC1ECD8E-0F77-414D-8275-11180C429323} 19 | EndGlobalSection 20 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 21 | {879C056C-583E-4F73-BEE3-D0C6176C9BE6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 22 | {879C056C-583E-4F73-BEE3-D0C6176C9BE6}.Debug|Any CPU.Build.0 = Debug|Any CPU 23 | {879C056C-583E-4F73-BEE3-D0C6176C9BE6}.Release|Any CPU.ActiveCfg = Release|Any CPU 24 | {879C056C-583E-4F73-BEE3-D0C6176C9BE6}.Release|Any CPU.Build.0 = Release|Any CPU 25 | {75AAD085-C4D9-4C21-A67E-F9205134E129}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 26 | {75AAD085-C4D9-4C21-A67E-F9205134E129}.Debug|Any CPU.Build.0 = Debug|Any CPU 27 | {75AAD085-C4D9-4C21-A67E-F9205134E129}.Release|Any CPU.ActiveCfg = Release|Any CPU 28 | {75AAD085-C4D9-4C21-A67E-F9205134E129}.Release|Any CPU.Build.0 = Release|Any CPU 29 | EndGlobalSection 30 | EndGlobal 31 | -------------------------------------------------------------------------------- /samples/SerilogAspnetcoreHttpcontextSample/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Microsoft.AspNetCore; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.AspNetCore.Http; 7 | using Serilog; 8 | using Serilog.Core; 9 | using Serilog.Enrichers.AspnetcoreHttpcontext; 10 | using Serilog.Events; 11 | using Serilog.Sinks.Elasticsearch; 12 | 13 | namespace SerilogAspnetcoreHttpcontextSample 14 | { 15 | public class Program 16 | { 17 | public static void Main(string[] args) 18 | { 19 | CreateWebHostBuilder(args).Build().Run(); 20 | } 21 | 22 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 23 | WebHost.CreateDefaultBuilder(args) 24 | .UseStartup() 25 | .UseSerilog((provider, context, loggerConfiguration) => 26 | { 27 | loggerConfiguration.MinimumLevel.Debug() 28 | .MinimumLevel.Override("Microsoft", LogEventLevel.Information) 29 | .Enrich.WithAspnetcoreHttpcontext(provider, 30 | customMethod: CustomEnricherLogic) 31 | .WriteTo.Console( 32 | outputTemplate: 33 | "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {NewLine}{HttpContext} {NewLine}{Exception}"); 34 | //.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200")) 35 | //{ 36 | // IndexFormat = "serilog-enrichers-aspnetcore-httpcontext-{0:yyyy.MM}" 37 | //}); 38 | }); 39 | 40 | private static MyObject CustomEnricherLogic(IHttpContextAccessor ctx) 41 | { 42 | var context = ctx.HttpContext; 43 | if (context == null) return null; 44 | 45 | var myInfo = new MyObject 46 | { 47 | Path = context.Request.Path.ToString(), 48 | Host = context.Request.Host.ToString(), 49 | Method = context.Request.Method 50 | }; 51 | 52 | var user = context.User; 53 | if (user != null && user.Identity != null && user.Identity.IsAuthenticated) 54 | { 55 | myInfo.UserClaims = user.Claims.Select(a => new KeyValuePair(a.Type, a.Value)).ToList(); 56 | } 57 | return myInfo; 58 | } 59 | 60 | public class MyObject 61 | { 62 | public string Path { get; set; } 63 | public string Host { get; set; } 64 | public string Method { get; set; } 65 | 66 | public List> UserClaims { get; set; } 67 | } 68 | } 69 | } -------------------------------------------------------------------------------- /samples/SerilogAspnetcoreHttpcontextSample/SerilogAspnetcoreHttpcontextSample.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | netcoreapp2.1 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 3.1.1 15 | 16 | 17 | 6.5.0 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /samples/SerilogAspnetcoreHttpcontextSample/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Builder; 6 | using Microsoft.AspNetCore.Hosting; 7 | using Microsoft.AspNetCore.Http; 8 | using Microsoft.Extensions.DependencyInjection; 9 | 10 | namespace SerilogAspnetcoreHttpcontextSample 11 | { 12 | public class Startup 13 | { 14 | // This method gets called by the runtime. Use this method to add services to the container. 15 | // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 16 | public void ConfigureServices(IServiceCollection services) 17 | { 18 | } 19 | 20 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 21 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) 22 | { 23 | if (env.IsDevelopment()) 24 | { 25 | app.UseDeveloperExceptionPage(); 26 | } 27 | 28 | app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /samples/SerilogAspnetcoreHttpcontextSample/console.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trenoncourt/serilog-enrichers-aspnetcore-httpcontext/9962df923daa1a061ad4a798d5edfcc848c0a014/samples/SerilogAspnetcoreHttpcontextSample/console.png -------------------------------------------------------------------------------- /samples/SerilogAspnetcoreHttpcontextSample/elastic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trenoncourt/serilog-enrichers-aspnetcore-httpcontext/9962df923daa1a061ad4a798d5edfcc848c0a014/samples/SerilogAspnetcoreHttpcontextSample/elastic.png -------------------------------------------------------------------------------- /src/Serilog.Enrichers.AspnetcoreHttpcontext/AspnetcoreHttpcontextEnricher.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Text; 5 | using Microsoft.AspNetCore.Http; 6 | using Microsoft.AspNetCore.Http.Internal; 7 | using Serilog.Core; 8 | using Serilog.Events; 9 | 10 | namespace Serilog.Enrichers.AspnetcoreHttpcontext 11 | { 12 | public class AspnetcoreHttpcontextEnricher : ILogEventEnricher 13 | { 14 | private readonly IHttpContextAccessor _httpContextAccessor; 15 | private Func _customAction = null; 16 | 17 | public AspnetcoreHttpcontextEnricher(IHttpContextAccessor httpContextAccessor) 18 | { 19 | _httpContextAccessor = httpContextAccessor; 20 | _customAction = StandardEnricher; // by default 21 | 22 | } 23 | public void SetCustomAction(Func customAction) 24 | { 25 | _customAction = customAction; 26 | } 27 | 28 | public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) 29 | { 30 | HttpContext ctx = _httpContextAccessor.HttpContext; 31 | if (ctx == null) return; 32 | 33 | var httpContextCache = ctx.Items[$"serilog-enrichers-aspnetcore-httpcontext"]; 34 | 35 | if (httpContextCache == null) 36 | { 37 | httpContextCache = _customAction.Invoke(_httpContextAccessor); 38 | ctx.Items[$"serilog-enrichers-aspnetcore-httpcontext"] = httpContextCache; 39 | } 40 | logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("HttpContext", httpContextCache, true)); 41 | } 42 | 43 | public static object StandardEnricher(IHttpContextAccessor hca) 44 | { 45 | var ctx = hca.HttpContext; 46 | if (ctx == null) return null; 47 | 48 | var httpContextCache = new HttpContextCache 49 | { 50 | IpAddress = ctx.Connection.RemoteIpAddress.ToString(), 51 | Host = ctx.Request.Host.ToString(), 52 | Path = ctx.Request.Path.ToString(), 53 | IsHttps = ctx.Request.IsHttps, 54 | Scheme = ctx.Request.Scheme, 55 | Method = ctx.Request.Method, 56 | ContentType = ctx.Request.ContentType, 57 | Protocol = ctx.Request.Protocol, 58 | QueryString = ctx.Request.QueryString.ToString(), 59 | Query = ctx.Request.Query.ToDictionary(x => x.Key, y => y.Value.ToString()), 60 | Headers = ctx.Request.Headers.ToDictionary(x => x.Key, y => y.Value.ToString()), 61 | Cookies = ctx.Request.Cookies.ToDictionary(x => x.Key, y => y.Value.ToString()) 62 | }; 63 | 64 | if (ctx.Request.ContentLength.HasValue && ctx.Request.ContentLength > 0) 65 | { 66 | ctx.Request.EnableRewind(); 67 | 68 | using (StreamReader reader = new StreamReader(ctx.Request.Body, Encoding.UTF8, true, 1024, true)) 69 | { 70 | httpContextCache.Body = reader.ReadToEnd(); 71 | } 72 | 73 | ctx.Request.Body.Position = 0; 74 | } 75 | return httpContextCache; 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/Serilog.Enrichers.AspnetcoreHttpcontext/HttpContextCache.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Serilog.Enrichers.AspnetcoreHttpcontext 4 | { 5 | public class HttpContextCache 6 | { 7 | public string IpAddress { get; set; } 8 | 9 | public string Host { get; set; } 10 | 11 | public string Path { get; set; } 12 | 13 | public bool IsHttps { get; set; } 14 | 15 | public string Scheme { get; set; } 16 | 17 | public string Method { get; set; } 18 | 19 | public string ContentType { get; set; } 20 | 21 | public string Protocol { get; set; } 22 | 23 | public string QueryString { get; set; } 24 | 25 | public Dictionary Query { get; set; } 26 | 27 | public Dictionary Headers { get; set; } 28 | 29 | public Dictionary Cookies { get; set; } 30 | 31 | public string Body { get; set; } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Serilog.Enrichers.AspnetcoreHttpcontext/LoggerEnrichmentConfigurationExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.AspNetCore.Http; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Serilog.Configuration; 5 | using Serilog.Core; 6 | using Serilog.Events; 7 | 8 | namespace Serilog.Enrichers.AspnetcoreHttpcontext 9 | { 10 | /// 11 | /// Extends to add enrichers for . 12 | /// capabilities. 13 | /// 14 | public static class LoggerEnrichmentConfigurationExtensions 15 | { 16 | /// 17 | /// Enrich log events with Aspnetcore httpContext properties. 18 | /// 19 | /// Logger enrichment configuration. 20 | /// 21 | /// Configuration object allowing method chaining. 22 | public static LoggerConfiguration WithAspnetcoreHttpcontext(this LoggerEnrichmentConfiguration enrichmentConfiguration, 23 | IServiceProvider serviceProvider, Func customMethod = null) 24 | { 25 | if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration)); 26 | 27 | var enricher = serviceProvider.GetService(); 28 | 29 | if (customMethod != null) 30 | enricher.SetCustomAction(customMethod); 31 | 32 | return enrichmentConfiguration.With(enricher); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /src/Serilog.Enrichers.AspnetcoreHttpcontext/Serilog.Enrichers.AspnetcoreHttpcontext.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | netstandard2.0 4 | trenoncourt;dahlsailrunner 5 | Enriches Serilog events with Aspnetcore HttpContext 6 | https://github.com/trenoncourt/serilog-enrichers-aspnetcore-httpcontext/blob/master/LICENSE 7 | https://github.com/trenoncourt/serilog-enrichers-aspnetcore-httpcontext 8 | serilog enrichers enricher aspnetcore httpcontext 9 | 1.1.0 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/Serilog.Enrichers.AspnetcoreHttpcontext/WebhostBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.DependencyInjection.Extensions; 6 | using Microsoft.Extensions.Logging; 7 | using Serilog.AspNetCore; 8 | using Serilog.Core; 9 | 10 | namespace Serilog.Enrichers.AspnetcoreHttpcontext 11 | { 12 | public static class WebhostBuilderExtensions 13 | { 14 | /// Sets Serilog as the logging provider. 15 | /// 16 | /// A is supplied so that configuration and hosting information can be used. 17 | /// The logger will be shut down when application services are disposed. 18 | /// 19 | /// The web host builder to configure. 20 | /// The delegate for configuring the that will be used to construct a . 21 | /// Indicates whether to preserve the value of . 22 | /// The web host builder. 23 | public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, 24 | Action configureLogger, 25 | bool preserveStaticLogger = false) 26 | { 27 | if (builder == null) 28 | throw new ArgumentNullException(nameof(builder)); 29 | if (configureLogger == null) 30 | throw new ArgumentNullException(nameof(configureLogger)); 31 | 32 | builder.ConfigureServices((context, collection) => 33 | { 34 | collection.TryAddSingleton(); 35 | var provider = collection.BuildServiceProvider(); 36 | var hca = provider.GetRequiredService(); 37 | 38 | collection.AddSingleton(); 39 | 40 | LoggerConfiguration loggerConfiguration = new LoggerConfiguration(); 41 | configureLogger(collection.BuildServiceProvider(), context, loggerConfiguration); 42 | 43 | Logger logger = loggerConfiguration.CreateLogger(); 44 | if (preserveStaticLogger) 45 | { 46 | collection.AddSingleton(services => (ILoggerFactory)new SerilogLoggerFactory(logger, true)); 47 | } 48 | else 49 | { 50 | Log.Logger = logger; 51 | collection.AddSingleton(services => (ILoggerFactory)new SerilogLoggerFactory(null, true)); 52 | } 53 | }); 54 | return builder; 55 | } 56 | } 57 | } --------------------------------------------------------------------------------