├── .gitignore ├── LICENSE ├── README.md ├── Samples ├── AspNetCoreSample │ ├── AspNetCoreSample.csproj │ ├── Controllers │ │ └── WeatherForecastController.cs │ ├── Program.cs │ ├── Startup.cs │ ├── WeatherForecast.cs │ ├── appsettings.Development.json │ └── appsettings.json ├── ConsoleSample │ ├── ConsoleSample.csproj │ └── Program.cs └── FileConfigurationSample │ ├── FileConfigurationSample.csproj │ ├── Program.cs │ └── appsettings.json ├── Serilog.ThrowContext.Tests ├── CaptureOriginContextTests.cs ├── EnrichersOrderTests.cs ├── FrameworkLoggerTests.cs ├── PreventStackOverflowTests.cs ├── ReThrowTests.cs ├── Serilog.ThrowContext.Tests.csproj ├── Support │ ├── DelegatingSink.cs │ └── LogEventPropertyValueExtensions.cs └── WrapTests.cs ├── Serilog.ThrowContext.sln ├── Serilog.ThrowContext ├── Serilog.ThrowContext.csproj └── ThrowContextEnricher.cs └── azure-pipelines.yml /.gitignore: -------------------------------------------------------------------------------- 1 | ## Serilog-specific 2 | .vscode/ 3 | 4 | ## Ignore Visual Studio temporary files, build results, and 5 | ## files generated by popular Visual Studio add-ons. 6 | ## 7 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 8 | 9 | # User-specific files 10 | *.suo 11 | *.user 12 | *.userosscache 13 | *.sln.docstates 14 | 15 | # User-specific files (MonoDevelop/Xamarin Studio) 16 | *.userprefs 17 | 18 | # Build results 19 | [Dd]ebug/ 20 | [Dd]ebugPublic/ 21 | [Rr]elease/ 22 | [Rr]eleases/ 23 | x64/ 24 | x86/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | **/Properties/launchSettings.json 59 | 60 | # StyleCop 61 | StyleCopReport.xml 62 | 63 | # Files built by Visual Studio 64 | *_i.c 65 | *_p.c 66 | *_i.h 67 | *.ilk 68 | *.meta 69 | *.obj 70 | *.iobj 71 | *.pch 72 | *.pdb 73 | *.ipdb 74 | *.pgc 75 | *.pgd 76 | *.rsp 77 | *.sbr 78 | *.tlb 79 | *.tli 80 | *.tlh 81 | *.tmp 82 | *.tmp_proj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | 259 | # Microsoft Fakes 260 | FakesAssemblies/ 261 | 262 | # GhostDoc plugin setting file 263 | *.GhostDoc.xml 264 | 265 | # Node.js Tools for Visual Studio 266 | .ntvs_analysis.dat 267 | node_modules/ 268 | 269 | # Visual Studio 6 build log 270 | *.plg 271 | 272 | # Visual Studio 6 workspace options file 273 | *.opt 274 | 275 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 276 | *.vbw 277 | 278 | # Visual Studio LightSwitch build output 279 | **/*.HTMLClient/GeneratedArtifacts 280 | **/*.DesktopClient/GeneratedArtifacts 281 | **/*.DesktopClient/ModelManifest.xml 282 | **/*.Server/GeneratedArtifacts 283 | **/*.Server/ModelManifest.xml 284 | _Pvt_Extensions 285 | 286 | # Paket dependency manager 287 | .paket/paket.exe 288 | paket-files/ 289 | 290 | # FAKE - F# Make 291 | .fake/ 292 | 293 | # JetBrains Rider 294 | .idea/ 295 | *.sln.iml 296 | 297 | # CodeRush 298 | .cr/ 299 | 300 | # Python Tools for Visual Studio (PTVS) 301 | __pycache__/ 302 | *.pyc 303 | 304 | # Cake - Uncomment if you are using it 305 | # tools/** 306 | # !tools/packages.config 307 | 308 | # Tabs Studio 309 | *.tss 310 | 311 | # Telerik's JustMock configuration file 312 | *.jmconfig 313 | 314 | # BizTalk build output 315 | *.btp.cs 316 | *.btm.cs 317 | *.odx.cs 318 | *.xsd.cs 319 | 320 | # OpenCover UI analysis results 321 | OpenCover/ 322 | 323 | # Azure Stream Analytics local run output 324 | ASALocalRun/ 325 | 326 | # MSBuild Binary and Structured Log 327 | *.binlog 328 | 329 | # NVidia Nsight GPU debugger configuration file 330 | *.nvuser 331 | 332 | # MFractors (Xamarin productivity tool) working folder 333 | .mfractor/ 334 | *.orig 335 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Anatoly Buranov 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 | # Throw context enricher for Serilog [![Azure DevOps tests](https://img.shields.io/azure-devops/tests/tolyandre/serilog-throw-context-enricher/1)](https://tolyandre.visualstudio.com/serilog-throw-context-enricher/_build?definitionId=1) [![Nuget](https://img.shields.io/nuget/v/Serilog.ThrowContext)](https://www.nuget.org/packages/Serilog.ThrowContext) 2 | Captures LogContext on `throw` to enrich exception's log with origin context. 3 | 4 | ## Use case 5 | Assume an exception is thrown in scope with context properties: 6 | ```c# 7 | [HttpGet()] 8 | public WeatherForecast Get() 9 | { 10 | var weatherForecast = new WeatherForecast 11 | { 12 | Date = DateTime.Now.AddDays(1), 13 | TemperatureC = new Random().Next(-20, 55), 14 | } 15 | 16 | using (LogContext.PushProperty("WeatherForecast", weatherForecast)) 17 | { 18 | throw new Exception("Oops"); 19 | } 20 | } 21 | ``` 22 | If the exception is caught and logged outside the scope, context properties are lost by default. 23 | ```c# 24 | // global exception handler middleware 25 | app.Use(async (context, next) => 26 | { 27 | try 28 | { 29 | await next(); 30 | } 31 | catch (Exception ex) 32 | { 33 | log.LogError(ex, "Exceptional weather"); // would not contain WeatherForecast property` 34 | } 35 | }); 36 | ``` 37 | 38 | This library enriches exception logs with properties from a throwing scope. 39 | 40 | It works both with pure Serilog `LogContext.PushProperty()` and framework's logger `_logger.BeginScope()`. Some special cases described below. 41 | 42 | 43 | ## Setup 44 | Add `ThrowContextEnricher` globally or enrich a specific exception handler. 45 | 46 | ### Global setup 47 | Just add `.Enrich.With()`: 48 | 49 | ```c# 50 | Log.Logger = new LoggerConfiguration() 51 | .Enrich.With() 52 | .Enrich.FromLogContext() 53 | .WriteTo 54 | ... 55 | .CreateLogger(); 56 | ``` 57 | 58 | ### Setup with appsettings.json 59 | Full `appsettings.json` configuration is also possible with [Serilog.Settings.Configuration](https://github.com/serilog/serilog-settings-configuration). 60 | Make sure you referenced all the assemblies. See [appsettings.json](./Samples/FileConfigurationSample/appsettings.json) in Samples. 61 | ```json 62 | { 63 | "Serilog": { 64 | "MinimumLevel": "Debug", 65 | "Enrich": [ 66 | "FromLogContext", 67 | { 68 | "Name": "With", 69 | "Args": { "enricher": "Serilog.ThrowContext.ThrowContextEnricher, Serilog.ThrowContext" } 70 | } 71 | ], 72 | "WriteTo": [{ 73 | "Name": "Console", 74 | "Args": { 75 | "formatter": "Serilog.Formatting.Compact.RenderedCompactJsonFormatter, Serilog.Formatting.Compact" 76 | } 77 | } 78 | ] 79 | } 80 | } 81 | ``` 82 | 83 | ```c# 84 | var logger = new LoggerConfiguration() 85 | .ReadFrom.Configuration(configuration) 86 | .CreateLogger(); 87 | ``` 88 | 89 | ### Note on enrichers order 90 | Properties can exist both in exception's origin and exception handler contexts. And they can have different values. In this case order of `ThrowContextEnricher` and `FromLogContext` matters: 91 | 92 | 93 | 94 | 103 | 112 |
95 |
 96 | // Logs value from exception origin (A="inner")
 97 | Log.Logger = new LoggerConfiguration()
 98 |     .Enrich.With<ThrowContextEnricher>()
 99 |     .Enrich.FromLogContext()
