├── .gitattributes ├── .gitignore ├── Build.ps1 ├── LICENSE ├── README.md ├── appveyor.yml ├── asset ├── SerilogTimings.snk ├── serilog-timings.png └── serilog-timings.svg ├── global.json ├── sample └── Example │ ├── Example.csproj │ └── Program.cs ├── serilog-timings.sln ├── serilog-timings.sln.DotSettings ├── src └── SerilogTimings │ ├── CompletionBehaviour.cs │ ├── Configuration │ └── LevelledOperation.cs │ ├── Extensions │ └── LoggerOperationExtensions.cs │ ├── Operation.cs │ ├── OperationExtensions.cs │ └── SerilogTimings.csproj └── test └── SerilogTimings.Tests ├── OperationEnrichmentTests.cs ├── OperationTests.cs ├── SerilogTimings.Tests.csproj └── Support ├── CollectingLogger.cs └── CollectionSink.cs /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | 24 | # Visual Studio 2015 cache/options directory 25 | .vs/ 26 | # Uncomment if you have tasks that create the project's static files in wwwroot 27 | #wwwroot/ 28 | 29 | # MSTest test Results 30 | [Tt]est[Rr]esult*/ 31 | [Bb]uild[Ll]og.* 32 | 33 | # NUNIT 34 | *.VisualState.xml 35 | TestResult.xml 36 | 37 | # Build Results of an ATL Project 38 | [Dd]ebugPS/ 39 | [Rr]eleasePS/ 40 | dlldata.c 41 | 42 | # DNX 43 | project.lock.json 44 | artifacts/ 45 | 46 | *_i.c 47 | *_p.c 48 | *_i.h 49 | *.ilk 50 | *.meta 51 | *.obj 52 | *.pch 53 | *.pdb 54 | *.pgc 55 | *.pgd 56 | *.rsp 57 | *.sbr 58 | *.tlb 59 | *.tli 60 | *.tlh 61 | *.tmp 62 | *.tmp_proj 63 | *.log 64 | *.vspscc 65 | *.vssscc 66 | .builds 67 | *.pidb 68 | *.svclog 69 | *.scc 70 | 71 | # Chutzpah Test files 72 | _Chutzpah* 73 | 74 | # Visual C++ cache files 75 | ipch/ 76 | *.aps 77 | *.ncb 78 | *.opendb 79 | *.opensdf 80 | *.sdf 81 | *.cachefile 82 | 83 | # Visual Studio profiler 84 | *.psess 85 | *.vsp 86 | *.vspx 87 | *.sap 88 | 89 | # TFS 2012 Local Workspace 90 | $tf/ 91 | 92 | # Guidance Automation Toolkit 93 | *.gpState 94 | 95 | # ReSharper is a .NET coding add-in 96 | _ReSharper*/ 97 | *.[Rr]e[Ss]harper 98 | *.DotSettings.user 99 | 100 | # JustCode is a .NET coding add-in 101 | .JustCode 102 | 103 | # TeamCity is a build add-in 104 | _TeamCity* 105 | 106 | # DotCover is a Code Coverage Tool 107 | *.dotCover 108 | 109 | # NCrunch 110 | _NCrunch_* 111 | .*crunch*.local.xml 112 | nCrunchTemp_* 113 | 114 | # MightyMoose 115 | *.mm.* 116 | AutoTest.Net/ 117 | 118 | # Web workbench (sass) 119 | .sass-cache/ 120 | 121 | # Installshield output folder 122 | [Ee]xpress/ 123 | 124 | # DocProject is a documentation generator add-in 125 | DocProject/buildhelp/ 126 | DocProject/Help/*.HxT 127 | DocProject/Help/*.HxC 128 | DocProject/Help/*.hhc 129 | DocProject/Help/*.hhk 130 | DocProject/Help/*.hhp 131 | DocProject/Help/Html2 132 | DocProject/Help/html 133 | 134 | # Click-Once directory 135 | publish/ 136 | 137 | # Publish Web Output 138 | *.[Pp]ublish.xml 139 | *.azurePubxml 140 | # TODO: Comment the next line if you want to checkin your web deploy settings 141 | # but database connection strings (with potential passwords) will be unencrypted 142 | *.pubxml 143 | *.publishproj 144 | 145 | # NuGet Packages 146 | *.nupkg 147 | # The packages folder can be ignored because of Package Restore 148 | **/packages/* 149 | # except build/, which is used as an MSBuild target. 150 | !**/packages/build/ 151 | # Uncomment if necessary however generally it will be regenerated when needed 152 | #!**/packages/repositories.config 153 | # NuGet v3's project.json files produces more ignoreable files 154 | *.nuget.props 155 | *.nuget.targets 156 | 157 | # Microsoft Azure Build Output 158 | csx/ 159 | *.build.csdef 160 | 161 | # Microsoft Azure Emulator 162 | ecf/ 163 | rcf/ 164 | 165 | # Microsoft Azure ApplicationInsights config file 166 | ApplicationInsights.config 167 | 168 | # Windows Store app package directory 169 | AppPackages/ 170 | BundleArtifacts/ 171 | 172 | # Visual Studio cache files 173 | # files ending in .cache can be ignored 174 | *.[Cc]ache 175 | # but keep track of directories ending in .cache 176 | !*.[Cc]ache/ 177 | 178 | # Others 179 | ClientBin/ 180 | ~$* 181 | *~ 182 | *.dbmdl 183 | *.dbproj.schemaview 184 | *.pfx 185 | *.publishsettings 186 | node_modules/ 187 | orleans.codegen.cs 188 | 189 | # RIA/Silverlight projects 190 | Generated_Code/ 191 | 192 | # Backup & report files from converting an old project file 193 | # to a newer Visual Studio version. Backup files are not needed, 194 | # because we have git ;-) 195 | _UpgradeReport_Files/ 196 | Backup*/ 197 | UpgradeLog*.XML 198 | UpgradeLog*.htm 199 | 200 | # SQL Server files 201 | *.mdf 202 | *.ldf 203 | 204 | # Business Intelligence projects 205 | *.rdl.data 206 | *.bim.layout 207 | *.bim_*.settings 208 | 209 | # Microsoft Fakes 210 | FakesAssemblies/ 211 | 212 | # GhostDoc plugin setting file 213 | *.GhostDoc.xml 214 | 215 | # Node.js Tools for Visual Studio 216 | .ntvs_analysis.dat 217 | 218 | # Visual Studio 6 build log 219 | *.plg 220 | 221 | # Visual Studio 6 workspace options file 222 | *.opt 223 | 224 | # Visual Studio LightSwitch build output 225 | **/*.HTMLClient/GeneratedArtifacts 226 | **/*.DesktopClient/GeneratedArtifacts 227 | **/*.DesktopClient/ModelManifest.xml 228 | **/*.Server/GeneratedArtifacts 229 | **/*.Server/ModelManifest.xml 230 | _Pvt_Extensions 231 | 232 | # Paket dependency manager 233 | .paket/paket.exe 234 | 235 | # FAKE - F# Make 236 | .fake/ 237 | 238 | .idea/ -------------------------------------------------------------------------------- /Build.ps1: -------------------------------------------------------------------------------- 1 | Push-Location $PSScriptRoot 2 | 3 | if(Test-Path .\artifacts) { Remove-Item .\artifacts -Force -Recurse } 4 | 5 | & dotnet restore --no-cache 6 | 7 | $branch = @{ $true = $env:APPVEYOR_REPO_BRANCH; $false = $(git symbolic-ref --short -q HEAD) }[$env:APPVEYOR_REPO_BRANCH -ne $NULL]; 8 | $revision = @{ $true = "{0:00000}" -f [convert]::ToInt32("0" + $env:APPVEYOR_BUILD_NUMBER, 10); $false = "local" }[$env:APPVEYOR_BUILD_NUMBER -ne $NULL]; 9 | $suffix = @{ $true = ""; $false = "$branch-$revision"}[$branch -eq "main" -and $revision -ne "local"] 10 | 11 | foreach ($src in ls src/Serilog*) { 12 | Push-Location $src 13 | 14 | if ($suffix) { 15 | & dotnet pack -c Release -o ..\..\.\artifacts --version-suffix=$suffix 16 | } else { 17 | & dotnet pack -c Release -o ..\..\.\artifacts 18 | } 19 | if($LASTEXITCODE -ne 0) { exit 1 } 20 | 21 | Pop-Location 22 | } 23 | 24 | foreach ($test in ls test/Serilog*.Tests) { 25 | Push-Location $test 26 | 27 | & dotnet test -c Release 28 | if($LASTEXITCODE -ne 0) { exit 2 } 29 | 30 | Pop-Location 31 | } 32 | 33 | Pop-Location 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Serilog Timings [![Build status](https://ci.appveyor.com/api/projects/status/rgluby771a4rkwul?svg=true)](https://ci.appveyor.com/project/NicholasBlumhardt/serilog-timings) [![NuGet Release](https://img.shields.io/nuget/v/SerilogTimings.svg)](https://nuget.org/packages/serilogtimings) 2 | 3 | Serilog's support for structured data makes it a great way to collect timing information. It's easy 4 | to get started with in development, because the timings are printed to the same output as other 5 | log messages (the console, files, etc.) so a metrics server doesn't have to be available all the time. 6 | 7 | Serilog Timings is built with some specific requirements in mind: 8 | 9 | * One operation produces exactly one log event (events are raised at the completion of an operation) 10 | * Natural and fully-templated messages 11 | * Events for a single operation have a single event type, across both success and failure cases (only the logging level and `Outcome` properties change) 12 | 13 | This keeps noise in the log to a minimum, and makes it easy to extract and manipulate timing 14 | information on a per-operation basis. 15 | 16 | > [!IMPORTANT] 17 | > SerilogTimings is maintained, but "done". Its simple, lightweight, portable, opinionated API is considered a feature, and it's unlikely any further changes will 18 | > be made. For integration with .NET's tracing system, including out-of-the-box support for ASP.NET Core, `HttpClient`, and `SqlClient` tracing, check out 19 | > [SerilogTracing](https://github.com/serilog-tracing/serilog-tracing), the logical successor to SerilogTimings, influenced strongly by the SerilogTimings API. Read 20 | > [this migration guide](https://nblumhardt.com/2024/03/from-serilog-timings-to-tracing/) if you're interested in porting an existing codebase to the new library. 21 | 22 | ### Installation 23 | 24 | The library is published as _SerilogTimings_ on NuGet. 25 | 26 | ```powershell 27 | Install-Package SerilogTimings -DependencyVersion Highest 28 | ``` 29 | 30 | The package works on all currently-supported .NET versions. 31 | 32 | ### Getting started 33 | 34 | Before your timings will go anywhere, [install and configure Serilog](http://serilog.net). 35 | 36 | Types are in the `SerilogTimings` namespace. 37 | 38 | ```csharp 39 | using SerilogTimings; 40 | ``` 41 | 42 | The simplest use case is to time an operation, without explicitly recording success/failure: 43 | 44 | ```csharp 45 | using (Operation.Time("Submitting payment for {OrderId}", order.Id)) 46 | { 47 | // Timed block of code goes here 48 | } 49 | ``` 50 | 51 | At the completion of the `using` block, a message will be written to the log like: 52 | 53 | ``` 54 | [INF] Submitting payment for order-12345 completed in 456.7 ms 55 | ``` 56 | 57 | The operation description passed to `Time()` is a message template; the event written to the log 58 | extends it with `" {Outcome} in {Elapsed} ms"`. 59 | 60 | * All events raised by SerilogTimings carry an `Elapsed` property in milliseconds 61 | * `Outcome` will always be `"completed"` when the `Time()` method is used 62 | 63 | All of the properties from the description, plus the outcome and timing, will be recorded as 64 | first-class properties on the log event. 65 | 66 | Operations that can either _succeed or fail_, or _that produce a result_, can be created with 67 | `Operation.Begin()`: 68 | 69 | ```csharp 70 | using (var op = Operation.Begin("Retrieving orders for {CustomerId}", customer.Id)) 71 | { 72 | // Timed block of code goes here 73 | 74 | op.Complete(); 75 | } 76 | ``` 77 | 78 | Using `op.Complete()` will produce the same kind of result as in the first example: 79 | 80 | ``` 81 | [INF] Retrieving orders for customer-67890 completed in 7.8 ms 82 | ``` 83 | 84 | Additional methods on `Operation` allow more detailed results to be captured: 85 | 86 | ```csharp 87 | op.Complete("Rows", orders.Rows.Length); 88 | ``` 89 | 90 | This will not change the text of the log message, but the property `Rows` will be attached to it for 91 | later filtering and analysis. 92 | 93 | If the operation is not completed by calling `Complete()`, it is assumed to have failed and a 94 | warning-level event will be written to the log instead: 95 | 96 | ``` 97 | [WRN] Retrieving orders for customer-67890 abandoned in 1234.5 ms 98 | ``` 99 | 100 | In this case the `Outcome` property will be `"abandoned"`. 101 | 102 | To suppress this message, for example when an operation turns out to be inapplicable, use 103 | `op.Cancel()`. Once `Cancel()` has been called, no event will be written by the operation on 104 | either completion or abandonment. 105 | 106 | ### Use with `ILogger` 107 | 108 | If a contextual `ILogger` is available, the extensions methods `TimeOperation()` and 109 | `BeginOperation()` can be used to write operation timings through it: 110 | 111 | ```csharp 112 | using (logger.TimeOperation("Submitting payment for {OrderId}", order.Id)) 113 | { 114 | // Timed block of code goes here 115 | } 116 | ``` 117 | 118 | 119 | If you need to the the log level too, the `OperationAt` extension method is useful: 120 | ```csharp 121 | using (requestLogger.OperationAt(LogEventLevel.Debug).Time("Fetching")) { 122 | { 123 | // Timed block of code goes here 124 | } 125 | 126 | ``` 127 | 128 | These otherwise behave identically to `Operation.Time()` and `Operation.Begin()`. 129 | 130 | ### `LogContext` support 131 | 132 | If your application enables the Serilog `LogContext` feature using `Enrich.FromLogContext()` on 133 | the `LoggerConfiguration`, Serilog Timings will add an `OperationId` property to all events inside 134 | timing blocks automatically. 135 | 136 | This is **highly recommended**, because it makes it much easier to trace from a timing result back 137 | through the operation that raised it. 138 | 139 | ### Levelling 140 | 141 | Timings are most useful in production, so timing events are recorded at the `Information` level and 142 | higher, which should generally be collected all the time. 143 | 144 | If you truly need `Verbose`- or `Debug`-level timings, you can trigger them with `Operation.At()` or 145 | the `OperationAt()` extension method on `ILogger`: 146 | 147 | ```csharp 148 | using (Operation.At(LogEventLevel.Debug).Time("Preparing zip archive")) 149 | { 150 | // ... 151 | ``` 152 | 153 | When a level is specified, both completion and abandonment events will use it. To configure a different 154 | abandonment level, pass the second optional parameter to the `At()` method. 155 | 156 | ### Caveats 157 | 158 | One important usage note: because the event is not written until the completion of the `using` block 159 | (or call to `Complete()`), arguments to `Begin()` or `Time()` are not captured until then; don't 160 | pass parameters to these methods that mutate during the operation. 161 | 162 | ### How does this relate to SerilogMetrics? 163 | 164 | [SerilogMetrics](https://github.com/serilog-metrics/serilog-metrics) is a mature metrics solution 165 | for Serilog that includes timings as well as counters, gauges and more. Serilog Timings is an 166 | alternative implementation of timings only, designed with some different stylistic preferences and 167 | goals. You should definitely check out SerilogMetrics as well, to see if it's more to your tastes! 168 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | version: '{build}' 2 | skip_tags: true 3 | image: Visual Studio 2022 4 | build_script: 5 | - ps: ./Build.ps1 6 | test: off 7 | artifacts: 8 | - path: artifacts/SerilogTimings.*.nupkg 9 | deploy: 10 | - provider: NuGet 11 | api_key: 12 | secure: PNt/eGIH1e+7YX5jjXKmBDz4QKZ6RvpoIkTz1SYzJJHPYBUnzGY0EiBH9ylG19is 13 | skip_symbols: true 14 | on: 15 | branch: /^(dev|main)$/ 16 | -------------------------------------------------------------------------------- /asset/SerilogTimings.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nblumhardt/serilog-timings/d44323c5e96c70cbc5b8f22aff47f9eb3469f484/asset/SerilogTimings.snk -------------------------------------------------------------------------------- /asset/serilog-timings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nblumhardt/serilog-timings/d44323c5e96c70cbc5b8f22aff47f9eb3469f484/asset/serilog-timings.png -------------------------------------------------------------------------------- /asset/serilog-timings.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 19 | 21 | 23 | 27 | 31 | 32 | 34 | 38 | 42 | 43 | 45 | 49 | 53 | 54 | 64 | 74 | 75 | 93 | 95 | 96 | 98 | image/svg+xml 99 | 101 | 102 | 103 | 104 | 105 | 109 | 121 | 128 | 138 | 148 | 158 | 168 | 169 | 170 | -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "version": "6.0.101", 4 | "rollForward": "latestMinor" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /sample/Example/Example.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | Exe 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /sample/Example/Program.cs: -------------------------------------------------------------------------------- 1 | using Serilog; 2 | using SerilogTimings; 3 | 4 | Log.Logger = new LoggerConfiguration() 5 | .Enrich.FromLogContext() 6 | .WriteTo.Console() 7 | .WriteTo.Seq("http://localhost:5341") 8 | .CreateLogger(); 9 | 10 | try 11 | { 12 | Log.Information("Hello, world!"); 13 | 14 | const int count = 10000; 15 | using (var op = Operation.Begin("Adding {Count} successive integers", count)) 16 | { 17 | var sum = Enumerable.Range(0, count).Sum(); 18 | Log.Information("This event is tagged with an operation id"); 19 | 20 | op.Complete("Sum", sum); 21 | } 22 | 23 | Log.Information("Goodbye!"); 24 | return 0; 25 | } 26 | catch (Exception e) 27 | { 28 | Log.Error(e, "Unhandled exception"); 29 | return 1; 30 | } 31 | finally 32 | { 33 | Log.CloseAndFlush(); 34 | } 35 | 36 | -------------------------------------------------------------------------------- /serilog-timings.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.28010.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E12C42C0-7235-47D6-8D63-2EF82A2365B0}" 7 | ProjectSection(SolutionItems) = preProject 8 | appveyor.yml = appveyor.yml 9 | Build.ps1 = Build.ps1 10 | global.json = global.json 11 | README.md = README.md 12 | .gitattributes = .gitattributes 13 | .gitignore = .gitignore 14 | LICENSE = LICENSE 15 | EndProjectSection 16 | EndProject 17 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SerilogTimings", "src\SerilogTimings\SerilogTimings.csproj", "{3B709371-7B4D-41D5-9F0A-34E3CA14B6CD}" 18 | EndProject 19 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SerilogTimings.Tests", "test\SerilogTimings.Tests\SerilogTimings.Tests.csproj", "{E813903B-9791-43FA-AB21-7757385C7EB1}" 20 | EndProject 21 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Example", "sample\Example\Example.csproj", "{3482E6CB-3EE6-4BCF-8DBB-2343ECCFD1E1}" 22 | EndProject 23 | Global 24 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 25 | Debug|Any CPU = Debug|Any CPU 26 | Release|Any CPU = Release|Any CPU 27 | EndGlobalSection 28 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 29 | {3B709371-7B4D-41D5-9F0A-34E3CA14B6CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 30 | {3B709371-7B4D-41D5-9F0A-34E3CA14B6CD}.Debug|Any CPU.Build.0 = Debug|Any CPU 31 | {3B709371-7B4D-41D5-9F0A-34E3CA14B6CD}.Release|Any CPU.ActiveCfg = Release|Any CPU 32 | {3B709371-7B4D-41D5-9F0A-34E3CA14B6CD}.Release|Any CPU.Build.0 = Release|Any CPU 33 | {E813903B-9791-43FA-AB21-7757385C7EB1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 34 | {E813903B-9791-43FA-AB21-7757385C7EB1}.Debug|Any CPU.Build.0 = Debug|Any CPU 35 | {E813903B-9791-43FA-AB21-7757385C7EB1}.Release|Any CPU.ActiveCfg = Release|Any CPU 36 | {E813903B-9791-43FA-AB21-7757385C7EB1}.Release|Any CPU.Build.0 = Release|Any CPU 37 | {3482E6CB-3EE6-4BCF-8DBB-2343ECCFD1E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 38 | {3482E6CB-3EE6-4BCF-8DBB-2343ECCFD1E1}.Debug|Any CPU.Build.0 = Debug|Any CPU 39 | {3482E6CB-3EE6-4BCF-8DBB-2343ECCFD1E1}.Release|Any CPU.ActiveCfg = Release|Any CPU 40 | {3482E6CB-3EE6-4BCF-8DBB-2343ECCFD1E1}.Release|Any CPU.Build.0 = Release|Any CPU 41 | EndGlobalSection 42 | GlobalSection(SolutionProperties) = preSolution 43 | HideSolutionNode = FALSE 44 | EndGlobalSection 45 | GlobalSection(ExtensibilityGlobals) = postSolution 46 | SolutionGuid = {7D3EB619-9D44-46CA-9488-F3FBBBD9D6BA} 47 | EndGlobalSection 48 | EndGlobal 49 | -------------------------------------------------------------------------------- /serilog-timings.sln.DotSettings: -------------------------------------------------------------------------------- 1 |  2 | True 3 | True 4 | True 5 | True 6 | True -------------------------------------------------------------------------------- /src/SerilogTimings/CompletionBehaviour.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 SerilogTimings Contributors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace SerilogTimings 16 | { 17 | enum CompletionBehaviour 18 | { 19 | Abandon, 20 | Complete, 21 | Silent 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/SerilogTimings/Configuration/LevelledOperation.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 SerilogTimings Contributors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Serilog; 16 | using Serilog.Core; 17 | using Serilog.Events; 18 | 19 | namespace SerilogTimings.Configuration 20 | { 21 | /// 22 | /// Launches s with non-default completion and abandonment levels. 23 | /// 24 | /// 25 | public class LevelledOperation 26 | { 27 | readonly Operation? _cachedResult; 28 | 29 | readonly ILogger? _logger; 30 | readonly LogEventLevel _completion; 31 | readonly LogEventLevel _abandonment; 32 | readonly TimeSpan? _warningThreshold; 33 | 34 | internal LevelledOperation(ILogger logger, LogEventLevel completion, LogEventLevel abandonment, TimeSpan? warningThreshold = null) 35 | { 36 | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); 37 | _completion = completion; 38 | _abandonment = abandonment; 39 | _warningThreshold = warningThreshold; 40 | } 41 | 42 | LevelledOperation(Operation cachedResult) 43 | { 44 | _cachedResult = cachedResult ?? throw new ArgumentNullException(nameof(cachedResult)); 45 | } 46 | 47 | internal static LevelledOperation None { get; } = new LevelledOperation( 48 | new Operation( 49 | new LoggerConfiguration().CreateLogger(), 50 | "", Array.Empty(), 51 | CompletionBehaviour.Silent, 52 | LogEventLevel.Fatal, 53 | LogEventLevel.Fatal)); 54 | 55 | /// 56 | /// Begin a new timed operation. The return value must be completed using , 57 | /// or disposed to record abandonment. 58 | /// 59 | /// A log message describing the operation, in message template format. 60 | /// Arguments to the log message. These will be stored and captured only when the 61 | /// operation completes, so do not pass arguments that are mutated during the operation. 62 | /// An object. 63 | [MessageTemplateFormatMethod("messageTemplate")] 64 | public Operation Begin(string messageTemplate, params object[] args) 65 | { 66 | return _cachedResult ?? new Operation(_logger!, messageTemplate, args, CompletionBehaviour.Abandon, _completion, _abandonment, _warningThreshold); 67 | } 68 | 69 | /// 70 | /// Begin a new timed operation. The return value must be disposed to complete the operation. 71 | /// 72 | /// A log message describing the operation, in message template format. 73 | /// Arguments to the log message. These will be stored and captured only when the 74 | /// operation completes, so do not pass arguments that are mutated during the operation. 75 | /// An object. 76 | [MessageTemplateFormatMethod("messageTemplate")] 77 | public IDisposable Time(string messageTemplate, params object[] args) 78 | { 79 | return _cachedResult ?? new Operation(_logger!, messageTemplate, args, CompletionBehaviour.Complete, _completion, _abandonment, _warningThreshold); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/SerilogTimings/Extensions/LoggerOperationExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 SerilogTimings Contributors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Serilog; 16 | using Serilog.Core; 17 | using Serilog.Events; 18 | using SerilogTimings.Configuration; 19 | 20 | namespace SerilogTimings.Extensions 21 | { 22 | /// 23 | /// Extends with timed operations. 24 | /// 25 | public static class LoggerOperationExtensions 26 | { 27 | /// 28 | /// Begin a new timed operation. The return value must be disposed to complete the operation. 29 | /// 30 | /// The logger through which the timing will be recorded. 31 | /// A log message describing the operation, in message template format. 32 | /// Arguments to the log message. These will be stored and captured only when the 33 | /// operation completes, so do not pass arguments that are mutated during the operation. 34 | /// An object. 35 | [MessageTemplateFormatMethod("messageTemplate")] 36 | public static IDisposable TimeOperation(this ILogger logger, string messageTemplate, params object[] args) 37 | { 38 | return new Operation(logger, messageTemplate, args, CompletionBehaviour.Complete, LogEventLevel.Information, LogEventLevel.Warning); 39 | } 40 | 41 | /// 42 | /// Begin a new timed operation. The return value must be completed using , 43 | /// or disposed to record abandonment. 44 | /// 45 | /// The logger through which the timing will be recorded. 46 | /// A log message describing the operation, in message template format. 47 | /// Arguments to the log message. These will be stored and captured only when the 48 | /// operation completes, so do not pass arguments that are mutated during the operation. 49 | /// An object. 50 | [MessageTemplateFormatMethod("messageTemplate")] 51 | public static Operation BeginOperation(this ILogger logger, string messageTemplate, params object[] args) 52 | { 53 | return new Operation(logger, messageTemplate, args, CompletionBehaviour.Abandon, LogEventLevel.Information, LogEventLevel.Warning); 54 | } 55 | 56 | /// 57 | /// Configure the logging levels used for completion and abandonment events. 58 | /// 59 | /// The logger through which the timing will be recorded. 60 | /// The level of the event to write on operation completion. 61 | /// The level of the event to write on operation abandonment; if not 62 | /// specified, the level will be used. 63 | /// The threshold which determines whether the timing will be recorded as warning 64 | /// An object from which timings with the configured levels can be made. 65 | /// If neither nor is enabled 66 | /// on the logger at the time of the call, a no-op result is returned. 67 | public static LevelledOperation OperationAt(this ILogger logger, LogEventLevel completion, LogEventLevel? abandonment = null, TimeSpan? warningThreshold = null) 68 | { 69 | if (logger == null) throw new ArgumentNullException(nameof(logger)); 70 | 71 | var appliedAbandonment = abandonment ?? completion; 72 | if (!logger.IsEnabled(completion) && 73 | (appliedAbandonment == completion || !logger.IsEnabled(appliedAbandonment))) 74 | { 75 | return LevelledOperation.None; 76 | } 77 | 78 | return new LevelledOperation(logger, completion, appliedAbandonment, warningThreshold); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/SerilogTimings/Operation.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 SerilogTimings Contributors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Serilog; 16 | using Serilog.Context; 17 | using Serilog.Core; 18 | using Serilog.Events; 19 | using SerilogTimings.Configuration; 20 | using SerilogTimings.Extensions; 21 | using System.Diagnostics; 22 | 23 | namespace SerilogTimings 24 | { 25 | /// 26 | /// Records operation timings to the Serilog log. 27 | /// 28 | /// 29 | /// Static members on this class are thread-safe. Instances 30 | /// of are designed for use on a single thread only. 31 | /// 32 | public class Operation : IDisposable 33 | { 34 | /// 35 | /// Property names attached to events by s. 36 | /// 37 | // ReSharper disable once MemberCanBePrivate.Global 38 | public enum Properties 39 | { 40 | /// 41 | /// The timing, in milliseconds. 42 | /// 43 | Elapsed, 44 | 45 | /// 46 | /// Completion status, either completed or discarded. 47 | /// 48 | Outcome, 49 | 50 | /// 51 | /// A unique identifier added to the log context during 52 | /// the operation. 53 | /// 54 | OperationId 55 | }; 56 | 57 | const string OutcomeCompleted = "completed", OutcomeAbandoned = "abandoned"; 58 | static readonly double StopwatchToTimeSpanTicks = (double)Stopwatch.Frequency / TimeSpan.TicksPerSecond; 59 | 60 | ILogger _target; 61 | readonly string _messageTemplate; 62 | readonly object[] _args; 63 | readonly long _start; 64 | long? _stop; 65 | 66 | readonly IDisposable _popContext; 67 | CompletionBehaviour _completionBehaviour; 68 | readonly LogEventLevel _completionLevel; 69 | readonly LogEventLevel _abandonmentLevel; 70 | readonly TimeSpan? _warningThreshold; 71 | Exception? _exception; 72 | 73 | internal Operation(ILogger target, string messageTemplate, object[] args, 74 | CompletionBehaviour completionBehaviour, LogEventLevel completionLevel, LogEventLevel abandonmentLevel, 75 | TimeSpan? warningThreshold = null) 76 | { 77 | _target = target ?? throw new ArgumentNullException(nameof(target)); 78 | _messageTemplate = messageTemplate ?? throw new ArgumentNullException(nameof(messageTemplate)); 79 | _args = args ?? throw new ArgumentNullException(nameof(args)); 80 | _completionBehaviour = completionBehaviour; 81 | _completionLevel = completionLevel; 82 | _abandonmentLevel = abandonmentLevel; 83 | _warningThreshold = warningThreshold; 84 | _popContext = LogContext.PushProperty(nameof(Properties.OperationId), Guid.NewGuid()); 85 | _start = GetTimestamp(); 86 | } 87 | 88 | static long GetTimestamp() 89 | { 90 | return unchecked((long)(Stopwatch.GetTimestamp() / StopwatchToTimeSpanTicks)); 91 | } 92 | 93 | /// 94 | /// Begin a new timed operation. The return value must be completed using , 95 | /// or disposed to record abandonment. 96 | /// 97 | /// A log message describing the operation, in message template format. 98 | /// Arguments to the log message. These will be stored and captured only when the 99 | /// operation completes, so do not pass arguments that are mutated during the operation. 100 | /// An object. 101 | [MessageTemplateFormatMethod("messageTemplate")] 102 | public static Operation Begin(string messageTemplate, params object[] args) 103 | { 104 | return Log.Logger.BeginOperation(messageTemplate, args); 105 | } 106 | 107 | /// 108 | /// Begin a new timed operation. The return value must be disposed to complete the operation. 109 | /// 110 | /// A log message describing the operation, in message template format. 111 | /// Arguments to the log message. These will be stored and captured only when the 112 | /// operation completes, so do not pass arguments that are mutated during the operation. 113 | /// An object. 114 | [MessageTemplateFormatMethod("messageTemplate")] 115 | public static IDisposable Time(string messageTemplate, params object[] args) 116 | { 117 | return Log.Logger.TimeOperation(messageTemplate, args); 118 | } 119 | 120 | /// 121 | /// Configure the logging levels used for completion and abandonment events. 122 | /// 123 | /// The level of the event to write on operation completion. 124 | /// The level of the event to write on operation abandonment; if not 125 | /// specified, the level will be used. 126 | /// An object from which timings with the configured levels can be made. 127 | /// If neither nor is enabled 128 | /// on the logger at the time of the call, a no-op result is returned. 129 | public static LevelledOperation At(LogEventLevel completion, LogEventLevel? abandonment = null) 130 | { 131 | return Log.Logger.OperationAt(completion, abandonment); 132 | } 133 | 134 | /// 135 | /// Returns the elapsed time of the operation. This will update during the operation, and be frozen once the 136 | /// operation is completed or canceled. 137 | /// 138 | public TimeSpan Elapsed 139 | { 140 | get 141 | { 142 | var stop = _stop ?? GetTimestamp(); 143 | var elapsedTicks = stop - _start; 144 | 145 | if (elapsedTicks < 0) 146 | { 147 | // When measuring small time periods the StopWatch.Elapsed* properties can return negative values. 148 | // This is due to bugs in the basic input/output system (BIOS) or the hardware abstraction layer 149 | // (HAL) on machines with variable-speed CPUs (e.g. Intel SpeedStep). 150 | return TimeSpan.Zero; 151 | } 152 | 153 | return TimeSpan.FromTicks(elapsedTicks); 154 | } 155 | } 156 | 157 | /// 158 | /// Complete the timed operation. This will write the event and elapsed time to the log. 159 | /// 160 | public void Complete() 161 | { 162 | if (_completionBehaviour == CompletionBehaviour.Silent) 163 | return; 164 | 165 | Write(_target, _completionLevel, OutcomeCompleted); 166 | } 167 | 168 | /// 169 | /// Complete the timed operation with the given Log Event level. This will write the event and elapsed time to the log. 170 | /// 171 | /// The log event level with which the complete operation will be logged 172 | 173 | public void Complete(LogEventLevel level) 174 | { 175 | if (_completionBehaviour == CompletionBehaviour.Silent) 176 | return; 177 | 178 | Write(_target, level, OutcomeCompleted); 179 | } 180 | 181 | 182 | /// 183 | /// Complete the timed operation with an included result value. 184 | /// 185 | /// The name for the property to attach to the event. 186 | /// The result value. 187 | /// If true, the property value will be destructured (serialized). 188 | public void Complete(string resultPropertyName, object result, bool destructureObjects = false) 189 | { 190 | if (resultPropertyName == null) throw new ArgumentNullException(nameof(resultPropertyName)); 191 | 192 | if (_completionBehaviour == CompletionBehaviour.Silent) 193 | return; 194 | 195 | Write(_target.ForContext(resultPropertyName, result, destructureObjects), _completionLevel, OutcomeCompleted); 196 | } 197 | 198 | /// 199 | /// Complete the timed operation with an included result value and log event level. 200 | /// 201 | /// The log event level with which the complete operation will be logged 202 | /// The name for the property to attach to the event. 203 | /// The result value. 204 | /// If true, the property value will be destructured (serialized). 205 | public void Complete(string resultPropertyName, object result, LogEventLevel level, bool destructureObjects = false) 206 | { 207 | if (resultPropertyName == null) throw new ArgumentNullException(nameof(resultPropertyName)); 208 | 209 | if (_completionBehaviour == CompletionBehaviour.Silent) 210 | return; 211 | 212 | Write(_target.ForContext(resultPropertyName, result, destructureObjects), level, OutcomeCompleted); 213 | } 214 | 215 | /// 216 | /// Abandon the timed operation. This will write the event and elapsed time to the log. 217 | /// 218 | public void Abandon() 219 | { 220 | if (_completionBehaviour == CompletionBehaviour.Silent) 221 | return; 222 | 223 | Write(_target, _abandonmentLevel, OutcomeAbandoned); 224 | } 225 | 226 | /// 227 | /// Cancel the timed operation. After calling, no event will be recorded either through 228 | /// completion or disposal. 229 | /// 230 | public void Cancel() 231 | { 232 | _completionBehaviour = CompletionBehaviour.Silent; 233 | PopLogContext(); 234 | } 235 | 236 | /// 237 | /// Dispose the operation. If not already completed or canceled, an event will be written 238 | /// with timing information. Operations started with will be completed through 239 | /// disposal. Operations started with will be recorded as abandoned. 240 | /// 241 | public void Dispose() 242 | { 243 | switch (_completionBehaviour) 244 | { 245 | case CompletionBehaviour.Silent: 246 | break; 247 | 248 | case CompletionBehaviour.Abandon: 249 | Write(_target, _abandonmentLevel, OutcomeAbandoned); 250 | break; 251 | 252 | case CompletionBehaviour.Complete: 253 | Write(_target, _completionLevel, OutcomeCompleted); 254 | break; 255 | 256 | default: 257 | throw new InvalidOperationException("Unknown underlying state value"); 258 | } 259 | 260 | PopLogContext(); 261 | } 262 | 263 | void StopTiming() 264 | { 265 | _stop ??= GetTimestamp(); 266 | } 267 | 268 | void PopLogContext() 269 | { 270 | _popContext.Dispose(); 271 | } 272 | 273 | void Write(ILogger target, LogEventLevel level, string outcome) 274 | { 275 | StopTiming(); 276 | _completionBehaviour = CompletionBehaviour.Silent; 277 | 278 | var elapsed = Elapsed.TotalMilliseconds; 279 | 280 | level = elapsed > _warningThreshold?.TotalMilliseconds && level < LogEventLevel.Warning 281 | ? LogEventLevel.Warning 282 | : level; 283 | 284 | target.Write(level, _exception, $"{_messageTemplate} {{{nameof(Properties.Outcome)}}} in {{{nameof(Properties.Elapsed)}:0.0}} ms", _args.Concat(new object[] { outcome, elapsed }).ToArray()); 285 | 286 | PopLogContext(); 287 | } 288 | 289 | /// 290 | /// Enriches resulting log event via the provided enricher. 291 | /// 292 | /// Enricher that applies in the context. 293 | /// Same . 294 | /// 295 | public Operation EnrichWith(ILogEventEnricher enricher) 296 | { 297 | _target = _target.ForContext(enricher); 298 | return this; 299 | } 300 | 301 | /// 302 | /// Enriches resulting log event via the provided enrichers. 303 | /// 304 | /// Enrichers that apply in the context. 305 | /// A logger that will enrich log events as specified. 306 | /// Same . 307 | /// 308 | public Operation EnrichWith(IEnumerable enrichers) 309 | { 310 | _target = _target.ForContext(enrichers); 311 | return this; 312 | } 313 | 314 | /// 315 | /// Enriches resulting log event with the specified property. 316 | /// 317 | /// The name of the property. Must be non-empty. 318 | /// The property value. 319 | /// If true, the value will be serialized as a structured 320 | /// object if possible; if false, the object will be recorded as a scalar or simple array. 321 | /// Same . 322 | /// 323 | public Operation EnrichWith(string propertyName, object value, bool destructureObjects = false) 324 | { 325 | _target = _target.ForContext(propertyName, value, destructureObjects); 326 | return this; 327 | } 328 | 329 | /// 330 | /// Enriches resulting log event with the given exception. 331 | /// 332 | /// Exception related to the event. 333 | /// Same . 334 | /// 335 | public Operation SetException(Exception exception) 336 | { 337 | _exception = exception; 338 | return this; 339 | } 340 | } 341 | } 342 | -------------------------------------------------------------------------------- /src/SerilogTimings/OperationExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2019 SerilogTimings Contributors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Serilog.Core; 16 | 17 | namespace SerilogTimings 18 | { 19 | /// 20 | /// Exception-handling related helpers for . 21 | /// 22 | public static class OperationExtensions 23 | { 24 | /// 25 | /// Enriches resulting log event with the given exception and skips exception-handling block. 26 | /// 27 | /// Operation to enrich with exception. 28 | /// Exception related to the event. 29 | /// false 30 | /// 31 | /// 32 | /// 33 | /// using (var op = Operation.Begin(...) 34 | /// { 35 | /// try 36 | /// { 37 | /// //Do something 38 | /// op.Complete(); 39 | /// } 40 | /// catch (Exception e) when (op.SetExceptionAndRethrow(e)) 41 | /// { 42 | /// //this will never be called 43 | /// } 44 | /// } 45 | /// 46 | /// 47 | public static bool SetExceptionAndRethrow(this Operation operation, Exception exception) 48 | { 49 | operation.SetException(exception); 50 | return false; 51 | } 52 | 53 | /// 54 | /// Complete the timed operation enriching it with provided enricher. 55 | /// 56 | /// Operation to enrich and complete. 57 | /// Enricher that applies in the context. 58 | /// 59 | /// 60 | public static void Complete(this Operation operation, ILogEventEnricher enricher) 61 | => operation.EnrichWith(enricher).Complete(); 62 | 63 | /// 64 | /// Complete the timed operation enriching it with provided enrichers. 65 | /// 66 | /// Operation to enrich and complete. 67 | /// Enrichers that apply in the context. 68 | /// 69 | /// 70 | public static void Complete(this Operation operation, IEnumerable enrichers) 71 | => operation.EnrichWith(enrichers).Complete(); 72 | 73 | /// 74 | /// Abandon the timed operation with an included result value. 75 | /// 76 | /// Operation to enrich and abandon. 77 | /// The name for the property to attach to the event. 78 | /// The result value. 79 | /// If true, the property value will be destructured (serialized). 80 | /// 81 | /// 82 | public static void Abandon(this Operation operation, string resultPropertyName, object result, bool destructureObjects = false) 83 | => operation.EnrichWith(resultPropertyName, result, destructureObjects).Abandon(); 84 | 85 | /// 86 | /// Abandon the timed operation enriching it with provided enricher. 87 | /// 88 | /// Operation to enrich and abandon. 89 | /// Enricher that applies in the context. 90 | /// 91 | /// 92 | public static void Abandon(this Operation operation, ILogEventEnricher enricher) 93 | => operation.EnrichWith(enricher).Abandon(); 94 | 95 | /// 96 | /// Abandon the timed operation enriching it with provided enrichers. 97 | /// 98 | /// Operation to enrich and abandon. 99 | /// Enrichers that apply in the context. 100 | /// 101 | /// 102 | public static void Abandon(this Operation operation, IEnumerable enrichers) 103 | => operation.EnrichWith(enrichers).Abandon(); 104 | 105 | /// 106 | /// Abandon the timed operation with an included exception. 107 | /// 108 | /// Operation to enrich and abandon. 109 | /// Enricher related to the event. 110 | /// 111 | /// 112 | public static void Abandon(this Operation operation, Exception exception) 113 | => operation.SetException(exception).Abandon(); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/SerilogTimings/SerilogTimings.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Extend Serilog with timed operations. 5 | 3.1.1 6 | nblumhardt;SerilogTimings Contributors 7 | netstandard2.0;net6.0 8 | true 9 | true 10 | enable 11 | enable 12 | 10 13 | ../../asset/SerilogTimings.snk 14 | true 15 | true 16 | serilog;metrics;timings;operations 17 | serilog-timings.png 18 | https://github.com/nblumhardt/serilog-timings 19 | Apache-2.0 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /test/SerilogTimings.Tests/OperationEnrichmentTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Serilog.Core; 3 | using Serilog.Events; 4 | using SerilogTimings.Extensions; 5 | using SerilogTimings.Tests.Support; 6 | using Xunit; 7 | 8 | namespace SerilogTimings.Tests 9 | { 10 | public class OperationEnrichmentTests 11 | { 12 | static void AssertScalarPropertyOfSingleEvent(CollectingLogger logger, string propertyName, T expected) 13 | { 14 | var ev = Assert.Single(logger.Events); 15 | Assert.True(ev.Properties.TryGetValue(propertyName, out var value)); 16 | Assert.Equal( 17 | expected, 18 | Assert.IsType(Assert.IsType(value).Value) 19 | ); 20 | } 21 | 22 | [Fact] 23 | public void AbandonRecordsAddedProperty() 24 | { 25 | var logger = new CollectingLogger(); 26 | var op = logger.Logger.BeginOperation("Test"); 27 | op.EnrichWith("Value", 42); 28 | op.Dispose(); 29 | AssertScalarPropertyOfSingleEvent(logger, "Value", 42); 30 | } 31 | 32 | [Fact] 33 | public void CompleteRecordsAddedProperty() 34 | { 35 | var logger = new CollectingLogger(); 36 | var op = logger.Logger.BeginOperation("Test"); 37 | op.EnrichWith("Value", 42); 38 | op.Complete(); 39 | AssertScalarPropertyOfSingleEvent(logger, "Value", 42); 40 | } 41 | 42 | [Fact] 43 | public void CompleteOverridesAddedProperty() 44 | { 45 | var logger = new CollectingLogger(); 46 | var op = logger.Logger.BeginOperation("Test"); 47 | op.EnrichWith("Value", 42); 48 | op.Complete("Value", 43); 49 | AssertScalarPropertyOfSingleEvent(logger, "Value", 43); 50 | } 51 | 52 | [Fact] 53 | public void AbandonRecordsPropertyAddedViaEnricher() 54 | { 55 | var logger = new CollectingLogger(); 56 | var op = logger.Logger.BeginOperation("Test"); 57 | op.EnrichWith(new Enricher("Value", 42)); 58 | op.Dispose(); 59 | AssertScalarPropertyOfSingleEvent(logger, "Value", 42); 60 | } 61 | 62 | [Fact] 63 | public void CompleteRecordsPropertyAddedViaEnricher() 64 | { 65 | var logger = new CollectingLogger(); 66 | var op = logger.Logger.BeginOperation("Test"); 67 | op.EnrichWith(new Enricher("Value", 42)); 68 | op.Complete(); 69 | AssertScalarPropertyOfSingleEvent(logger, "Value", 42); 70 | } 71 | 72 | [Fact] 73 | public void OnceCanceledDisposeDoesNotInvokeEnricher() 74 | { 75 | var enricher = new Enricher(null, null); 76 | var logger = new CollectingLogger(); 77 | var op = logger.Logger.BeginOperation("Test"); 78 | op.EnrichWith(enricher); 79 | op.Cancel(); 80 | op.Dispose(); 81 | Assert.False(enricher.WasCalled); 82 | } 83 | 84 | [Fact] 85 | public void OnceCanceledCompleteDoesNotInvokeEnricher() 86 | { 87 | var enricher = new Enricher(null, null); 88 | var logger = new CollectingLogger(); 89 | var op = logger.Logger.BeginOperation("Test"); 90 | op.EnrichWith(enricher); 91 | op.Cancel(); 92 | op.Complete(); 93 | op.Dispose(); 94 | Assert.False(enricher.WasCalled); 95 | } 96 | 97 | [Fact] 98 | public void AbandonRecordsPropertiesAddedViaEnrichers() 99 | { 100 | var logger = new CollectingLogger(); 101 | var op = logger.Logger.BeginOperation("Test"); 102 | op.EnrichWith(new ILogEventEnricher[] { 103 | new Enricher("Question", "unknown"), 104 | new Enricher("Answer", 42) 105 | }); 106 | op.Dispose(); 107 | AssertScalarPropertyOfSingleEvent(logger, "Question", "unknown"); 108 | AssertScalarPropertyOfSingleEvent(logger, "Answer", 42); 109 | } 110 | 111 | [Fact] 112 | public void CompleteRecordsPropertiesAddedViaEnrichers() 113 | { 114 | var logger = new CollectingLogger(); 115 | var op = logger.Logger.BeginOperation("Test"); 116 | op.EnrichWith(new ILogEventEnricher[] { 117 | new Enricher("Question", "unknown"), 118 | new Enricher("Answer", 42) 119 | }); 120 | op.Complete(); 121 | AssertScalarPropertyOfSingleEvent(logger, "Question", "unknown"); 122 | AssertScalarPropertyOfSingleEvent(logger, "Answer", 42); 123 | } 124 | 125 | [Fact] 126 | public void CompleteOverloadWithEnricherRecordsPropertyAddedViaEnricher() 127 | { 128 | var logger = new CollectingLogger(); 129 | var op = logger.Logger.BeginOperation("Test"); 130 | op.Complete(new Enricher("Value", 42)); 131 | AssertScalarPropertyOfSingleEvent(logger, "Value", 42); 132 | } 133 | 134 | [Fact] 135 | public void CompleteOverloadWithEnrichersRecordsPropertiesAddedViaEnrichers() 136 | { 137 | var logger = new CollectingLogger(); 138 | var op = logger.Logger.BeginOperation("Test"); 139 | op.Complete(new ILogEventEnricher[] { 140 | new Enricher("Question", "unknown"), 141 | new Enricher("Answer", 42) 142 | }); 143 | AssertScalarPropertyOfSingleEvent(logger, "Question", "unknown"); 144 | AssertScalarPropertyOfSingleEvent(logger, "Answer", 42); 145 | } 146 | 147 | [Fact] 148 | public void PropertyBonanza() 149 | { 150 | var logger = new CollectingLogger(); 151 | logger.Logger 152 | .BeginOperation("Test") 153 | .EnrichWith(new ILogEventEnricher[] { 154 | new Enricher("Question", "unknown"), 155 | new Enricher("Answer", 42) 156 | }) 157 | .EnrichWith(new Enricher("Don't", "panic")) 158 | .EnrichWith("And bring", "towel") 159 | .Complete(); 160 | AssertScalarPropertyOfSingleEvent(logger, "Question", "unknown"); 161 | AssertScalarPropertyOfSingleEvent(logger, "Answer", 42); 162 | AssertScalarPropertyOfSingleEvent(logger, "Don't", "panic"); 163 | AssertScalarPropertyOfSingleEvent(logger, "And bring", "towel"); 164 | } 165 | 166 | [Fact] 167 | public void DisposedOperationDoesNotCaptureException() 168 | { 169 | var logger = new CollectingLogger(); 170 | Assert.Throws((Action) (() => 171 | { 172 | using (logger.Logger.BeginOperation("Test")) 173 | { 174 | throw new InvalidOperationException(); 175 | } 176 | }) 177 | ); 178 | Assert.Null(Assert.Single(logger.Events).Exception); 179 | } 180 | 181 | [Fact] 182 | public void DisposeRecordsSetException() 183 | { 184 | var exception = new InvalidOperationException(); 185 | var logger = new CollectingLogger(); 186 | Assert.Throws((Action) (() => 187 | { 188 | using (var op = logger.Logger.BeginOperation("Test")) 189 | { 190 | try 191 | { 192 | throw exception; 193 | } 194 | catch (Exception e) 195 | { 196 | op.SetException(e); 197 | throw; 198 | } 199 | } 200 | }) 201 | ); 202 | Assert.Same(exception, Assert.Single(logger.Events).Exception); 203 | } 204 | 205 | [Fact] 206 | public void CompleteRecordsSetException() 207 | { 208 | var exception = new InvalidOperationException(); 209 | var logger = new CollectingLogger(); 210 | using (var op = logger.Logger.BeginOperation("Test")) 211 | { 212 | try 213 | { 214 | throw exception; 215 | } 216 | catch (Exception e) 217 | { 218 | op.SetException(e); 219 | op.Complete(); 220 | } 221 | } 222 | Assert.Same(exception, Assert.Single(logger.Events).Exception); 223 | } 224 | 225 | [Fact] 226 | public void SetExceptionAndRethrowSkipsCatchBlock() 227 | { 228 | var exception = new InvalidOperationException(); 229 | var logger = new CollectingLogger(); 230 | Assert.Throws((Action) (() => 231 | { 232 | using (var op = logger.Logger.BeginOperation("Test")) 233 | { 234 | try 235 | { 236 | throw exception; 237 | } 238 | catch (Exception e) when (op.SetExceptionAndRethrow(e)) 239 | { 240 | throw new Exception("This catch block should be skipped"); 241 | } 242 | } 243 | }) 244 | ); 245 | Assert.Same(exception, Assert.Single(logger.Events).Exception); 246 | } 247 | 248 | [Fact] 249 | public void AbandonRecordsResultsOfOperations() 250 | { 251 | var logger = new CollectingLogger(); 252 | var op = logger.Logger.BeginOperation("Test"); 253 | op.Abandon("Value", 42); 254 | AssertScalarPropertyOfSingleEvent(logger, "Value", 42); 255 | } 256 | 257 | [Fact] 258 | public void AbandonOverloadWithEnricherRecordsPropertyAddedViaEnricher() 259 | { 260 | var logger = new CollectingLogger(); 261 | var op = logger.Logger.BeginOperation("Test"); 262 | op.Abandon(new Enricher("Value", 42)); 263 | AssertScalarPropertyOfSingleEvent(logger, "Value", 42); 264 | } 265 | 266 | [Fact] 267 | public void AbandonOverloadWithEnrichersRecordsPropertiesAddedViaEnrichers() 268 | { 269 | var logger = new CollectingLogger(); 270 | var op = logger.Logger.BeginOperation("Test"); 271 | op.Abandon(new ILogEventEnricher[] { 272 | new Enricher("Question", "unknown"), 273 | new Enricher("Answer", 42) 274 | }); 275 | AssertScalarPropertyOfSingleEvent(logger, "Question", "unknown"); 276 | AssertScalarPropertyOfSingleEvent(logger, "Answer", 42); 277 | } 278 | 279 | [Fact] 280 | public void AbandonRecordsException() 281 | { 282 | var exception = new InvalidOperationException(); 283 | var logger = new CollectingLogger(); 284 | using (var op = logger.Logger.BeginOperation("Test")) 285 | { 286 | try 287 | { 288 | throw exception; 289 | } 290 | catch (Exception e) 291 | { 292 | op.Abandon(e); 293 | } 294 | } 295 | Assert.Same(exception, Assert.Single(logger.Events).Exception); 296 | } 297 | 298 | class Enricher : ILogEventEnricher 299 | { 300 | string _propertyName; 301 | object _value; 302 | 303 | public Enricher(string propertyName, object value) 304 | { 305 | _propertyName = propertyName; 306 | _value = value; 307 | } 308 | 309 | public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) 310 | { 311 | WasCalled = true; 312 | logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(_propertyName, _value)); 313 | } 314 | 315 | public bool WasCalled { get; private set; } 316 | } 317 | } 318 | } 319 | -------------------------------------------------------------------------------- /test/SerilogTimings.Tests/OperationTests.cs: -------------------------------------------------------------------------------- 1 | using Serilog; 2 | using Serilog.Events; 3 | using SerilogTimings.Extensions; 4 | using SerilogTimings.Tests.Support; 5 | using System; 6 | using System.Linq; 7 | using System.Threading.Tasks; 8 | using Xunit; 9 | 10 | namespace SerilogTimings.Tests 11 | { 12 | public class OperationTests 13 | { 14 | const string OutcomeCompleted = "completed"; 15 | const string OutcomeAbandoned = "abandoned"; 16 | 17 | // ReSharper disable once UnusedMethodReturnValue.Local 18 | static LogEvent AssertSingleCompletionEvent(CollectingLogger logger, LogEventLevel expectedLevel, 19 | string expectedOutcome) 20 | { 21 | T GetScalarPropertyValue(LogEvent e, string key) 22 | { 23 | Assert.True(e.Properties.TryGetValue(key, out var value)); 24 | return Assert.IsType(Assert.IsType(value).Value); 25 | } 26 | 27 | var ev = Assert.Single(logger.Events); 28 | Assert.NotNull(ev); 29 | Assert.Equal(expectedLevel, ev.Level); 30 | 31 | Assert.Equal(expectedOutcome, GetScalarPropertyValue(ev, nameof(Operation.Properties.Outcome))); 32 | GetScalarPropertyValue(ev, nameof(Operation.Properties.Elapsed)); 33 | return ev; 34 | } 35 | 36 | static double GetElapsedMilliseconds(CollectingLogger logger) 37 | { 38 | var elapsed = (double)((ScalarValue)logger.Events.Single().Properties[nameof(Operation.Properties.Elapsed)]).Value; 39 | return elapsed; 40 | } 41 | 42 | [Fact] 43 | public void DisposeRecordsCompletionOfTimings() 44 | { 45 | var logger = new CollectingLogger(); 46 | var op = logger.Logger.TimeOperation("Test"); 47 | op.Dispose(); 48 | AssertSingleCompletionEvent(logger, LogEventLevel.Information, OutcomeCompleted); 49 | } 50 | 51 | [Fact] 52 | public void CompleteRecordsCompletionOfOperations() 53 | { 54 | var logger = new CollectingLogger(); 55 | var op = logger.Logger.BeginOperation("Test"); 56 | op.Complete(); 57 | AssertSingleCompletionEvent(logger, LogEventLevel.Information, OutcomeCompleted); 58 | 59 | op.Dispose(); 60 | Assert.Single(logger.Events); 61 | } 62 | 63 | [Fact] 64 | public void DisposeRecordsAbandonmentOfIncompleteOperations() 65 | { 66 | var logger = new CollectingLogger(); 67 | var op = logger.Logger.BeginOperation("Test"); 68 | op.Dispose(); 69 | AssertSingleCompletionEvent(logger, LogEventLevel.Warning, OutcomeAbandoned); 70 | 71 | op.Dispose(); 72 | Assert.Single(logger.Events); 73 | } 74 | 75 | [Fact] 76 | public void AbandonRecordsAbandonmentOfBegunOperations() 77 | { 78 | var logger = new CollectingLogger(); 79 | var op = logger.Logger.BeginOperation("Test"); 80 | op.Abandon(); 81 | AssertSingleCompletionEvent(logger, LogEventLevel.Warning, OutcomeAbandoned); 82 | 83 | op.Dispose(); 84 | Assert.Single(logger.Events); 85 | } 86 | 87 | [Fact] 88 | public void CompleteRecordsResultsOfOperations() 89 | { 90 | var logger = new CollectingLogger(); 91 | var op = logger.Logger.BeginOperation("Test"); 92 | op.Complete("Value", 42); 93 | Assert.Single(logger.Events); 94 | Assert.True(logger.Events.Single().Properties.ContainsKey("Value")); 95 | } 96 | 97 | [Fact] 98 | public void CompleteRecordsResultsOfOperationsWithGivenLogLevel() 99 | { 100 | var logger = new CollectingLogger(); 101 | var op = logger.Logger.BeginOperation("Test"); 102 | op.Complete("Value", 42, LogEventLevel.Warning); 103 | Assert.Single(logger.Events); 104 | Assert.True(logger.Events.Single().Properties.ContainsKey("Value")); 105 | Assert.Equal(LogEventLevel.Warning, logger.Events.Single().Level); 106 | } 107 | 108 | [Fact] 109 | public void CompletesWithGivenLogLevel() 110 | { 111 | var logger = new CollectingLogger(); 112 | var op = logger.Logger.BeginOperation("Test"); 113 | op.Complete(LogEventLevel.Error); 114 | Assert.Equal(LogEventLevel.Error, logger.Events.Single().Level); 115 | } 116 | 117 | [Fact] 118 | public void DoesNotCompleteWithGivenLevelIfAbandonedBeforehand() 119 | { 120 | var logger = new CollectingLogger(); 121 | var op = logger.Logger.BeginOperation("Test"); 122 | op.Abandon(); 123 | op.Complete(LogEventLevel.Error); 124 | Assert.Equal(LogEventLevel.Warning, logger.Events.Single().Level); 125 | } 126 | 127 | [Fact] 128 | public void OnceCanceledDisposeDoesNotRecordCompletionOfOperations() 129 | { 130 | var logger = new CollectingLogger(); 131 | var op = logger.Logger.BeginOperation("Test"); 132 | op.Cancel(); 133 | op.Dispose(); 134 | Assert.Empty(logger.Events); 135 | } 136 | 137 | [Fact] 138 | public void OnceCanceledCompleteDoesNotRecordCompletionOfOperations() 139 | { 140 | var logger = new CollectingLogger(); 141 | var op = logger.Logger.BeginOperation("Test"); 142 | op.Cancel(); 143 | op.Complete(); 144 | op.Dispose(); 145 | Assert.Empty(logger.Events); 146 | } 147 | 148 | [Fact] 149 | public void OnceCanceledAbandonDoesNotRecordCompletionOfOperations() 150 | { 151 | var logger = new CollectingLogger(); 152 | var op = logger.Logger.BeginOperation("Test"); 153 | op.Cancel(); 154 | op.Abandon(); 155 | op.Dispose(); 156 | Assert.Empty(logger.Events); 157 | } 158 | 159 | [Fact] 160 | public void OnceCompletedAbandonDoesNotRecordAbandonmentOfOperations() 161 | { 162 | var logger = new CollectingLogger(); 163 | var op = logger.Logger.BeginOperation("Test"); 164 | op.Complete(); 165 | AssertSingleCompletionEvent(logger, LogEventLevel.Information, OutcomeCompleted); 166 | 167 | op.Abandon(); 168 | op.Dispose(); 169 | Assert.Single(logger.Events); 170 | } 171 | 172 | [Fact] 173 | public void OnceAbandonedCompleteDoesNotRecordAbandonmentOfOperations() 174 | { 175 | var logger = new CollectingLogger(); 176 | var op = logger.Logger.BeginOperation("Test"); 177 | op.Abandon(); 178 | AssertSingleCompletionEvent(logger, LogEventLevel.Warning, OutcomeAbandoned); 179 | 180 | op.Complete(); 181 | op.Dispose(); 182 | Assert.Single(logger.Events); 183 | } 184 | 185 | [Fact] 186 | public void CustomCompletionLevelsAreApplied() 187 | { 188 | var logger = new CollectingLogger(); 189 | var op = logger.Logger.OperationAt(LogEventLevel.Error).Time("Test"); 190 | op.Dispose(); 191 | AssertSingleCompletionEvent(logger, LogEventLevel.Error, OutcomeCompleted); 192 | } 193 | 194 | [Fact] 195 | public void AbandonmentLevelsDefaultToCustomCompletionLevelIfApplied() 196 | { 197 | var logger = new CollectingLogger(); 198 | var op = logger.Logger.OperationAt(LogEventLevel.Error).Begin("Test"); 199 | op.Dispose(); 200 | AssertSingleCompletionEvent(logger, LogEventLevel.Error, OutcomeAbandoned); 201 | } 202 | 203 | [Fact] 204 | public void CustomAbandonmentLevelsAreApplied() 205 | { 206 | var logger = new CollectingLogger(); 207 | var op = logger.Logger.OperationAt(LogEventLevel.Error, LogEventLevel.Fatal).Begin("Test"); 208 | op.Dispose(); 209 | AssertSingleCompletionEvent(logger, LogEventLevel.Fatal, OutcomeAbandoned); 210 | } 211 | 212 | [Fact] 213 | public void IfNeitherLevelIsEnabledACachedResultIsReturned() 214 | { 215 | var logger = new LoggerConfiguration().CreateLogger(); // Information 216 | var op = logger.OperationAt(LogEventLevel.Verbose).Time("Test"); 217 | var op2 = logger.OperationAt(LogEventLevel.Verbose).Time("Test"); 218 | Assert.Same(op, op2); 219 | } 220 | 221 | [Fact] 222 | public void LoggerContextIsPreserved() 223 | { 224 | var logger = new CollectingLogger(); 225 | var op = logger.Logger 226 | .ForContext().BeginOperation("Test"); 227 | op.Complete(); 228 | 229 | var sourceContext = ((ScalarValue)logger.Events.Single().Properties["SourceContext"]).Value; 230 | Assert.Equal(sourceContext, typeof(OperationTests).FullName); 231 | } 232 | 233 | [Fact] 234 | public void CompleteRecordsOperationId() 235 | { 236 | var innerLogger = new CollectingLogger(); 237 | var logger = new LoggerConfiguration() 238 | .WriteTo.Logger(innerLogger.Logger) 239 | .Enrich.FromLogContext() 240 | .CreateLogger(); 241 | 242 | var op = logger.BeginOperation("Test"); 243 | op.Complete(); 244 | Assert.True( 245 | Assert.Single(innerLogger.Events) 246 | .Properties.ContainsKey(nameof(Operation.Properties.OperationId)) 247 | ); 248 | } 249 | 250 | [Fact] 251 | public void AbandonRecordsOperationId() 252 | { 253 | var innerLogger = new CollectingLogger(); 254 | var logger = new LoggerConfiguration() 255 | .WriteTo.Logger(innerLogger.Logger) 256 | .Enrich.FromLogContext() 257 | .CreateLogger(); 258 | 259 | var op = logger.BeginOperation("Test"); 260 | op.Dispose(); 261 | Assert.True( 262 | Assert.Single(innerLogger.Events) 263 | .Properties.ContainsKey(nameof(Operation.Properties.OperationId)) 264 | ); 265 | } 266 | 267 | [Theory] 268 | [InlineData(10)] 269 | [InlineData(100)] 270 | [InlineData(1000)] 271 | public async Task TimingWithinOrderOfMagnitude(int delay) 272 | { 273 | var logger = new CollectingLogger(); 274 | var op = logger.Logger.TimeOperation("Test"); 275 | await Task.Delay(delay); 276 | op.Dispose(); 277 | 278 | var elapsed = GetElapsedMilliseconds(logger); 279 | Assert.InRange(elapsed, delay * 0.2, delay * 8); 280 | } 281 | 282 | [Fact] 283 | public async Task ElapsedUpdatesDuringOperation() 284 | { 285 | var logger = new CollectingLogger(); 286 | var op = logger.Logger.BeginOperation("Test"); 287 | var first = op.Elapsed; 288 | await Task.Delay(10); 289 | var second = op.Elapsed; 290 | await Task.Delay(10); 291 | op.Complete(); 292 | var third = op.Elapsed; 293 | await Task.Delay(10); 294 | var fourth = op.Elapsed; 295 | await Task.Delay(10); 296 | op.Complete(); 297 | var fifth = op.Elapsed; 298 | 299 | Assert.NotEqual(first, second); 300 | Assert.NotEqual(second, third); 301 | Assert.Equal(third, fourth); 302 | Assert.Equal(fourth, fifth); 303 | } 304 | 305 | [Fact] 306 | public async Task LongOperationsAreLoggedAsWarnings() 307 | { 308 | var operationDuration = TimeSpan.FromMilliseconds(100); 309 | 310 | var logger = new CollectingLogger(); 311 | var op = logger.Logger 312 | .OperationAt(LogEventLevel.Debug, warningThreshold: operationDuration) 313 | .Begin("Test"); 314 | 315 | await Task.Delay(operationDuration + operationDuration); 316 | 317 | op.Complete(); 318 | 319 | Assert.Equal(LogEventLevel.Warning, logger.Events.Single().Level); 320 | } 321 | 322 | [Fact] 323 | public async Task LongOperationsDoNotLowerTheOverallLoggingLevel() 324 | { 325 | var operationDuration = TimeSpan.FromMilliseconds(100); 326 | 327 | var logger = new CollectingLogger(); 328 | var op = logger.Logger 329 | .OperationAt(LogEventLevel.Information, LogEventLevel.Error, operationDuration) 330 | .Begin("Test"); 331 | 332 | await Task.Delay(operationDuration + operationDuration); 333 | 334 | op.Abandon(); 335 | 336 | Assert.Equal(LogEventLevel.Error, logger.Events.Single().Level); 337 | } 338 | } 339 | } 340 | -------------------------------------------------------------------------------- /test/SerilogTimings.Tests/SerilogTimings.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net4.8;net6.0 5 | true 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /test/SerilogTimings.Tests/Support/CollectingLogger.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Serilog; 3 | using Serilog.Events; 4 | 5 | namespace SerilogTimings.Tests.Support 6 | { 7 | public class CollectingLogger 8 | { 9 | public ILogger Logger { get; } 10 | public List Events { get; } 11 | 12 | public CollectingLogger() 13 | { 14 | var sink = new CollectionSink(); 15 | 16 | Logger = new LoggerConfiguration() 17 | .MinimumLevel.Is(LevelAlias.Minimum) 18 | .WriteTo.Sink(sink) 19 | .CreateLogger(); 20 | 21 | Events = sink.Events; 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /test/SerilogTimings.Tests/Support/CollectionSink.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Serilog.Core; 3 | using Serilog.Events; 4 | 5 | namespace SerilogTimings.Tests.Support 6 | { 7 | public class CollectionSink : ILogEventSink 8 | { 9 | public List Events { get; } = new List(); 10 | 11 | public void Emit(LogEvent le) 12 | { 13 | Events.Add(le); 14 | } 15 | } 16 | } 17 | --------------------------------------------------------------------------------