100 |     ...
101 | 
102 |
104 |
105 | // Logs value from exception handler (A="outer")
106 | Log.Logger = new LoggerConfiguration()
107 |     .Enrich.FromLogContext()
108 |     .Enrich.With<ThrowContextEnricher>()
109 |     ...
110 | 
111 |
113 | 114 | ```c# 115 | using (LogContext.PushProperty("A", "outer")) 116 | try 117 | { 118 | using (LogContext.PushProperty("A", "inner")) 119 | throw new Exception(); 120 | } 121 | catch (Exception ex) 122 | { 123 | // A=inner or A=outer? 124 | Log.Error(ex, "Value of A is {A}"); 125 | } 126 | ``` 127 | 128 | 129 | 130 | ### Local enrichment 131 | To enrich only specific logs, push `ThrowContextEnricher` to LogContext as usual: 132 | 133 | ```c# 134 | Log.Logger = new LoggerConfiguration() 135 | .Enrich.FromLogContext() 136 | ... 137 | .CreateLogger(); 138 | 139 | ThrowContextEnricher.EnsureInitialized(); 140 | 141 | ... 142 | using (LogContext.PushProperty("A", "outer")) 143 | try 144 | { 145 | using (LogContext.PushProperty("A", "inner")) 146 | { 147 | throw new Exception(); 148 | } 149 | 150 | } 151 | catch (Exception ex) 152 | { 153 | using (LogContext.Push(new ThrowContextEnricher())) 154 | { 155 | Log.Error(ex, "Value of A is {A}"); // "Value of A is \"inner\"" 156 | } 157 | } 158 | ``` 159 | Note `ThrowContextEnricher.EnsureInitialized()` is used to trigger `ThrowContextEnricher` to begin capturing properties. If this call is omitted, enricher initializes lazily. Thus the first logged exception would miss properties. 160 | 161 | ## Special cases 162 | 163 | ### Rethrow 164 | If an exception is rethrown in a different context, the origin property value is not overwritten: 165 | ```c# 166 | Log.Logger = new LoggerConfiguration() 167 | .Enrich.With() 168 | .Enrich.FromLogContext() 169 | ... 170 | .CreateLogger(); 171 | 172 | try 173 | { 174 | try 175 | { 176 | using (LogContext.PushProperty("A", 1)) 177 | throw new ApplicationException(); 178 | } 179 | catch 180 | { 181 | using (LogContext.PushProperty("A", 2)) 182 | using (LogContext.PushProperty("B", 2)) 183 | throw; 184 | } 185 | } 186 | catch (ApplicationException ex) 187 | { 188 | Log.Information(ex, "A={A}, B={B}"); // "A=1, B=2" 189 | } 190 | ``` 191 | 192 | ### Wrap 193 | If an exception is wrapped into another in a different context, the wrapper context is used. Log of inner exception produces origin value though. 194 | 195 | ```c# 196 | Log.Logger = new LoggerConfiguration() 197 | .Enrich.With() 198 | .Enrich.FromLogContext() 199 | ... 200 | .CreateLogger(); 201 | 202 | try 203 | { 204 | try 205 | { 206 | using (LogContext.PushProperty("A", 1)) 207 | throw new Exception(); 208 | } 209 | catch (Exception ex) 210 | { 211 | using (LogContext.PushProperty("A", 2)) 212 | using (LogContext.PushProperty("B", 2)) 213 | throw new ApplicationException("Wrapper", ex); 214 | } 215 | } 216 | catch (ApplicationException ex) 217 | { 218 | Log.Information(ex, "A={A}, B={B}"); // "A=2, B=2" 219 | Log.Information(ex.InnerException, "A={A}, B={B}"); // "A=1, B={B}" 220 | } 221 | ``` 222 | -------------------------------------------------------------------------------- /Samples/AspNetCoreSample/AspNetCoreSample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /Samples/AspNetCoreSample/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.Extensions.Logging; 4 | using Serilog.Context; 5 | 6 | namespace AspNetCoreSample.Controllers 7 | { 8 | [ApiController] 9 | [Route("[controller]")] 10 | public class WeatherForecastController : ControllerBase 11 | { 12 | private static readonly string[] Summaries = new[] 13 | { 14 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 15 | }; 16 | 17 | private readonly ILogger _logger; 18 | 19 | public WeatherForecastController(ILogger logger) 20 | { 21 | _logger = logger; 22 | } 23 | 24 | [HttpGet] 25 | public RedirectResult Get() 26 | { 27 | return Redirect("WeatherForecast/get1"); 28 | } 29 | 30 | [HttpGet("get1")] 31 | public WeatherForecast Get1() 32 | { 33 | var rng = new Random(); 34 | using (LogContext.PushProperty("WeatherForecast", new 35 | { 36 | Date = DateTime.Now.AddDays(1), 37 | TemperatureC = rng.Next(-20, 55), 38 | Summary = Summaries[rng.Next(Summaries.Length)] 39 | })) 40 | { 41 | _logger.LogInformation("Today Weather forecast 1"); 42 | 43 | throw new InvalidOperationException("See context properties in log file"); 44 | } 45 | } 46 | 47 | [HttpGet("get2")] 48 | public WeatherForecast Get2() 49 | { 50 | var rng = new Random(); 51 | using (_logger.BeginScope(new 52 | { 53 | Date = DateTime.Now.AddDays(1), 54 | TemperatureC = rng.Next(-20, 55), 55 | Summary = Summaries[rng.Next(Summaries.Length)] 56 | })) 57 | { 58 | _logger.LogInformation("Today Weather forecast 2"); 59 | 60 | throw new InvalidOperationException("See context properties in log file"); 61 | } 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Samples/AspNetCoreSample/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Hosting; 3 | 4 | namespace AspNetCoreSample 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | CreateHostBuilder(args).Build().Run(); 11 | } 12 | 13 | public static IHostBuilder CreateHostBuilder(string[] args) => 14 | Host.CreateDefaultBuilder(args) 15 | .ConfigureWebHostDefaults(webBuilder => 16 | { 17 | webBuilder.UseStartup(); 18 | }); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Samples/AspNetCoreSample/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.Mvc; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.DependencyInjection; 10 | using Microsoft.Extensions.Hosting; 11 | using Microsoft.Extensions.Logging; 12 | using Serilog; 13 | using Serilog.Formatting.Compact; 14 | using Serilog.ThrowContext; 15 | 16 | namespace AspNetCoreSample 17 | { 18 | public class Startup 19 | { 20 | public Startup(IConfiguration configuration) 21 | { 22 | Configuration = configuration; 23 | } 24 | 25 | public IConfiguration Configuration { get; } 26 | 27 | // This method gets called by the runtime. Use this method to add services to the container. 28 | public void ConfigureServices(IServiceCollection services) 29 | { 30 | services.AddControllers(); 31 | services.AddLogging(loggingBuilder => 32 | loggingBuilder.AddSerilog( 33 | new LoggerConfiguration() 34 | .Enrich.FromLogContext() 35 | .Enrich.With() 36 | .WriteTo.File(new CompactJsonFormatter(), "log.txt") 37 | .CreateLogger(), 38 | dispose: true)); 39 | } 40 | 41 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 42 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger log) 43 | { 44 | app.Use(async (context, next) => 45 | { 46 | try 47 | { 48 | await next(); 49 | } 50 | catch (Exception ex) 51 | { 52 | log.LogError(ex, "Exceptional weather"); 53 | } 54 | }); 55 | 56 | if (env.IsDevelopment()) 57 | { 58 | app.UseDeveloperExceptionPage(); 59 | } 60 | 61 | app.UseRouting(); 62 | 63 | app.UseAuthorization(); 64 | 65 | app.UseEndpoints(endpoints => 66 | { 67 | endpoints.MapControllers(); 68 | }); 69 | 70 | 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /Samples/AspNetCoreSample/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace AspNetCoreSample 4 | { 5 | public class WeatherForecast 6 | { 7 | public DateTime Date { get; set; } 8 | 9 | public int TemperatureC { get; set; } 10 | 11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 12 | 13 | public string Summary { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Samples/AspNetCoreSample/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Samples/AspNetCoreSample/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*" 10 | } 11 | -------------------------------------------------------------------------------- /Samples/ConsoleSample/ConsoleSample.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | Serilog.ThrowContext.ExampleApp 7 | 8 | 9 | 10 | 11 | all 12 | runtime; build; native; contentfiles; analyzers; buildtransitive 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Samples/ConsoleSample/Program.cs: -------------------------------------------------------------------------------- 1 | using Serilog; 2 | using Serilog.Context; 3 | using Serilog.Formatting.Compact; 4 | using Serilog.ThrowContext; 5 | using System; 6 | 7 | namespace ExampleApp 8 | { 9 | class Program 10 | { 11 | static void Main(string[] args) 12 | { 13 | //Example1(); 14 | //Example2(); 15 | Example3(); 16 | //ExampleRethrow(); 17 | //ExampleWrap(); 18 | //ThrowInEnricherScope(); 19 | 20 | Log.CloseAndFlush(); 21 | } 22 | 23 | private static void Example1() 24 | { 25 | Log.Logger = new LoggerConfiguration() 26 | .Enrich.With() 27 | .Enrich.FromLogContext() 28 | .WriteTo.Console(new RenderedCompactJsonFormatter()) 29 | .CreateLogger(); 30 | 31 | using (LogContext.PushProperty("MyName", "Example1")) 32 | try 33 | { 34 | using (LogContext.PushProperty("MyName", "Inside TRY in Example1")) 35 | using (LogContext.PushProperty("Local", "Value from origin context")) 36 | { 37 | throw new InvalidOperationException("test"); 38 | } 39 | 40 | } 41 | catch (Exception ex) 42 | { 43 | Log.Error(ex, "Exception caught in MakeLogs()"); 44 | } 45 | } 46 | 47 | private static void Example2() 48 | { 49 | Log.Logger = new LoggerConfiguration() 50 | .Enrich.With() 51 | .Enrich.FromLogContext() 52 | .WriteTo.Console(new RenderedCompactJsonFormatter()) 53 | .CreateLogger(); 54 | 55 | using (LogContext.PushProperty("A", "outer")) 56 | try 57 | { 58 | using (LogContext.PushProperty("A", "inner")) 59 | { 60 | throw new Exception(); 61 | } 62 | 63 | } 64 | catch (Exception ex) 65 | { 66 | Log.Error(ex, "Value of A is {A}"); 67 | } 68 | } 69 | 70 | private static void Example3() 71 | { 72 | Log.Logger = new LoggerConfiguration() 73 | .Enrich.FromLogContext() 74 | .WriteTo.Console(new RenderedCompactJsonFormatter()) 75 | .CreateLogger(); 76 | 77 | ThrowContextEnricher.EnsureInitialized(); 78 | 79 | using (LogContext.PushProperty("A", "outer")) 80 | try 81 | { 82 | using (LogContext.PushProperty("A", "inner")) 83 | { 84 | throw new Exception(); 85 | } 86 | 87 | } 88 | catch (Exception ex) 89 | { 90 | using (LogContext.Push(new ThrowContextEnricher())) 91 | { 92 | Log.Error(ex, "Value of A is {A}"); 93 | } 94 | } 95 | } 96 | 97 | private static void ExampleRethrow() 98 | { 99 | Log.Logger = new LoggerConfiguration() 100 | .Enrich.With() 101 | .Enrich.FromLogContext() 102 | .WriteTo.Console(new RenderedCompactJsonFormatter()) 103 | .CreateLogger(); 104 | 105 | try 106 | { 107 | try 108 | { 109 | using (LogContext.PushProperty("A", 1)) 110 | throw new ApplicationException(); 111 | } 112 | catch 113 | { 114 | using (LogContext.PushProperty("A", 2)) 115 | using (LogContext.PushProperty("B", 2)) 116 | throw; 117 | } 118 | } 119 | catch (ApplicationException ex) 120 | { 121 | Log.Information(ex, "A={A}, B={B}"); 122 | } 123 | } 124 | 125 | public static void ExampleWrap() 126 | { 127 | Log.Logger = new LoggerConfiguration() 128 | .Enrich.With() 129 | .Enrich.FromLogContext() 130 | .WriteTo.Console(new RenderedCompactJsonFormatter()) 131 | .CreateLogger(); 132 | 133 | try 134 | { 135 | try 136 | { 137 | using (LogContext.PushProperty("A", 1)) 138 | throw new Exception(); 139 | } 140 | catch (Exception ex) 141 | { 142 | using (LogContext.PushProperty("A", 2)) 143 | using (LogContext.PushProperty("B", 2)) 144 | throw new ApplicationException("Wrapper", ex); 145 | } 146 | } 147 | catch (ApplicationException ex) 148 | { 149 | Log.Information(ex, "A={A}, B={B}"); 150 | Log.Information(ex.InnerException, "A={A}, B={B}"); 151 | } 152 | } 153 | 154 | public static void ThrowInEnricherScope() 155 | { 156 | Log.Logger = new LoggerConfiguration() 157 | .Enrich.FromLogContext() 158 | .WriteTo.Console(new RenderedCompactJsonFormatter()) 159 | .CreateLogger(); 160 | 161 | using (LogContext.Push(new ThrowContextEnricher())) 162 | { 163 | try 164 | { 165 | using (LogContext.PushProperty("A", 1)) 166 | throw new ApplicationException(); 167 | 168 | } 169 | catch (ApplicationException ex) 170 | { 171 | Log.Information(ex, "Unit test"); 172 | } 173 | } 174 | } 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /Samples/FileConfigurationSample/FileConfigurationSample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net7.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | PreserveNewest 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Samples/FileConfigurationSample/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using Serilog; 3 | using Serilog.Context; 4 | 5 | // Demo of configuration from appsettings.json file 6 | 7 | var configuration = new ConfigurationBuilder() 8 | .SetBasePath(Directory.GetCurrentDirectory()) 9 | .AddJsonFile("appsettings.json") 10 | .Build(); 11 | 12 | var logger = new LoggerConfiguration() 13 | .ReadFrom.Configuration(configuration) 14 | .CreateLogger(); 15 | 16 | try 17 | { 18 | using (LogContext.PushProperty("PropertyMustBeInLog", "1")) 19 | throw new ApplicationException("Hello, world!"); 20 | 21 | } 22 | catch (ApplicationException ex) 23 | { 24 | logger.Information(ex, "Test exception"); 25 | } -------------------------------------------------------------------------------- /Samples/FileConfigurationSample/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Serilog": { 3 | "MinimumLevel": "Debug", 4 | "Enrich": [ 5 | "FromLogContext", 6 | { 7 | "Name": "With", 8 | "Args": { "enricher": "Serilog.ThrowContext.ThrowContextEnricher, Serilog.ThrowContext" } 9 | } 10 | ], 11 | "WriteTo": [{ 12 | "Name": "Console", 13 | "Args": { 14 | "formatter": "Serilog.Formatting.Compact.RenderedCompactJsonFormatter, Serilog.Formatting.Compact" 15 | } 16 | } 17 | ] 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Serilog.ThrowContext.Tests/CaptureOriginContextTests.cs: -------------------------------------------------------------------------------- 1 | using Serilog.Context; 2 | using Serilog.Core.Enrichers; 3 | using Serilog.Events; 4 | using Serilog.ThrowContext.Tests.Support; 5 | using System; 6 | using System.Threading.Tasks; 7 | using Xunit; 8 | 9 | namespace Serilog.ThrowContext.Tests 10 | { 11 | public class CaptureOriginContextTests 12 | { 13 | private LogEvent _lastEvent = null; 14 | private readonly ILogger _log; 15 | 16 | public CaptureOriginContextTests() 17 | { 18 | ThrowContextEnricher.EnsureInitialized(); 19 | 20 | _log = new LoggerConfiguration() 21 | .Enrich.FromLogContext() 22 | .WriteTo.Sink(new DelegatingSink(e => _lastEvent = e)) 23 | .CreateLogger(); 24 | } 25 | 26 | [Fact] 27 | public void CapturesContextProperty() 28 | { 29 | try 30 | { 31 | using (LogContext.Push(new PropertyEnricher("A", 1))) 32 | throw new ApplicationException(); 33 | 34 | } 35 | catch (ApplicationException ex) 36 | { 37 | using (LogContext.Push(new ThrowContextEnricher())) 38 | _log.Information(ex, "Unit test"); 39 | 40 | } 41 | 42 | Assert.Equal(1, _lastEvent.Properties["A"].LiteralValue()); 43 | } 44 | 45 | [Fact] 46 | public async Task CapturesContextPropertyAsync() 47 | { 48 | try 49 | { 50 | await Task.Delay(1); 51 | 52 | using (LogContext.Push(new PropertyEnricher("A", 1))) 53 | throw new ApplicationException(); 54 | } 55 | catch (ApplicationException ex) 56 | { 57 | await Task.Delay(1); 58 | 59 | using (LogContext.Push(new ThrowContextEnricher())) 60 | _log.Information(ex, "Unit test"); 61 | } 62 | 63 | Assert.Equal(1, _lastEvent.Properties["A"].LiteralValue()); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Serilog.ThrowContext.Tests/EnrichersOrderTests.cs: -------------------------------------------------------------------------------- 1 | using Serilog.Context; 2 | using Serilog.Core.Enrichers; 3 | using Serilog.Events; 4 | using Serilog.ThrowContext.Tests.Support; 5 | using System; 6 | using Xunit; 7 | 8 | namespace Serilog.ThrowContext.Tests 9 | { 10 | public class EnrichersOrderTests 11 | { 12 | private LogEvent _lastEvent = null; 13 | 14 | [Fact] 15 | public void LogContextThanThrowContext() 16 | { 17 | var log = new LoggerConfiguration() 18 | .Enrich.FromLogContext() 19 | .Enrich.With() 20 | .WriteTo.Sink(new DelegatingSink(e => _lastEvent = e)) 21 | .CreateLogger(); 22 | 23 | DoLogging(log); 24 | 25 | Assert.Equal("outer", _lastEvent.Properties["A"].LiteralValue()); 26 | } 27 | 28 | [Fact] 29 | public void ThrowContextThanLogContext() 30 | { 31 | var log = new LoggerConfiguration() 32 | .Enrich.With() 33 | .Enrich.FromLogContext() 34 | .WriteTo.Sink(new DelegatingSink(e => _lastEvent = e)) 35 | .CreateLogger(); 36 | 37 | DoLogging(log); 38 | 39 | Assert.Equal("inner", _lastEvent.Properties["A"].LiteralValue()); 40 | } 41 | 42 | private static void DoLogging(ILogger log) 43 | { 44 | using (LogContext.Push(new PropertyEnricher("A", "outer"))) 45 | try 46 | { 47 | using (LogContext.Push(new PropertyEnricher("A", "inner"))) 48 | throw new ApplicationException(); 49 | 50 | } 51 | catch (ApplicationException ex) 52 | { 53 | log.Information(ex, "Unit test"); 54 | } 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Serilog.ThrowContext.Tests/FrameworkLoggerTests.cs: -------------------------------------------------------------------------------- 1 | using Serilog.Events; 2 | using Serilog.Extensions.Logging; 3 | using Serilog.ThrowContext.Tests.Support; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Threading.Tasks; 7 | using Xunit; 8 | 9 | namespace Serilog.ThrowContext.Tests 10 | { 11 | public class FrameworkLoggerTests 12 | { 13 | private LogEvent _lastEvent = null; 14 | private readonly Microsoft.Extensions.Logging.ILogger _frameworkLogger; 15 | private readonly Serilog.ILogger _serilogLogger; 16 | 17 | public FrameworkLoggerTests() 18 | { 19 | ThrowContextEnricher.EnsureInitialized(); 20 | 21 | _serilogLogger = new LoggerConfiguration() 22 | .Enrich.FromLogContext() 23 | .Enrich.With() 24 | .WriteTo.Sink(new DelegatingSink(e => _lastEvent = e)) 25 | .CreateLogger(); 26 | 27 | _frameworkLogger = new SerilogLoggerProvider(_serilogLogger) 28 | .CreateLogger(nameof(FrameworkLoggerTests)); 29 | } 30 | 31 | [Fact] 32 | public void BeginScopeConfiguredCorrectly() 33 | { 34 | using (_frameworkLogger.BeginScope(new Dictionary { { "A", 1 } })) 35 | _frameworkLogger.Log(Microsoft.Extensions.Logging.LogLevel.Information, 0, new object(), null, null); 36 | 37 | Assert.Equal(1, _lastEvent.Properties["A"].LiteralValue()); 38 | } 39 | 40 | [Fact] 41 | public void CapturesContextProperty() 42 | { 43 | try 44 | { 45 | using (_frameworkLogger.BeginScope(new Dictionary { { "A", 1 } })) 46 | throw new ApplicationException(); 47 | } 48 | catch (ApplicationException ex) 49 | { 50 | using (Serilog.Context.LogContext.Push(new ThrowContextEnricher())) 51 | _serilogLogger.Information(ex, "Unit test"); 52 | } 53 | 54 | Assert.Equal(1, _lastEvent.Properties["A"].LiteralValue()); 55 | } 56 | 57 | [Fact] 58 | public async Task CapturesContextPropertyAsync() 59 | { 60 | try 61 | { 62 | await Task.Delay(1); 63 | 64 | using (_frameworkLogger.BeginScope(new Dictionary { { "A", 1 } })) 65 | throw new ApplicationException(); 66 | } 67 | catch (ApplicationException ex) 68 | { 69 | await Task.Delay(1); 70 | 71 | using (Serilog.Context.LogContext.Push(new ThrowContextEnricher())) 72 | _serilogLogger.Information(ex, "Unit test"); 73 | } 74 | 75 | Assert.Equal(1, _lastEvent.Properties["A"].LiteralValue()); 76 | } 77 | 78 | [Fact] 79 | public void CapturesContextPropertyWithNestedScopes() 80 | { 81 | try 82 | { 83 | using (_frameworkLogger.BeginScope(new Dictionary { { "A", 1 } })) 84 | using (_frameworkLogger.BeginScope(new Dictionary { { "B", 2 } })) 85 | throw new ApplicationException(); 86 | } 87 | catch (ApplicationException ex) 88 | { 89 | using (Serilog.Context.LogContext.Push(new ThrowContextEnricher())) 90 | _serilogLogger.Information(ex, "Unit test"); 91 | } 92 | 93 | Assert.Equal(1, _lastEvent.Properties["A"].LiteralValue()); 94 | Assert.Equal(2, _lastEvent.Properties["B"].LiteralValue()); 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /Serilog.ThrowContext.Tests/PreventStackOverflowTests.cs: -------------------------------------------------------------------------------- 1 | using Serilog.Context; 2 | using Serilog.Core.Enrichers; 3 | using Serilog.Events; 4 | using Serilog.ThrowContext.Tests.Support; 5 | using System; 6 | using Xunit; 7 | 8 | namespace Serilog.ThrowContext.Tests 9 | { 10 | public class PreventStackOverflowTests 11 | { 12 | private LogEvent _lastEvent = null; 13 | 14 | [Fact] 15 | public void ThrowInEnricherScope() 16 | { 17 | var log = new LoggerConfiguration() 18 | .Enrich.FromLogContext() 19 | .WriteTo.Sink(new DelegatingSink(e => _lastEvent = e)) 20 | .CreateLogger(); 21 | 22 | using (LogContext.Push(new ThrowContextEnricher())) 23 | { 24 | try 25 | { 26 | using (LogContext.PushProperty("A", 1)) 27 | throw new ApplicationException(); 28 | 29 | } 30 | catch (ApplicationException ex) 31 | { 32 | log.Information(ex, "Unit test"); 33 | } 34 | } 35 | 36 | Assert.Equal(1, _lastEvent.Properties["A"].LiteralValue()); 37 | } 38 | 39 | [Fact] 40 | public void ThrowInEnricherDoubleScope() 41 | { 42 | var log = new LoggerConfiguration() 43 | .Enrich.FromLogContext() 44 | .WriteTo.Sink(new DelegatingSink(e => _lastEvent = e)) 45 | .CreateLogger(); 46 | 47 | using (LogContext.Push(new ThrowContextEnricher())) 48 | using (LogContext.Push(new ThrowContextEnricher())) 49 | { 50 | try 51 | { 52 | using (LogContext.PushProperty("A", 1)) 53 | throw new ApplicationException(); 54 | 55 | } 56 | catch (ApplicationException ex) 57 | { 58 | log.Information(ex, "Unit test"); 59 | } 60 | } 61 | 62 | Assert.Equal(1, _lastEvent.Properties["A"].LiteralValue()); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Serilog.ThrowContext.Tests/ReThrowTests.cs: -------------------------------------------------------------------------------- 1 | using Serilog.Context; 2 | using Serilog.Core.Enrichers; 3 | using Serilog.Events; 4 | using Serilog.ThrowContext.Tests.Support; 5 | using System; 6 | using System.Threading.Tasks; 7 | using Xunit; 8 | 9 | namespace Serilog.ThrowContext.Tests 10 | { 11 | public class ReThrowTests 12 | { 13 | private LogEvent _lastEvent = null; 14 | private readonly ILogger _log; 15 | 16 | public ReThrowTests() 17 | { 18 | ThrowContextEnricher.EnsureInitialized(); 19 | 20 | _log = new LoggerConfiguration() 21 | .Enrich.FromLogContext() 22 | .WriteTo.Sink(new DelegatingSink(e => _lastEvent = e)) 23 | .CreateLogger(); 24 | } 25 | 26 | [Fact] 27 | public void ReThrowCapturesProperty() 28 | { 29 | try 30 | { 31 | try 32 | { 33 | using (LogContext.Push(new PropertyEnricher("A", 1))) 34 | throw new ApplicationException(); 35 | } 36 | catch 37 | { 38 | using (LogContext.Push(new PropertyEnricher("B", 2))) 39 | throw; 40 | } 41 | } 42 | catch (ApplicationException ex) 43 | { 44 | using (LogContext.Push(new ThrowContextEnricher())) 45 | _log.Information(ex, "Unit test"); 46 | } 47 | 48 | Assert.Equal(1, _lastEvent.Properties["A"].LiteralValue()); 49 | Assert.Equal(2, _lastEvent.Properties["B"].LiteralValue()); 50 | } 51 | 52 | [Fact] 53 | public async Task ReThrowCapturesPropertyAsync() 54 | { 55 | try 56 | { 57 | try 58 | { 59 | await Task.Delay(1); 60 | 61 | using (LogContext.Push(new PropertyEnricher("A", 1))) 62 | throw new ApplicationException(); 63 | } 64 | catch 65 | { 66 | await Task.Delay(1); 67 | 68 | using (LogContext.Push(new PropertyEnricher("B", 2))) 69 | throw; 70 | } 71 | } 72 | catch (ApplicationException ex) 73 | { 74 | await Task.Delay(1); 75 | 76 | using (LogContext.Push(new ThrowContextEnricher())) 77 | _log.Information(ex, "Unit test"); 78 | } 79 | 80 | Assert.Equal(1, _lastEvent.Properties["A"].LiteralValue()); 81 | Assert.Equal(2, _lastEvent.Properties["B"].LiteralValue()); 82 | } 83 | 84 | [Theory] 85 | [InlineData(true)] 86 | [InlineData(false)] 87 | public void ReThrowDoesNotOverrideOriginalProperty(bool preserveStack) 88 | { 89 | try 90 | { 91 | try 92 | { 93 | using (LogContext.Push(new PropertyEnricher("A", 1))) 94 | throw new ApplicationException(); 95 | } 96 | catch (Exception ex) 97 | { 98 | using (LogContext.Push(new PropertyEnricher("A", 2))) 99 | if (preserveStack) 100 | throw; 101 | else 102 | throw ex; 103 | } 104 | } 105 | catch (ApplicationException ex) 106 | { 107 | using (LogContext.Push(new ThrowContextEnricher())) 108 | _log.Information(ex, "Unit test"); 109 | } 110 | 111 | Assert.Equal(1, _lastEvent.Properties["A"].LiteralValue()); 112 | } 113 | 114 | [Fact] 115 | public void ReThrowDoesNotCaptureOriginalPropertyForNewException() 116 | { 117 | try 118 | { 119 | try 120 | { 121 | using (LogContext.Push(new PropertyEnricher("A", 1))) 122 | throw new FormatException(); 123 | } 124 | catch 125 | { 126 | using (LogContext.Push(new PropertyEnricher("B", 2))) 127 | throw new ApplicationException(); 128 | } 129 | } 130 | catch (ApplicationException ex) 131 | { 132 | using (LogContext.Push(new ThrowContextEnricher())) 133 | _log.Information(ex, "Unit test"); 134 | } 135 | 136 | Assert.False(_lastEvent.Properties.ContainsKey("A")); 137 | Assert.Equal(2, _lastEvent.Properties["B"].LiteralValue()); 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /Serilog.ThrowContext.Tests/Serilog.ThrowContext.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp3.1 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Serilog.ThrowContext.Tests/Support/DelegatingSink.cs: -------------------------------------------------------------------------------- 1 | using Serilog.Core; 2 | using Serilog.Events; 3 | using System; 4 | 5 | namespace Serilog.ThrowContext.Tests.Support 6 | { 7 | class DelegatingSink : ILogEventSink 8 | { 9 | readonly Action _write; 10 | 11 | public DelegatingSink(Action write) 12 | { 13 | _write = write ?? throw new ArgumentNullException(nameof(write)); 14 | } 15 | 16 | public void Emit(LogEvent logEvent) 17 | { 18 | _write(logEvent); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Serilog.ThrowContext.Tests/Support/LogEventPropertyValueExtensions.cs: -------------------------------------------------------------------------------- 1 | using Serilog.Events; 2 | 3 | namespace Serilog.ThrowContext.Tests.Support 4 | { 5 | public static class LogEventPropertyValueExtensions 6 | { 7 | public static object LiteralValue(this LogEventPropertyValue @this) 8 | { 9 | return ((ScalarValue)@this).Value; 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Serilog.ThrowContext.Tests/WrapTests.cs: -------------------------------------------------------------------------------- 1 | using Serilog.Context; 2 | using Serilog.Core.Enrichers; 3 | using Serilog.Events; 4 | using Serilog.ThrowContext.Tests.Support; 5 | using System; 6 | using System.Threading.Tasks; 7 | using Xunit; 8 | 9 | namespace Serilog.ThrowContext.Tests 10 | { 11 | public class WrapTests 12 | { 13 | private LogEvent _lastEvent = null; 14 | private readonly ILogger _log; 15 | 16 | public WrapTests() 17 | { 18 | ThrowContextEnricher.EnsureInitialized(); 19 | 20 | _log = new LoggerConfiguration() 21 | .Enrich.FromLogContext() 22 | .WriteTo.Sink(new DelegatingSink(e => _lastEvent = e)) 23 | .CreateLogger(); 24 | } 25 | 26 | [Fact] 27 | public void WrapIncludesOriginalContext() 28 | { 29 | try 30 | { 31 | try 32 | { 33 | using (LogContext.Push(new PropertyEnricher("A", 1))) 34 | throw new FormatException(); 35 | } 36 | catch(Exception ex) 37 | { 38 | using (LogContext.Push(new PropertyEnricher("B", 2))) 39 | throw new ApplicationException("Wrapper", ex); 40 | } 41 | } 42 | catch (ApplicationException ex) 43 | { 44 | using (LogContext.Push(new ThrowContextEnricher())) 45 | _log.Information(ex, "Unit test"); 46 | } 47 | 48 | Assert.Equal(1, _lastEvent.Properties["A"].LiteralValue()); 49 | Assert.Equal(2, _lastEvent.Properties["B"].LiteralValue()); 50 | } 51 | 52 | [Fact] 53 | public async Task WrapIncludesOriginalContextAsync() 54 | { 55 | try 56 | { 57 | try 58 | { 59 | await Task.Delay(1); 60 | 61 | using (LogContext.Push(new PropertyEnricher("A", 1))) 62 | throw new FormatException(); 63 | } 64 | catch (Exception ex) 65 | { 66 | await Task.Delay(1); 67 | 68 | using (LogContext.Push(new PropertyEnricher("B", 2))) 69 | throw new ApplicationException("Wrapper", ex); 70 | } 71 | } 72 | catch (ApplicationException ex) 73 | { 74 | await Task.Delay(1); 75 | 76 | using (LogContext.Push(new ThrowContextEnricher())) 77 | _log.Information(ex, "Unit test"); 78 | } 79 | 80 | Assert.Equal(1, _lastEvent.Properties["A"].LiteralValue()); 81 | Assert.Equal(2, _lastEvent.Properties["B"].LiteralValue()); 82 | } 83 | 84 | [Fact] 85 | public void WrapOverridesOriginalProperty() 86 | { 87 | try 88 | { 89 | try 90 | { 91 | using (LogContext.Push(new PropertyEnricher("A", 1))) 92 | throw new FormatException(); 93 | } 94 | catch (Exception ex) 95 | { 96 | using (LogContext.Push(new PropertyEnricher("A", 2))) 97 | throw new ApplicationException("Wrapper", ex); 98 | } 99 | } 100 | catch (ApplicationException ex) 101 | { 102 | using (LogContext.Push(new ThrowContextEnricher())) 103 | _log.Information(ex, "Unit test"); 104 | } 105 | 106 | Assert.Equal(2, _lastEvent.Properties["A"].LiteralValue()); 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /Serilog.ThrowContext.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29519.181 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.ThrowContext", "Serilog.ThrowContext\Serilog.ThrowContext.csproj", "{42BF7183-AAC3-4FAC-BDC8-0D3FC8F70A69}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleSample", "Samples\ConsoleSample\ConsoleSample.csproj", "{166E1779-3E23-4FE6-A940-525A89F89D3F}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.ThrowContext.Tests", "Serilog.ThrowContext.Tests\Serilog.ThrowContext.Tests.csproj", "{16AA1E39-4BEE-4335-99DB-C808CF8103C8}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{1EFD4BDC-FDBF-4062-AE7D-013E345C429F}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNetCoreSample", "Samples\AspNetCoreSample\AspNetCoreSample.csproj", "{424B8CF2-740B-48B2-9531-F5CC7F108F29}" 15 | ProjectSection(ProjectDependencies) = postProject 16 | {42BF7183-AAC3-4FAC-BDC8-0D3FC8F70A69} = {42BF7183-AAC3-4FAC-BDC8-0D3FC8F70A69} 17 | EndProjectSection 18 | EndProject 19 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FileConfigurationSample", "Samples\FileConfigurationSample\FileConfigurationSample.csproj", "{40934272-F147-499C-B953-55D0288A4A5E}" 20 | EndProject 21 | Global 22 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 23 | Debug|Any CPU = Debug|Any CPU 24 | Release|Any CPU = Release|Any CPU 25 | EndGlobalSection 26 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 27 | {42BF7183-AAC3-4FAC-BDC8-0D3FC8F70A69}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {42BF7183-AAC3-4FAC-BDC8-0D3FC8F70A69}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {42BF7183-AAC3-4FAC-BDC8-0D3FC8F70A69}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {42BF7183-AAC3-4FAC-BDC8-0D3FC8F70A69}.Release|Any CPU.Build.0 = Release|Any CPU 31 | {166E1779-3E23-4FE6-A940-525A89F89D3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 32 | {166E1779-3E23-4FE6-A940-525A89F89D3F}.Debug|Any CPU.Build.0 = Debug|Any CPU 33 | {166E1779-3E23-4FE6-A940-525A89F89D3F}.Release|Any CPU.ActiveCfg = Release|Any CPU 34 | {166E1779-3E23-4FE6-A940-525A89F89D3F}.Release|Any CPU.Build.0 = Release|Any CPU 35 | {16AA1E39-4BEE-4335-99DB-C808CF8103C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 36 | {16AA1E39-4BEE-4335-99DB-C808CF8103C8}.Debug|Any CPU.Build.0 = Debug|Any CPU 37 | {16AA1E39-4BEE-4335-99DB-C808CF8103C8}.Release|Any CPU.ActiveCfg = Release|Any CPU 38 | {16AA1E39-4BEE-4335-99DB-C808CF8103C8}.Release|Any CPU.Build.0 = Release|Any CPU 39 | {424B8CF2-740B-48B2-9531-F5CC7F108F29}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 40 | {424B8CF2-740B-48B2-9531-F5CC7F108F29}.Debug|Any CPU.Build.0 = Debug|Any CPU 41 | {424B8CF2-740B-48B2-9531-F5CC7F108F29}.Release|Any CPU.ActiveCfg = Release|Any CPU 42 | {424B8CF2-740B-48B2-9531-F5CC7F108F29}.Release|Any CPU.Build.0 = Release|Any CPU 43 | {40934272-F147-499C-B953-55D0288A4A5E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 44 | {40934272-F147-499C-B953-55D0288A4A5E}.Debug|Any CPU.Build.0 = Debug|Any CPU 45 | {40934272-F147-499C-B953-55D0288A4A5E}.Release|Any CPU.ActiveCfg = Release|Any CPU 46 | {40934272-F147-499C-B953-55D0288A4A5E}.Release|Any CPU.Build.0 = Release|Any CPU 47 | EndGlobalSection 48 | GlobalSection(SolutionProperties) = preSolution 49 | HideSolutionNode = FALSE 50 | EndGlobalSection 51 | GlobalSection(NestedProjects) = preSolution 52 | {166E1779-3E23-4FE6-A940-525A89F89D3F} = {1EFD4BDC-FDBF-4062-AE7D-013E345C429F} 53 | {424B8CF2-740B-48B2-9531-F5CC7F108F29} = {1EFD4BDC-FDBF-4062-AE7D-013E345C429F} 54 | {40934272-F147-499C-B953-55D0288A4A5E} = {1EFD4BDC-FDBF-4062-AE7D-013E345C429F} 55 | EndGlobalSection 56 | GlobalSection(ExtensibilityGlobals) = postSolution 57 | SolutionGuid = {74532A8B-7EFC-454B-85D5-738015E800B6} 58 | EndGlobalSection 59 | EndGlobal 60 | -------------------------------------------------------------------------------- /Serilog.ThrowContext/Serilog.ThrowContext.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0 5 | true 6 | 0.1.2 7 | Throw context enricher for Serilog 8 | 9 | Tolyandre 10 | LICENSE 11 | 12 | https://github.com/Tolyandre/serilog-throw-context-enricher 13 | Captures LogContext of a thrown exception to enrich logs when the exception is eventually logged. 14 | Serilog Exception LogContext 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | True 24 | 25 | 26 | 27 | 28 | 29 | 30 | README.md 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Serilog.ThrowContext/ThrowContextEnricher.cs: -------------------------------------------------------------------------------- 1 | using Serilog.Context; 2 | using Serilog.Core; 3 | using Serilog.Events; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Runtime.CompilerServices; 7 | using System.Runtime.ExceptionServices; 8 | using System.Threading; 9 | 10 | namespace Serilog.ThrowContext 11 | { 12 | public class ThrowContextEnricher : ILogEventEnricher 13 | { 14 | static readonly ConditionalWeakTable> ConditionalWeakTable = 15 | new ConditionalWeakTable>(); 16 | 17 | static readonly ConditionalWeakTable EnrichedLogEvents = new ConditionalWeakTable(); 18 | 19 | static ThrowContextEnricher() 20 | { 21 | AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException; 22 | } 23 | 24 | /// 25 | /// Ensures that capturing of thrown exception log context is initialized. 26 | /// 27 | /// This method should be invoked only if ThrowContextEnricher is not referenced before the actual exception may occur. 28 | /// 29 | public static void EnsureInitialized() 30 | { 31 | // just triggers static ctor 32 | } 33 | 34 | private static void CurrentDomain_FirstChanceException(object sender, FirstChanceExceptionEventArgs e) 35 | { 36 | var exceptionContexts = ConditionalWeakTable.GetOrCreateValue(e.Exception); 37 | exceptionContexts.Add((LogContext.Clone(), ExecutionContext.Capture())); 38 | } 39 | 40 | public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) 41 | { 42 | if (logEvent.Exception == null) 43 | return; 44 | 45 | // prevent recursion if an exception is thrown inside our enricher scope 46 | bool alreadyEnriched = true; 47 | EnrichedLogEvents.GetValue(logEvent, _ => 48 | { 49 | alreadyEnriched = false; 50 | return null; 51 | }); 52 | 53 | if (alreadyEnriched) 54 | return; 55 | 56 | EnrichInternal(logEvent, propertyFactory); 57 | } 58 | 59 | private static void EnrichInternal(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) 60 | { 61 | Exception exception = logEvent.Exception; 62 | 63 | while (exception != null) 64 | { 65 | if (ConditionalWeakTable.TryGetValue(exception, out List<(ILogEventEnricher EnricherContext, ExecutionContext ExecutionContext)> contexts)) 66 | { 67 | foreach (var context in contexts) 68 | { 69 | // ExecutionContext is only needed to support framework's logger BeginScope (Serilog.Extensions.Logging) 70 | ExecutionContext.Run(context.ExecutionContext, _ => 71 | { 72 | context.EnricherContext.Enrich(logEvent, propertyFactory); 73 | }, null); 74 | } 75 | } 76 | 77 | exception = exception.InnerException; 78 | } 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | # ASP.NET Core (.NET Framework) 2 | # Build and test ASP.NET Core projects targeting the full .NET Framework. 3 | # Add steps that publish symbols, save build artifacts, and more: 4 | # https://docs.microsoft.com/azure/devops/pipelines/languages/dotnet-core 5 | 6 | trigger: 7 | - master 8 | 9 | pool: 10 | vmImage: 'windows-latest' 11 | 12 | variables: 13 | solution: '**/*.sln' 14 | buildPlatform: 'Any CPU' 15 | buildConfiguration: 'Release' 16 | 17 | steps: 18 | - task: NuGetToolInstaller@1 19 | 20 | - task: NuGetCommand@2 21 | inputs: 22 | restoreSolution: '$(solution)' 23 | 24 | - task: VSBuild@1 25 | inputs: 26 | solution: '$(solution)' 27 | msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:DesktopBuildPackageLocation="$(build.artifactStagingDirectory)\WebApp.zip" /p:DeployIisAppPath="Default Web Site"' 28 | platform: '$(buildPlatform)' 29 | configuration: '$(buildConfiguration)' 30 | 31 | - task: DotNetCoreCLI@2 32 | inputs: 33 | command: 'test' 34 | projects: '**/*Tests/*.csproj' 35 | arguments: '--configuration $(buildConfiguration)' 36 | testRunTitle: 'Run tests' --------------------------------------------------------------------------------