├── .editorconfig ├── .gitattributes ├── .gitignore ├── Build.ps1 ├── CHANGES.md ├── LICENSE ├── README.md ├── appveyor.yml ├── assets ├── Serilog.snk └── Serilog.svg ├── serilog-sinks-rollingfile.sln ├── src └── Serilog.Sinks.RollingFile │ ├── Properties │ └── AssemblyInfo.cs │ ├── RollingFileLoggerConfigurationExtensions.cs │ ├── Serilog.Sinks.RollingFile.csproj │ └── Sinks │ └── RollingFile │ ├── Clock.cs │ ├── IOErrors.cs │ ├── RollingFileSink.cs │ ├── RollingLogFile.cs │ ├── Specifier.cs │ └── TemplatedPathRoller.cs └── test └── Serilog.Sinks.RollingFile.Tests ├── Properties └── launchSettings.json ├── RollingFileLoggerConfigurationExtensionsTests.cs ├── RollingFileSinkTests.cs ├── Serilog.Sinks.RollingFile.Tests.csproj ├── Support ├── CollectingSink.cs ├── DelegateDisposable.cs ├── DelegatingEnricher.cs ├── DelegatingSink.cs ├── DisposableLogger.cs ├── DisposeTrackingSink.cs ├── Extensions.cs ├── Some.cs └── TempFolder.cs └── TemplatedPathRollerTests.cs /.editorconfig: -------------------------------------------------------------------------------- 1 | root=true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 4 6 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | 3 | * text=auto 4 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /Build.ps1: -------------------------------------------------------------------------------- 1 | echo "build: Build started" 2 | 3 | Push-Location $PSScriptRoot 4 | 5 | if(Test-Path .\artifacts) { 6 | echo "build: Cleaning .\artifacts" 7 | Remove-Item .\artifacts -Force -Recurse 8 | } 9 | 10 | & dotnet restore --no-cache 11 | 12 | $branch = @{ $true = $env:APPVEYOR_REPO_BRANCH; $false = $(git symbolic-ref --short -q HEAD) }[$env:APPVEYOR_REPO_BRANCH -ne $NULL]; 13 | $revision = @{ $true = "{0:00000}" -f [convert]::ToInt32("0" + $env:APPVEYOR_BUILD_NUMBER, 10); $false = "local" }[$env:APPVEYOR_BUILD_NUMBER -ne $NULL]; 14 | $suffix = @{ $true = ""; $false = "$($branch.Substring(0, [math]::Min(10,$branch.Length)))-$revision"}[$branch -eq "master" -and $revision -ne "local"] 15 | $commitHash = $(git rev-parse --short HEAD) 16 | $buildSuffix = @{ $true = "$($suffix)-$($commitHash)"; $false = "$($branch)-$($commitHash)" }[$suffix -ne ""] 17 | 18 | echo "build: Package version suffix is $suffix" 19 | echo "build: Build version suffix is $buildSuffix" 20 | 21 | foreach ($src in ls src/*) { 22 | Push-Location $src 23 | 24 | echo "build: Packaging project in $src" 25 | 26 | & dotnet build -c Release --version-suffix=$buildSuffix 27 | & dotnet pack -c Release --include-symbols -o ..\..\artifacts --version-suffix=$suffix --no-build 28 | if($LASTEXITCODE -ne 0) { exit 1 } 29 | 30 | Pop-Location 31 | } 32 | 33 | foreach ($test in ls test/*.Tests) { 34 | Push-Location $test 35 | 36 | echo "build: Testing project in $test" 37 | 38 | & dotnet test -c Release 39 | if($LASTEXITCODE -ne 0) { exit 3 } 40 | 41 | Pop-Location 42 | } 43 | 44 | Pop-Location -------------------------------------------------------------------------------- /CHANGES.md: -------------------------------------------------------------------------------- 1 | 2.2.0-* 2 | * #11 - default to UTF-8 encoding **without BOM** 3 | 4 | 2.1.0 5 | * #7 - overload accepting an `ITextFormatter` 6 | 7 | 2.0.0 8 | * Moved to new project 9 | * .NET Core support 10 | -------------------------------------------------------------------------------- /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.Sinks.RollingFile [![Build status](https://ci.appveyor.com/api/projects/status/s9y1u1djdtdwn6u5?svg=true)](https://ci.appveyor.com/project/serilog/serilog-sinks-rollingfile) [![NuGet Version](http://img.shields.io/nuget/v/Serilog.Sinks.RollingFile.svg?style=flat)](https://www.nuget.org/packages/Serilog.Sinks.RollingFile/) [![Documentation](https://img.shields.io/badge/docs-wiki-yellow.svg)](https://github.com/serilog/serilog/wiki) 2 | 3 | Writes [Serilog](https://serilog.net) events to a set of text files, one per day. 4 | 5 | > [!IMPORTANT] 6 | > **Deprecation notice:** the rolling functionality in this sink has been improved and merged into the [_Serilog.Sinks.File_](https://github.com/serilog/serilog-sinks-file) package. New code should use that package instead. 7 | 8 | ### Migrating to `Serilog.Sinks.File` 9 | 10 | First install the new package, and uninstall this one: 11 | 12 | ``` 13 | dotnet add package Serilog.Sinks.File 14 | dotnet remove package Serilog.Sinks.RollingFile 15 | ``` 16 | 17 | Then, replace calls to `RollingFile` with plain `File`, removing the `{Date}` token from the path format, and adding the required rolling interval: 18 | 19 | ```diff 20 | var log = new LoggerConfiguration() 21 | - .WriteTo.RollingFile("log-{Date}.txt") 22 | + .WriteTo.File("log-.txt", rollingInterval: RollingInterval.Day) 23 | .CreateLogger(); 24 | ``` 25 | 26 | See the [`Serilog.Sinks.File` README](https://github.com/serilog/serilog-sinks-file) for more information. 27 | 28 | ### Getting started 29 | 30 | Install the [Serilog.Sinks.RollingFile](https://nuget.org/packages/serilog.sinks.rollingfile) package from NuGet: 31 | 32 | ```powershell 33 | Install-Package Serilog.Sinks.RollingFile 34 | ``` 35 | 36 | To configure the sink in C# code, call `WriteTo.RollingFile()` during logger configuration: 37 | 38 | ```csharp 39 | var log = new LoggerConfiguration() 40 | .WriteTo.RollingFile("log-{Date}.txt") 41 | .CreateLogger(); 42 | 43 | Log.Information("This will be written to the rolling file set"); 44 | ``` 45 | 46 | The filename should include the `{Date}` placeholder, which will be replaced with the date of the events contained in the file. Filenames use the `yyyyMMdd` date format so that files can be ordered using a lexicographic sort: 47 | 48 | ``` 49 | log-20160630.txt 50 | log-20160701.txt 51 | log-20160702.txt 52 | ``` 53 | 54 | > **Important:** By default, only one process may write to a log file at a given time. See _Shared log files_ below for information on multi-process sharing. 55 | 56 | ### Limits 57 | 58 | To avoid bringing down apps with runaway disk usage the rolling file sink **limits file size to 1GB by default**. The limit can be changed or removed using the `fileSizeLimitBytes` parameter. 59 | 60 | ```csharp 61 | .WriteTo.RollingFile("log-{Date}.txt", fileSizeLimitBytes: null) 62 | ``` 63 | 64 | For the same reason, only **the most recent 31 files** are retained by default (i.e. one long month). To change or remove this limit, pass the `retainedFileCountLimit` parameter. 65 | 66 | ```csharp 67 | .WriteTo.RollingFile("log-{Date}.txt", retainedFileCountLimit: null) 68 | ``` 69 | 70 | ### XML `` configuration 71 | 72 | To use the rolling file sink with the [Serilog.Settings.AppSettings](https://github.com/serilog/serilog-settings-appsettings) package, first install that package if you haven't already done so: 73 | 74 | ```powershell 75 | Install-Package Serilog.Settings.AppSettings 76 | ``` 77 | 78 | Instead of configuring the logger in code, call `ReadFrom.AppSettings()`: 79 | 80 | ```csharp 81 | var log = new LoggerConfiguration() 82 | .ReadFrom.AppSettings() 83 | .CreateLogger(); 84 | ``` 85 | 86 | In your application's `App.config` or `Web.config` file, specify the rolling file sink assembly and required path format under the `` node: 87 | 88 | ```xml 89 | 90 | 91 | 92 | 93 | ``` 94 | 95 | The parameters that can be set through the `serilog:write-to:RollingFile` keys are the method parameters accepted by the `WriteTo.RollingFile()` configuration method. This means, for example, that the `fileSizeLimitBytes` parameter can be set with: 96 | 97 | ```xml 98 | 99 | ``` 100 | 101 | Omitting the `value` will set the parameter to `null`: 102 | 103 | ```xml 104 | 105 | ``` 106 | 107 | In XML and JSON configuration formats, environment variables can be used in setting values. This means, for instance, that the log file path can be based on `TMP` or `APPDATA`: 108 | 109 | ```xml 110 | 111 | ``` 112 | 113 | ### JSON `appsettings.json` configuration 114 | 115 | To use the rolling file sink with _Microsoft.Extensions.Configuration_, for example with ASP.NET Core or .NET Core, use the [Serilog.Settings.Configuration](https://github.com/serilog/serilog-settings-configuration) package. First install that package if you have not already done so: 116 | 117 | ```powershell 118 | Install-Package Serilog.Settings.Configuration 119 | ``` 120 | 121 | Instead of configuring the rolling file directly in code, call `ReadFrom.Configuration()`: 122 | 123 | ```csharp 124 | var configuration = new ConfigurationBuilder() 125 | .AddJsonFile("appsettings.json") 126 | .Build(); 127 | 128 | var logger = new LoggerConfiguration() 129 | .ReadFrom.Configuration(configuration) 130 | .CreateLogger(); 131 | ``` 132 | 133 | In your `appsettings.json` file, under the `Serilog` node, : 134 | 135 | ```json 136 | { 137 | "Serilog": { 138 | "WriteTo": [ 139 | { "Name": "RollingFile", "Args": { "pathFormat": "log-{Date}.txt" } } 140 | ] 141 | } 142 | } 143 | ``` 144 | 145 | See the XML `` example above for a discussion of available `Args` options. 146 | 147 | ### Controlling event formatting 148 | 149 | The rolling file sink creates events in a fixed text format by default: 150 | 151 | ``` 152 | 2016-07-06 09:02:17.148 +10:00 [Information] HTTP "GET" "/" responded 200 in 1994 ms 153 | ``` 154 | 155 | The format is controlled using an _output template_, which the rolling file configuration method accepts as an `outputTemplate` parameter. 156 | 157 | The default format above corresponds to an output template like: 158 | 159 | ```csharp 160 | .WriteTo.RollingFile("log-{Date}.txt", 161 | outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}") 162 | ``` 163 | 164 | ##### JSON event formatting 165 | 166 | To write events to the file in an alternative format such as JSON, pass an `ITextFormatter` as the first argument: 167 | 168 | ```csharp 169 | .WriteTo.RollingFile(new JsonFormatter(), "log-{Date}.txt") 170 | ``` 171 | 172 | ### Shared log files 173 | 174 | To enable multi-process shared log files, set `shared` to `true`: 175 | 176 | ```csharp 177 | .WriteTo.RollingFile("log-{Date}.txt", shared: true) 178 | ``` 179 | 180 | ### Filename format specifiers 181 | 182 | The sink supports three different filename format specifiers: 183 | 184 | * `{Date}` Creates a file per day. Filenames use the `yyyyMMdd` format. 185 | * `{Hour}` Creates a file per hour. Filenames use the `yyyyMMddHH` format. 186 | * `{HalfHour}` Creates a file per half hour. Filenames use the `yyyyMMddHHmm` format. 187 | 188 | If a log file path is provided without one of the specifiers above, `{Date}` will be inserted by default. 189 | 190 | ### Performance 191 | 192 | By default, the rolling file sink will flush each event written through it to disk. To improve write performance, specifying `buffered: true` will permit the underlying stream to buffer writes. 193 | 194 | The [Serilog.Sinks.Async](https://github.com/serilog/serilog-sinks-async) package can be used to wrap the rolling file sink and perform all disk access on a background worker thread. 195 | 196 | ### Alternatives 197 | 198 | The default rolling file sink is designed to suit most applications. So that we can keep it maintainable and reliable, it does not provide a large range of optional behavior. Check out alternative implemementations like [this one](https://github.com/BedeGaming/sinks-rollingfile) if your needs aren't met by the default version. 199 | 200 | _Copyright © 2016 Serilog Contributors - Provided under the [Apache License, Version 2.0](http://apache.org/licenses/LICENSE-2.0.html)._ 201 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | version: '{build}' 2 | skip_tags: true 3 | image: Visual Studio 2022 4 | configuration: Release 5 | test: off 6 | build_script: 7 | - ps: ./Build.ps1 8 | artifacts: 9 | - path: artifacts/Serilog.*.nupkg 10 | deploy: 11 | - provider: NuGet 12 | api_key: 13 | secure: nvZ/z+pMS91b3kG4DgfES5AcmwwGoBYQxr9kp4XiJHj25SAlgdIxFx++1N0lFH2x 14 | skip_symbols: true 15 | on: 16 | branch: /^(master|dev)$/ 17 | - provider: GitHub 18 | auth_token: 19 | secure: p4LpVhBKxGS5WqucHxFQ5c7C8cP74kbNB0Z8k9Oxx/PMaDQ1+ibmoexNqVU5ZlmX 20 | artifact: /Serilog.*\.nupkg/ 21 | tag: v$(appveyor_build_version) 22 | on: 23 | branch: master 24 | -------------------------------------------------------------------------------- /assets/Serilog.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/serilog/serilog-sinks-rollingfile/06d3f0e3b95a8dd5d9af5a3975d28385a1211ad0/assets/Serilog.snk -------------------------------------------------------------------------------- /assets/Serilog.svg: -------------------------------------------------------------------------------- 1 | 2 | image/svg+xml 44 | 55 | 56 | 57 | 70 | 75 | 79 | 83 | 87 | 91 | 95 | 99 | 103 | 110 | 117 | 123 | 128 | 131 | 134 | 137 | 140 | 143 | 146 | 149 | 156 | 163 | -------------------------------------------------------------------------------- /serilog-sinks-rollingfile.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26430.14 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{037440DE-440B-4129-9F7A-09B42D00397E}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "assets", "assets", "{E9D1B5E1-DEB9-4A04-8BAB-24EC7240ADAF}" 9 | ProjectSection(SolutionItems) = preProject 10 | appveyor.yml = appveyor.yml 11 | Build.ps1 = Build.ps1 12 | NuGet.Config = NuGet.Config 13 | README.md = README.md 14 | assets\Serilog.snk = assets\Serilog.snk 15 | EndProjectSection 16 | EndProject 17 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{04579757-7974-476C-A175-688A04164032}" 18 | EndProject 19 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.Sinks.RollingFile", "src\Serilog.Sinks.RollingFile\Serilog.Sinks.RollingFile.csproj", "{A3E6E5B4-995F-4C3D-9673-A4B6000F4E21}" 20 | EndProject 21 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.Sinks.RollingFile.Tests", "test\Serilog.Sinks.RollingFile.Tests\Serilog.Sinks.RollingFile.Tests.csproj", "{3C2D8E01-5580-426A-BDD9-EC59CD98E618}" 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 | {A3E6E5B4-995F-4C3D-9673-A4B6000F4E21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 30 | {A3E6E5B4-995F-4C3D-9673-A4B6000F4E21}.Debug|Any CPU.Build.0 = Debug|Any CPU 31 | {A3E6E5B4-995F-4C3D-9673-A4B6000F4E21}.Release|Any CPU.ActiveCfg = Release|Any CPU 32 | {A3E6E5B4-995F-4C3D-9673-A4B6000F4E21}.Release|Any CPU.Build.0 = Release|Any CPU 33 | {3C2D8E01-5580-426A-BDD9-EC59CD98E618}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 34 | {3C2D8E01-5580-426A-BDD9-EC59CD98E618}.Debug|Any CPU.Build.0 = Debug|Any CPU 35 | {3C2D8E01-5580-426A-BDD9-EC59CD98E618}.Release|Any CPU.ActiveCfg = Release|Any CPU 36 | {3C2D8E01-5580-426A-BDD9-EC59CD98E618}.Release|Any CPU.Build.0 = Release|Any CPU 37 | EndGlobalSection 38 | GlobalSection(SolutionProperties) = preSolution 39 | HideSolutionNode = FALSE 40 | EndGlobalSection 41 | GlobalSection(NestedProjects) = preSolution 42 | {A3E6E5B4-995F-4C3D-9673-A4B6000F4E21} = {037440DE-440B-4129-9F7A-09B42D00397E} 43 | {3C2D8E01-5580-426A-BDD9-EC59CD98E618} = {04579757-7974-476C-A175-688A04164032} 44 | EndGlobalSection 45 | EndGlobal 46 | -------------------------------------------------------------------------------- /src/Serilog.Sinks.RollingFile/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | using System.Runtime.CompilerServices; 4 | 5 | [assembly: AssemblyVersion("2.0.0.0")] 6 | 7 | [assembly: CLSCompliant(true)] 8 | 9 | [assembly: InternalsVisibleTo("Serilog.Sinks.RollingFile.Tests, PublicKey=" + 10 | "0024000004800000940000000602000000240000525341310004000001000100fb8d13fd344a1c" + 11 | "6fe0fe83ef33c1080bf30690765bc6eb0df26ebfdf8f21670c64265b30db09f73a0dea5b3db4c9" + 12 | "d18dbf6d5a25af5ce9016f281014d79dc3b4201ac646c451830fc7e61a2dfd633d34c39f87b818" + 13 | "94191652df5ac63cc40c77f3542f702bda692e6e8a9158353df189007a49da0f3cfd55eb250066" + 14 | "b19485ec")] 15 | -------------------------------------------------------------------------------- /src/Serilog.Sinks.RollingFile/RollingFileLoggerConfigurationExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2016 Serilog 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 System; 16 | using Serilog.Configuration; 17 | using Serilog.Core; 18 | using Serilog.Events; 19 | using Serilog.Formatting; 20 | using Serilog.Formatting.Display; 21 | using Serilog.Sinks.File; 22 | using Serilog.Sinks.RollingFile; 23 | 24 | namespace Serilog 25 | { 26 | /// 27 | /// Extends with rolling file configuration methods. 28 | /// 29 | public static class RollingFileLoggerConfigurationExtensions 30 | { 31 | const int DefaultRetainedFileCountLimit = 31; // A long month of logs 32 | const long DefaultFileSizeLimitBytes = 1L * 1024 * 1024 * 1024; 33 | const string DefaultOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"; 34 | 35 | /// 36 | /// Write log events to a series of files. Each file will be named according to 37 | /// the date of the first log entry written to it. Only simple date-based rolling is 38 | /// currently supported. 39 | /// 40 | /// Logger sink configuration. 41 | /// String describing the location of the log files, 42 | /// with {Date} in the place of the file date. E.g. "Logs\myapp-{Date}.log" will result in log 43 | /// files such as "Logs\myapp-2013-10-20.log", "Logs\myapp-2013-10-21.log" and so on. 44 | /// The minimum level for 45 | /// events passed through the sink. Ignored when is specified. 46 | /// A switch allowing the pass-through minimum level 47 | /// to be changed at runtime. 48 | /// A message template describing the format used to write to the sink. 49 | /// the default is "{Timestamp} [{Level}] {Message}{NewLine}{Exception}". 50 | /// Supplies culture-specific formatting information, or null. 51 | /// The maximum size, in bytes, to which any single log file will be allowed to grow. 52 | /// For unrestricted growth, pass null. The default is 1 GB. 53 | /// The maximum number of log files that will be retained, 54 | /// including the current log file. For unlimited retention, pass null. The default is 31. 55 | /// Indicates if flushing to the output file can be buffered or not. The default 56 | /// is false. 57 | /// Allow the log files to be shared by multiple processes. The default is false. 58 | /// If provided, a full disk flush will be performed periodically at the specified interval. 59 | /// Configuration object allowing method chaining. 60 | /// The file will be written using the UTF-8 encoding without a byte-order mark. 61 | public static LoggerConfiguration RollingFile( 62 | this LoggerSinkConfiguration sinkConfiguration, 63 | string pathFormat, 64 | LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, 65 | string outputTemplate = DefaultOutputTemplate, 66 | IFormatProvider formatProvider = null, 67 | long? fileSizeLimitBytes = DefaultFileSizeLimitBytes, 68 | int? retainedFileCountLimit = DefaultRetainedFileCountLimit, 69 | LoggingLevelSwitch levelSwitch = null, 70 | bool buffered = false, 71 | bool shared = false, 72 | TimeSpan? flushToDiskInterval = null) 73 | { 74 | var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider); 75 | return RollingFile(sinkConfiguration, formatter, pathFormat, restrictedToMinimumLevel, fileSizeLimitBytes, 76 | retainedFileCountLimit, levelSwitch, buffered, shared, flushToDiskInterval); 77 | } 78 | 79 | /// 80 | /// Write log events to a series of files. Each file will be named according to 81 | /// the date of the first log entry written to it. Only simple date-based rolling is 82 | /// currently supported. 83 | /// 84 | /// Logger sink configuration. 85 | /// Formatter to control how events are rendered into the file. To control 86 | /// plain text formatting, use the overload that accepts an output template instead. 87 | /// String describing the location of the log files, 88 | /// with {Date} in the place of the file date. E.g. "Logs\myapp-{Date}.log" will result in log 89 | /// files such as "Logs\myapp-2013-10-20.log", "Logs\myapp-2013-10-21.log" and so on. 90 | /// The minimum level for 91 | /// events passed through the sink. Ignored when is specified. 92 | /// A switch allowing the pass-through minimum level 93 | /// to be changed at runtime. 94 | /// The maximum size, in bytes, to which any single log file will be allowed to grow. 95 | /// For unrestricted growth, pass null. The default is 1 GB. 96 | /// The maximum number of log files that will be retained, 97 | /// including the current log file. For unlimited retention, pass null. The default is 31. 98 | /// Indicates if flushing to the output file can be buffered or not. The default 99 | /// is false. 100 | /// Allow the log files to be shared by multiple processes. The default is false. 101 | /// If provided, a full disk flush will be performed periodically at the specified interval. 102 | /// Configuration object allowing method chaining. 103 | /// The file will be written using the UTF-8 encoding without a byte-order mark. 104 | public static LoggerConfiguration RollingFile( 105 | this LoggerSinkConfiguration sinkConfiguration, 106 | ITextFormatter formatter, 107 | string pathFormat, 108 | LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, 109 | long? fileSizeLimitBytes = DefaultFileSizeLimitBytes, 110 | int? retainedFileCountLimit = DefaultRetainedFileCountLimit, 111 | LoggingLevelSwitch levelSwitch = null, 112 | bool buffered = false, 113 | bool shared = false, 114 | TimeSpan? flushToDiskInterval = null) 115 | { 116 | if (sinkConfiguration == null) throw new ArgumentNullException(nameof(sinkConfiguration)); 117 | if (formatter == null) throw new ArgumentNullException(nameof(formatter)); 118 | 119 | if (shared && buffered) 120 | throw new ArgumentException("Buffered writes are not available when file sharing is enabled.", nameof(buffered)); 121 | 122 | ILogEventSink sink = new RollingFileSink(pathFormat, formatter, fileSizeLimitBytes, retainedFileCountLimit, buffered: buffered, shared: shared); 123 | 124 | if (flushToDiskInterval.HasValue) 125 | { 126 | sink = new PeriodicFlushToDiskSink(sink, flushToDiskInterval.Value); 127 | } 128 | 129 | return sinkConfiguration.Sink(sink, restrictedToMinimumLevel, levelSwitch); 130 | } 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/Serilog.Sinks.RollingFile/Serilog.Sinks.RollingFile.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | The rolling file sink for Serilog 5 | 3.3.1 6 | Serilog Contributors 7 | net45;netstandard1.3 8 | true 9 | true 10 | Serilog.Sinks.RollingFile 11 | Serilog 12 | ../../assets/Serilog.snk 13 | true 14 | true 15 | Serilog.Sinks.RollingFile 16 | serilog;file;io;rolling 17 | https://serilog.net/images/serilog-sink-nuget.png 18 | https://serilog.net 19 | https://www.apache.org/licenses/LICENSE-2.0 20 | false 21 | 22 | true 23 | True 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | $(DefineConstants);HRESULTS 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /src/Serilog.Sinks.RollingFile/Sinks/RollingFile/Clock.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2016 Serilog 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 System; 16 | 17 | namespace Serilog.Sinks.RollingFile 18 | { 19 | static class Clock 20 | { 21 | static Func _dateTimeNow = () => DateTime.Now; 22 | 23 | [ThreadStatic] 24 | static DateTime _testDateTimeNow; 25 | 26 | public static DateTime DateTimeNow => _dateTimeNow(); 27 | 28 | // Time is set per thread to support parallel 29 | // If any thread uses the clock in test mode, all threads 30 | // must use it in test mode; once set to test mode only 31 | // terminating the application returns it to normal use. 32 | public static void SetTestDateTimeNow(DateTime now) 33 | { 34 | _testDateTimeNow = now; 35 | _dateTimeNow = () => _testDateTimeNow; 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /src/Serilog.Sinks.RollingFile/Sinks/RollingFile/IOErrors.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2016 Serilog 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 System.IO; 16 | 17 | namespace Serilog.Sinks.RollingFile 18 | { 19 | static class IOErrors 20 | { 21 | public static bool IsLockedFile(IOException ex) 22 | { 23 | #if HRESULTS 24 | var errorCode = System.Runtime.InteropServices.Marshal.GetHRForException(ex) & ((1 << 16) - 1); 25 | return errorCode == 32 || errorCode == 33; 26 | #else 27 | return true; 28 | #endif 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Serilog.Sinks.RollingFile/Sinks/RollingFile/RollingFileSink.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2016 Serilog 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 System; 16 | using System.IO; 17 | using System.Linq; 18 | using System.Text; 19 | using Serilog.Core; 20 | using Serilog.Debugging; 21 | using Serilog.Events; 22 | using Serilog.Formatting; 23 | using Serilog.Sinks.File; 24 | 25 | namespace Serilog.Sinks.RollingFile 26 | { 27 | /// 28 | /// Write log events to a series of files. Each file will be named according to 29 | /// the date of the first log entry written to it. Only simple date-based rolling is 30 | /// currently supported. 31 | /// 32 | public sealed class RollingFileSink : ILogEventSink, IFlushableFileSink, IDisposable 33 | { 34 | readonly TemplatedPathRoller _roller; 35 | readonly ITextFormatter _textFormatter; 36 | readonly long? _fileSizeLimitBytes; 37 | readonly int? _retainedFileCountLimit; 38 | readonly Encoding _encoding; 39 | readonly bool _buffered; 40 | readonly bool _shared; 41 | readonly object _syncRoot = new object(); 42 | 43 | bool _isDisposed; 44 | DateTime? _nextCheckpoint; 45 | ILogEventSink _currentFile; 46 | 47 | /// Construct a . 48 | /// String describing the location of the log files, 49 | /// with {Date} in the place of the file date. E.g. "Logs\myapp-{Date}.log" will result in log 50 | /// files such as "Logs\myapp-2013-10-20.log", "Logs\myapp-2013-10-21.log" and so on. 51 | /// Formatter used to convert log events to text. 52 | /// The maximum size, in bytes, to which a log file will be allowed to grow. 53 | /// For unrestricted growth, pass null. The default is 1 GB. 54 | /// The maximum number of log files that will be retained, 55 | /// including the current log file. For unlimited retention, pass null. The default is 31. 56 | /// Character encoding used to write the text file. The default is UTF-8 without BOM. 57 | /// Indicates if flushing to the output file can be buffered or not. The default 58 | /// is false. 59 | /// Allow the log files to be shared by multiple processes. The default is false. 60 | /// Configuration object allowing method chaining. 61 | /// The file will be written using the UTF-8 character set. 62 | public RollingFileSink(string pathFormat, 63 | ITextFormatter textFormatter, 64 | long? fileSizeLimitBytes, 65 | int? retainedFileCountLimit, 66 | Encoding encoding = null, 67 | bool buffered = false, 68 | bool shared = false) 69 | { 70 | if (pathFormat == null) throw new ArgumentNullException(nameof(pathFormat)); 71 | if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 0) throw new ArgumentException("Negative value provided; file size limit must be non-negative"); 72 | if (retainedFileCountLimit.HasValue && retainedFileCountLimit < 1) throw new ArgumentException("Zero or negative value provided; retained file count limit must be at least 1"); 73 | 74 | _roller = new TemplatedPathRoller(pathFormat); 75 | _textFormatter = textFormatter; 76 | _fileSizeLimitBytes = fileSizeLimitBytes; 77 | _retainedFileCountLimit = retainedFileCountLimit; 78 | _encoding = encoding; 79 | _buffered = buffered; 80 | _shared = shared; 81 | } 82 | 83 | /// 84 | /// Emit the provided log event to the sink. 85 | /// 86 | /// The log event to write. 87 | /// Events that come in out-of-order (e.g. around the rollovers) 88 | /// may end up written to a later file than their timestamp 89 | /// would indicate. 90 | public void Emit(LogEvent logEvent) 91 | { 92 | if (logEvent == null) throw new ArgumentNullException(nameof(logEvent)); 93 | 94 | lock (_syncRoot) 95 | { 96 | if (_isDisposed) throw new ObjectDisposedException("The rolling log file has been disposed."); 97 | 98 | AlignCurrentFileTo(Clock.DateTimeNow); 99 | 100 | // If the file was unable to be opened on the last attempt, it will remain 101 | // null until the next checkpoint passes, at which time another attempt will be made to 102 | // open it. 103 | _currentFile?.Emit(logEvent); 104 | } 105 | } 106 | 107 | void AlignCurrentFileTo(DateTime now) 108 | { 109 | if (!_nextCheckpoint.HasValue) 110 | { 111 | OpenFile(now); 112 | } 113 | else if (now >= _nextCheckpoint.Value) 114 | { 115 | CloseFile(); 116 | OpenFile(now); 117 | } 118 | } 119 | 120 | void OpenFile(DateTime now) 121 | { 122 | var currentCheckpoint = _roller.GetCurrentCheckpoint(now); 123 | 124 | // We only take one attempt at it because repeated failures 125 | // to open log files REALLY slow an app down. 126 | _nextCheckpoint = _roller.GetNextCheckpoint(now); 127 | 128 | var existingFiles = Enumerable.Empty(); 129 | try 130 | { 131 | existingFiles = Directory.GetFiles(_roller.LogFileDirectory, _roller.DirectorySearchPattern) 132 | .Select(Path.GetFileName); 133 | } 134 | catch (DirectoryNotFoundException) { } 135 | 136 | var latestForThisCheckpoint = _roller 137 | .SelectMatches(existingFiles) 138 | .Where(m => m.DateTime == currentCheckpoint) 139 | .OrderByDescending(m => m.SequenceNumber) 140 | .FirstOrDefault(); 141 | 142 | var sequence = latestForThisCheckpoint != null ? latestForThisCheckpoint.SequenceNumber : 0; 143 | 144 | const int maxAttempts = 3; 145 | for (var attempt = 0; attempt < maxAttempts; attempt++) 146 | { 147 | string path; 148 | _roller.GetLogFilePath(now, sequence, out path); 149 | 150 | try 151 | { 152 | _currentFile = _shared ? 153 | (ILogEventSink)new SharedFileSink(path, _textFormatter, _fileSizeLimitBytes, _encoding) : 154 | new FileSink(path, _textFormatter, _fileSizeLimitBytes, _encoding, _buffered); 155 | } 156 | catch (IOException ex) 157 | { 158 | if (IOErrors.IsLockedFile(ex)) 159 | { 160 | SelfLog.WriteLine("Rolling file target {0} was locked, attempting to open next in sequence (attempt {1})", path, attempt + 1); 161 | sequence++; 162 | continue; 163 | } 164 | 165 | throw; 166 | } 167 | 168 | ApplyRetentionPolicy(path); 169 | return; 170 | } 171 | } 172 | 173 | void ApplyRetentionPolicy(string currentFilePath) 174 | { 175 | if (_retainedFileCountLimit == null) return; 176 | 177 | var currentFileName = Path.GetFileName(currentFilePath); 178 | 179 | // We consider the current file to exist, even if nothing's been written yet, 180 | // because files are only opened on response to an event being processed. 181 | var potentialMatches = Directory.GetFiles(_roller.LogFileDirectory, _roller.DirectorySearchPattern) 182 | .Select(Path.GetFileName) 183 | .Union(new [] { currentFileName }); 184 | 185 | var newestFirst = _roller 186 | .SelectMatches(potentialMatches) 187 | .OrderByDescending(m => m.DateTime) 188 | .ThenByDescending(m => m.SequenceNumber) 189 | .Select(m => m.Filename); 190 | 191 | var toRemove = newestFirst 192 | .Where(n => StringComparer.OrdinalIgnoreCase.Compare(currentFileName, n) != 0) 193 | .Skip(_retainedFileCountLimit.Value - 1) 194 | .ToList(); 195 | 196 | foreach (var obsolete in toRemove) 197 | { 198 | var fullPath = Path.Combine(_roller.LogFileDirectory, obsolete); 199 | try 200 | { 201 | System.IO.File.Delete(fullPath); 202 | } 203 | catch (Exception ex) 204 | { 205 | SelfLog.WriteLine("Error {0} while removing obsolete file {1}", ex, fullPath); 206 | } 207 | } 208 | } 209 | 210 | /// 211 | /// Performs application-defined tasks associated with freeing, releasing, or 212 | /// resetting unmanaged resources. 213 | /// 214 | public void Dispose() 215 | { 216 | lock (_syncRoot) 217 | { 218 | if (_currentFile == null) return; 219 | CloseFile(); 220 | _isDisposed = true; 221 | } 222 | } 223 | 224 | void CloseFile() 225 | { 226 | if (_currentFile != null) 227 | { 228 | (_currentFile as IDisposable)?.Dispose(); 229 | _currentFile = null; 230 | } 231 | 232 | _nextCheckpoint = null; 233 | } 234 | 235 | /// 236 | public void FlushToDisk() 237 | { 238 | lock (_syncRoot) 239 | { 240 | (_currentFile as IFlushableFileSink)?.FlushToDisk(); 241 | } 242 | } 243 | } 244 | } 245 | -------------------------------------------------------------------------------- /src/Serilog.Sinks.RollingFile/Sinks/RollingFile/RollingLogFile.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2016 Serilog 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 System; 16 | 17 | namespace Serilog.Sinks.RollingFile 18 | { 19 | class RollingLogFile 20 | { 21 | public RollingLogFile(string filename, DateTime dateTime, int sequenceNumber) 22 | { 23 | Filename = filename; 24 | DateTime = dateTime; 25 | SequenceNumber = sequenceNumber; 26 | } 27 | 28 | public string Filename { get; } 29 | 30 | public DateTime DateTime { get; } 31 | 32 | public int SequenceNumber { get; } 33 | } 34 | } -------------------------------------------------------------------------------- /src/Serilog.Sinks.RollingFile/Sinks/RollingFile/Specifier.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2016 Serilog 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 System; 16 | using System.Linq; 17 | 18 | namespace Serilog.Sinks.RollingFile 19 | { 20 | class Specifier 21 | { 22 | public static readonly Specifier Date = new Specifier("Date", "yyyyMMdd", TimeSpan.FromDays(1)); 23 | public static readonly Specifier Hour = new Specifier("Hour", "yyyyMMddHH", TimeSpan.FromHours(1)); 24 | public static readonly Specifier HalfHour = new Specifier("HalfHour", "yyyyMMddHHmm", TimeSpan.FromMinutes(30)); 25 | 26 | public string Token { get; } 27 | public string Format { get; } 28 | public TimeSpan Interval { get; } 29 | 30 | Specifier(string name, string format, TimeSpan interval) 31 | { 32 | if (name == null) throw new ArgumentNullException(nameof(name)); 33 | if (format == null) throw new ArgumentNullException(nameof(format)); 34 | 35 | Token = "{" + name + "}"; 36 | Format = format; 37 | Interval = interval; 38 | } 39 | 40 | public DateTime GetCurrentCheckpoint(DateTime instant) 41 | { 42 | if (this == Hour) 43 | { 44 | return instant.Date.AddHours(instant.Hour); 45 | } 46 | 47 | if (this == HalfHour) 48 | { 49 | var hour = instant.Date.AddHours(instant.Hour); 50 | if (instant.Minute >= 30) 51 | return hour.AddMinutes(30); 52 | return hour; 53 | } 54 | 55 | return instant.Date; 56 | } 57 | 58 | public DateTime GetNextCheckpoint(DateTime instant) => GetCurrentCheckpoint(instant).Add(Interval); 59 | 60 | public static bool TryGetSpecifier(string pathTemplate, out Specifier specifier) 61 | { 62 | if (pathTemplate == null) throw new ArgumentNullException(nameof(pathTemplate)); 63 | 64 | var specifiers = new[] { HalfHour, Hour, Date }.Where(s => pathTemplate.Contains(s.Token)).ToArray(); 65 | 66 | if (specifiers.Length > 1) 67 | throw new ArgumentException("Only one interval specifier can be used in a rolling log file path.", nameof(pathTemplate)); 68 | 69 | specifier = specifiers.FirstOrDefault(); 70 | return specifier != null; 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/Serilog.Sinks.RollingFile/Sinks/RollingFile/TemplatedPathRoller.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2016 Serilog 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 System; 16 | using System.Collections.Generic; 17 | using System.Globalization; 18 | using System.IO; 19 | using System.Text.RegularExpressions; 20 | 21 | namespace Serilog.Sinks.RollingFile 22 | { 23 | // Rolls files based on the current date, using a path 24 | // formatting pattern like: 25 | // Logs/log-{Date}.txt 26 | // 27 | class TemplatedPathRoller 28 | { 29 | const string DefaultSeparator = "-"; 30 | 31 | const string SpecifierMatchGroup = "specifier"; 32 | const string SequenceNumberMatchGroup = "sequence"; 33 | 34 | readonly string _pathTemplate; 35 | readonly Regex _filenameMatcher; 36 | readonly Specifier _specifier = null; 37 | 38 | public TemplatedPathRoller(string pathTemplate) 39 | { 40 | if (pathTemplate == null) throw new ArgumentNullException(nameof(pathTemplate)); 41 | 42 | var directory = Path.GetDirectoryName(pathTemplate); 43 | if (string.IsNullOrEmpty(directory)) 44 | directory = Directory.GetCurrentDirectory(); 45 | 46 | Specifier directorySpecifier; 47 | if (Specifier.TryGetSpecifier(directory, out directorySpecifier)) 48 | throw new ArgumentException($"The {directorySpecifier.Token} specifier cannot form part of the directory name."); 49 | 50 | directory = Path.GetFullPath(directory); 51 | 52 | var filenameTemplate = Path.GetFileName(pathTemplate); 53 | if (!Specifier.TryGetSpecifier(filenameTemplate, out _specifier)) 54 | { 55 | _specifier = Specifier.Date; 56 | filenameTemplate = Path.GetFileNameWithoutExtension(filenameTemplate) + DefaultSeparator + 57 | _specifier.Token + Path.GetExtension(filenameTemplate); 58 | } 59 | 60 | var indexOfSpecifier = filenameTemplate.IndexOf(_specifier.Token, StringComparison.Ordinal); 61 | var prefix = filenameTemplate.Substring(0, indexOfSpecifier); 62 | var suffix = filenameTemplate.Substring(indexOfSpecifier + _specifier.Token.Length); 63 | _filenameMatcher = new Regex( 64 | "^" + 65 | Regex.Escape(prefix) + 66 | "(?<" + SpecifierMatchGroup + ">\\d{" + _specifier.Format.Length + "})" + 67 | "(?<" + SequenceNumberMatchGroup + ">_[0-9]{3,}){0,1}" + 68 | Regex.Escape(suffix) + 69 | "$"); 70 | 71 | DirectorySearchPattern = filenameTemplate.Replace(_specifier.Token, "*"); 72 | LogFileDirectory = directory; 73 | _pathTemplate = Path.Combine(LogFileDirectory, filenameTemplate); 74 | } 75 | 76 | public string LogFileDirectory { get; } 77 | 78 | public string DirectorySearchPattern { get; } 79 | 80 | public void GetLogFilePath(DateTime date, int sequenceNumber, out string path) 81 | { 82 | var currentCheckpoint = GetCurrentCheckpoint(date); 83 | 84 | var tok = currentCheckpoint.ToString(_specifier.Format, CultureInfo.InvariantCulture); 85 | 86 | if (sequenceNumber != 0) 87 | tok += "_" + sequenceNumber.ToString("000", CultureInfo.InvariantCulture); 88 | 89 | path = _pathTemplate.Replace(_specifier.Token, tok); 90 | } 91 | 92 | public IEnumerable SelectMatches(IEnumerable filenames) 93 | { 94 | foreach (var filename in filenames) 95 | { 96 | var match = _filenameMatcher.Match(filename); 97 | if (match.Success) 98 | { 99 | var inc = 0; 100 | var incGroup = match.Groups[SequenceNumberMatchGroup]; 101 | if (incGroup.Captures.Count != 0) 102 | { 103 | var incPart = incGroup.Captures[0].Value.Substring(1); 104 | inc = int.Parse(incPart, CultureInfo.InvariantCulture); 105 | } 106 | 107 | DateTime dateTime; 108 | var dateTimePart = match.Groups[SpecifierMatchGroup].Captures[0].Value; 109 | if (!DateTime.TryParseExact( 110 | dateTimePart, 111 | _specifier.Format, 112 | CultureInfo.InvariantCulture, 113 | DateTimeStyles.None, 114 | out dateTime)) 115 | continue; 116 | 117 | yield return new RollingLogFile(filename, dateTime, inc); 118 | } 119 | } 120 | } 121 | 122 | public DateTime GetCurrentCheckpoint(DateTime instant) => _specifier.GetCurrentCheckpoint(instant); 123 | 124 | public DateTime GetNextCheckpoint(DateTime instant) => _specifier.GetNextCheckpoint(instant); 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /test/Serilog.Sinks.RollingFile.Tests/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "test": { 4 | "commandName": "test" 5 | }, 6 | "test-dnxcore50": { 7 | "commandName": "test", 8 | "sdkVersion": "dnx-coreclr-win-x86.1.0.0-rc1-final" 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /test/Serilog.Sinks.RollingFile.Tests/RollingFileLoggerConfigurationExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using Serilog.Sinks.RollingFile.Tests.Support; 4 | using Xunit; 5 | 6 | namespace Serilog.Sinks.RollingFile.Tests 7 | { 8 | public class RollingFileLoggerConfigurationExtensionsTests 9 | { 10 | [Fact] 11 | public void BufferingIsNotAvailableWhenSharingEnabled() 12 | { 13 | Assert.Throws(() => 14 | new LoggerConfiguration() 15 | .WriteTo.RollingFile("logs", buffered: true, shared: true)); 16 | } 17 | 18 | [Fact] 19 | public void SinkCanBeConfiguredAndDisposedWhenFlushIntervalSpecified() 20 | { 21 | using (var temp = TempFolder.ForCaller()) 22 | using (var logger = new LoggerConfiguration() 23 | .WriteTo.RollingFile(temp.AllocateFilename(), flushToDiskInterval: TimeSpan.FromMilliseconds(500)) 24 | .CreateLogger()) 25 | { 26 | logger.Information("Hello, rolling file."); 27 | Thread.Sleep(TimeSpan.FromSeconds(1)); 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /test/Serilog.Sinks.RollingFile.Tests/RollingFileSinkTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Reflection; 5 | using Xunit; 6 | using Serilog.Events; 7 | using Serilog.Sinks.RollingFile.Tests.Support; 8 | using Serilog.Configuration; 9 | 10 | namespace Serilog.Sinks.RollingFile.Tests 11 | { 12 | public class RollingFileSinkTests 13 | { 14 | [Fact] 15 | public void LogEventsAreEmittedToTheFileNamedAccordingToTheEventTimestamp() 16 | { 17 | TestRollingEventSequence(Some.InformationEvent()); 18 | } 19 | 20 | [Fact] 21 | public void EventsAreWrittenWhenSharingIsEnabled() 22 | { 23 | TestRollingEventSequence( 24 | (pf, wt) => wt.RollingFile(pf, shared: true), 25 | new[] { Some.InformationEvent() }); 26 | } 27 | 28 | [Fact] 29 | public void EventsAreWrittenWhenBufferingIsEnabled() 30 | { 31 | TestRollingEventSequence( 32 | (pf, wt) => wt.RollingFile(pf, buffered: true), 33 | new[] { Some.InformationEvent() }); 34 | } 35 | 36 | [Fact] 37 | public void EventsAreWrittenWhenDiskFlushingIsEnabled() 38 | { 39 | // Doesn't test flushing, but ensures we haven't broken basic logging 40 | TestRollingEventSequence( 41 | (pf, wt) => wt.RollingFile(pf, flushToDiskInterval: TimeSpan.FromMilliseconds(50)), 42 | new[] { Some.InformationEvent() }); 43 | } 44 | 45 | [Fact] 46 | public void WhenTheDateChangesTheCorrectFileIsWritten() 47 | { 48 | var e1 = Some.InformationEvent(); 49 | var e2 = Some.InformationEvent(e1.Timestamp.AddDays(1)); 50 | TestRollingEventSequence(e1, e2); 51 | } 52 | 53 | [Fact] 54 | public void WhenRetentionCountIsSetOldFilesAreDeleted() 55 | { 56 | LogEvent e1 = Some.InformationEvent(), 57 | e2 = Some.InformationEvent(e1.Timestamp.AddDays(1)), 58 | e3 = Some.InformationEvent(e2.Timestamp.AddDays(5)); 59 | 60 | TestRollingEventSequence( 61 | (pf, wt) => wt.RollingFile(pf, retainedFileCountLimit: 2), 62 | new[] { e1, e2, e3 }, 63 | files => 64 | { 65 | Assert.Equal(3, files.Count); 66 | Assert.True(!System.IO.File.Exists(files[0])); 67 | Assert.True(System.IO.File.Exists(files[1])); 68 | Assert.True(System.IO.File.Exists(files[2])); 69 | }); 70 | } 71 | 72 | [Fact] 73 | public void IfTheLogFolderDoesNotExistItWillBeCreated() 74 | { 75 | var fileName = Some.String() + "-{Date}.txt"; 76 | var temp = Some.TempFolderPath(); 77 | var folder = Path.Combine(temp, Guid.NewGuid().ToString()); 78 | var pathFormat = Path.Combine(folder, fileName); 79 | 80 | ILogger log = null; 81 | 82 | try 83 | { 84 | log = new LoggerConfiguration() 85 | .WriteTo.RollingFile(pathFormat, retainedFileCountLimit: 3) 86 | .CreateLogger(); 87 | 88 | log.Write(Some.InformationEvent()); 89 | 90 | Assert.True(Directory.Exists(folder)); 91 | } 92 | finally 93 | { 94 | var disposable = (IDisposable)log; 95 | if (disposable != null) disposable.Dispose(); 96 | Directory.Delete(temp, true); 97 | } 98 | } 99 | 100 | [Fact] 101 | public void AssemblyVersionIsFixedAt200() 102 | { 103 | var assembly = typeof(RollingFileLoggerConfigurationExtensions).GetTypeInfo().Assembly; 104 | Assert.Equal("2.0.0.0", assembly.GetName().Version.ToString(4)); 105 | } 106 | 107 | static void TestRollingEventSequence(params LogEvent[] events) 108 | { 109 | TestRollingEventSequence( 110 | (pf, wt) => wt.RollingFile(pf, retainedFileCountLimit: null), 111 | events); 112 | } 113 | 114 | static void TestRollingEventSequence( 115 | Action configureFile, 116 | IEnumerable events, 117 | Action> verifyWritten = null) 118 | { 119 | var fileName = Some.String() + "-{Date}.txt"; 120 | var folder = Some.TempFolderPath(); 121 | var pathFormat = Path.Combine(folder, fileName); 122 | 123 | var config = new LoggerConfiguration(); 124 | configureFile(pathFormat, config.WriteTo); 125 | var log = config.CreateLogger(); 126 | 127 | var verified = new List(); 128 | 129 | try 130 | { 131 | foreach (var @event in events) 132 | { 133 | Clock.SetTestDateTimeNow(@event.Timestamp.DateTime); 134 | log.Write(@event); 135 | 136 | var expected = pathFormat.Replace("{Date}", @event.Timestamp.ToString("yyyyMMdd")); 137 | Assert.True(System.IO.File.Exists(expected)); 138 | 139 | verified.Add(expected); 140 | } 141 | } 142 | finally 143 | { 144 | log.Dispose(); 145 | verifyWritten?.Invoke(verified); 146 | Directory.Delete(folder, true); 147 | } 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /test/Serilog.Sinks.RollingFile.Tests/Serilog.Sinks.RollingFile.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net452;netcoreapp1.0 5 | true 6 | Serilog.Sinks.RollingFile.Tests 7 | ../../assets/Serilog.snk 8 | true 9 | true 10 | Serilog.Sinks.RollingFile.Tests 11 | true 12 | $(PackageTargetFallback);dnxcore50;portable-net45+win8 13 | 1.0.4 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /test/Serilog.Sinks.RollingFile.Tests/Support/CollectingSink.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using Serilog.Core; 4 | using Serilog.Events; 5 | 6 | namespace Serilog.Sinks.RollingFile.Tests.Support 7 | { 8 | class CollectingSink : ILogEventSink 9 | { 10 | readonly List _events = new List(); 11 | 12 | public List Events { get { return _events; } } 13 | 14 | public LogEvent SingleEvent { get { return _events.Single(); } } 15 | 16 | public void Emit(LogEvent logEvent) 17 | { 18 | _events.Add(logEvent); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /test/Serilog.Sinks.RollingFile.Tests/Support/DelegateDisposable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Serilog.Sinks.RollingFile.Tests.Support 4 | { 5 | public class DelegateDisposable : IDisposable 6 | { 7 | private readonly Action _disposeAction; 8 | private bool _disposed; 9 | 10 | public DelegateDisposable(Action disposeAction) 11 | { 12 | _disposeAction = disposeAction; 13 | } 14 | 15 | public void Dispose() 16 | { 17 | if (_disposed) 18 | return; 19 | 20 | _disposeAction(); 21 | _disposed = true; 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /test/Serilog.Sinks.RollingFile.Tests/Support/DelegatingEnricher.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Serilog.Core; 3 | using Serilog.Events; 4 | 5 | namespace Serilog.Sinks.RollingFile.Tests.Support 6 | { 7 | class DelegatingEnricher : ILogEventEnricher 8 | { 9 | readonly Action _enrich; 10 | 11 | public DelegatingEnricher(Action enrich) 12 | { 13 | if (enrich == null) throw new ArgumentNullException(nameof(enrich)); 14 | _enrich = enrich; 15 | } 16 | 17 | public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) 18 | { 19 | _enrich(logEvent, propertyFactory); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /test/Serilog.Sinks.RollingFile.Tests/Support/DelegatingSink.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Serilog.Core; 3 | using Serilog.Events; 4 | 5 | namespace Serilog.Sinks.RollingFile.Tests.Support 6 | { 7 | public class DelegatingSink : ILogEventSink 8 | { 9 | readonly Action _write; 10 | 11 | public DelegatingSink(Action write) 12 | { 13 | if (write == null) throw new ArgumentNullException(nameof(write)); 14 | _write = write; 15 | } 16 | 17 | public void Emit(LogEvent logEvent) 18 | { 19 | _write(logEvent); 20 | } 21 | 22 | public static LogEvent GetLogEvent(Action writeAction) 23 | { 24 | LogEvent result = null; 25 | var l = new LoggerConfiguration() 26 | .WriteTo.Sink(new DelegatingSink(le => result = le)) 27 | .CreateLogger(); 28 | 29 | writeAction(l); 30 | return result; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /test/Serilog.Sinks.RollingFile.Tests/Support/DisposableLogger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Serilog.Core; 4 | using Serilog.Events; 5 | 6 | namespace Serilog.Sinks.RollingFile.Tests.Support 7 | { 8 | public class DisposableLogger : ILogger, IDisposable 9 | { 10 | public bool Disposed { get; set; } 11 | 12 | public void Dispose() 13 | { 14 | Disposed = true; 15 | } 16 | 17 | public ILogger ForContext(ILogEventEnricher enricher) 18 | { 19 | throw new NotImplementedException(); 20 | } 21 | 22 | public ILogger ForContext(IEnumerable enrichers) 23 | { 24 | throw new NotImplementedException(); 25 | } 26 | 27 | public ILogger ForContext(string propertyName, object value, bool destructureObjects = false) 28 | { 29 | throw new NotImplementedException(); 30 | } 31 | 32 | public ILogger ForContext() 33 | { 34 | throw new NotImplementedException(); 35 | } 36 | 37 | public ILogger ForContext(Type source) 38 | { 39 | throw new NotImplementedException(); 40 | } 41 | 42 | public void Write(LogEvent logEvent) 43 | { 44 | throw new NotImplementedException(); 45 | } 46 | 47 | public void Write(LogEventLevel level, string messageTemplate) 48 | { 49 | throw new NotImplementedException(); 50 | } 51 | 52 | public void Write(LogEventLevel level, string messageTemplate, T propertyValue) 53 | { 54 | throw new NotImplementedException(); 55 | } 56 | 57 | public void Write(LogEventLevel level, string messageTemplate, T0 propertyValue0, T1 propertyValue1) 58 | { 59 | throw new NotImplementedException(); 60 | } 61 | 62 | public void Write(LogEventLevel level, string messageTemplate, T0 propertyValue0, T1 propertyValue1, 63 | T2 propertyValue2) 64 | { 65 | throw new NotImplementedException(); 66 | } 67 | 68 | public void Write(LogEventLevel level, string messageTemplate, params object[] propertyValues) 69 | { 70 | throw new NotImplementedException(); 71 | } 72 | 73 | public void Write(LogEventLevel level, Exception exception, string messageTemplate) 74 | { 75 | throw new NotImplementedException(); 76 | } 77 | 78 | public void Write(LogEventLevel level, Exception exception, string messageTemplate, T propertyValue) 79 | { 80 | throw new NotImplementedException(); 81 | } 82 | 83 | public void Write(LogEventLevel level, Exception exception, string messageTemplate, T0 propertyValue0, 84 | T1 propertyValue1) 85 | { 86 | throw new NotImplementedException(); 87 | } 88 | 89 | public void Write(LogEventLevel level, Exception exception, string messageTemplate, T0 propertyValue0, 90 | T1 propertyValue1, T2 propertyValue2) 91 | { 92 | throw new NotImplementedException(); 93 | } 94 | 95 | public void Write(LogEventLevel level, Exception exception, string messageTemplate, params object[] propertyValues) 96 | { 97 | throw new NotImplementedException(); 98 | } 99 | 100 | public bool IsEnabled(LogEventLevel level) 101 | { 102 | throw new NotImplementedException(); 103 | } 104 | 105 | public void Verbose(string messageTemplate) 106 | { 107 | throw new NotImplementedException(); 108 | } 109 | 110 | public void Verbose(string messageTemplate, T propertyValue) 111 | { 112 | throw new NotImplementedException(); 113 | } 114 | 115 | public void Verbose(string messageTemplate, T0 propertyValue0, T1 propertyValue1) 116 | { 117 | throw new NotImplementedException(); 118 | } 119 | 120 | public void Verbose(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) 121 | { 122 | throw new NotImplementedException(); 123 | } 124 | 125 | public void Verbose(string messageTemplate, params object[] propertyValues) 126 | { 127 | throw new NotImplementedException(); 128 | } 129 | 130 | public void Verbose(Exception exception, string messageTemplate) 131 | { 132 | throw new NotImplementedException(); 133 | } 134 | 135 | public void Verbose(Exception exception, string messageTemplate, T propertyValue) 136 | { 137 | throw new NotImplementedException(); 138 | } 139 | 140 | public void Verbose(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) 141 | { 142 | throw new NotImplementedException(); 143 | } 144 | 145 | public void Verbose(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, 146 | T2 propertyValue2) 147 | { 148 | throw new NotImplementedException(); 149 | } 150 | 151 | public void Verbose(Exception exception, string messageTemplate, params object[] propertyValues) 152 | { 153 | throw new NotImplementedException(); 154 | } 155 | 156 | public void Debug(string messageTemplate) 157 | { 158 | throw new NotImplementedException(); 159 | } 160 | 161 | public void Debug(string messageTemplate, T propertyValue) 162 | { 163 | throw new NotImplementedException(); 164 | } 165 | 166 | public void Debug(string messageTemplate, T0 propertyValue0, T1 propertyValue1) 167 | { 168 | throw new NotImplementedException(); 169 | } 170 | 171 | public void Debug(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) 172 | { 173 | throw new NotImplementedException(); 174 | } 175 | 176 | public void Debug(string messageTemplate, params object[] propertyValues) 177 | { 178 | throw new NotImplementedException(); 179 | } 180 | 181 | public void Debug(Exception exception, string messageTemplate) 182 | { 183 | throw new NotImplementedException(); 184 | } 185 | 186 | public void Debug(Exception exception, string messageTemplate, T propertyValue) 187 | { 188 | throw new NotImplementedException(); 189 | } 190 | 191 | public void Debug(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) 192 | { 193 | throw new NotImplementedException(); 194 | } 195 | 196 | public void Debug(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, 197 | T2 propertyValue2) 198 | { 199 | throw new NotImplementedException(); 200 | } 201 | 202 | public void Debug(Exception exception, string messageTemplate, params object[] propertyValues) 203 | { 204 | throw new NotImplementedException(); 205 | } 206 | 207 | public void Information(string messageTemplate) 208 | { 209 | throw new NotImplementedException(); 210 | } 211 | 212 | public void Information(string messageTemplate, T propertyValue) 213 | { 214 | throw new NotImplementedException(); 215 | } 216 | 217 | public void Information(string messageTemplate, T0 propertyValue0, T1 propertyValue1) 218 | { 219 | throw new NotImplementedException(); 220 | } 221 | 222 | public void Information(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) 223 | { 224 | throw new NotImplementedException(); 225 | } 226 | 227 | public void Information(string messageTemplate, params object[] propertyValues) 228 | { 229 | throw new NotImplementedException(); 230 | } 231 | 232 | public void Information(Exception exception, string messageTemplate) 233 | { 234 | throw new NotImplementedException(); 235 | } 236 | 237 | public void Information(Exception exception, string messageTemplate, T propertyValue) 238 | { 239 | throw new NotImplementedException(); 240 | } 241 | 242 | public void Information(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) 243 | { 244 | throw new NotImplementedException(); 245 | } 246 | 247 | public void Information(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, 248 | T2 propertyValue2) 249 | { 250 | throw new NotImplementedException(); 251 | } 252 | 253 | public void Information(Exception exception, string messageTemplate, params object[] propertyValues) 254 | { 255 | throw new NotImplementedException(); 256 | } 257 | 258 | public void Warning(string messageTemplate) 259 | { 260 | throw new NotImplementedException(); 261 | } 262 | 263 | public void Warning(string messageTemplate, T propertyValue) 264 | { 265 | throw new NotImplementedException(); 266 | } 267 | 268 | public void Warning(string messageTemplate, T0 propertyValue0, T1 propertyValue1) 269 | { 270 | throw new NotImplementedException(); 271 | } 272 | 273 | public void Warning(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) 274 | { 275 | throw new NotImplementedException(); 276 | } 277 | 278 | public void Warning(string messageTemplate, params object[] propertyValues) 279 | { 280 | throw new NotImplementedException(); 281 | } 282 | 283 | public void Warning(Exception exception, string messageTemplate) 284 | { 285 | throw new NotImplementedException(); 286 | } 287 | 288 | public void Warning(Exception exception, string messageTemplate, T propertyValue) 289 | { 290 | throw new NotImplementedException(); 291 | } 292 | 293 | public void Warning(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) 294 | { 295 | throw new NotImplementedException(); 296 | } 297 | 298 | public void Warning(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, 299 | T2 propertyValue2) 300 | { 301 | throw new NotImplementedException(); 302 | } 303 | 304 | public void Warning(Exception exception, string messageTemplate, params object[] propertyValues) 305 | { 306 | throw new NotImplementedException(); 307 | } 308 | 309 | public void Error(string messageTemplate) 310 | { 311 | throw new NotImplementedException(); 312 | } 313 | 314 | public void Error(string messageTemplate, T propertyValue) 315 | { 316 | throw new NotImplementedException(); 317 | } 318 | 319 | public void Error(string messageTemplate, T0 propertyValue0, T1 propertyValue1) 320 | { 321 | throw new NotImplementedException(); 322 | } 323 | 324 | public void Error(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) 325 | { 326 | throw new NotImplementedException(); 327 | } 328 | 329 | public void Error(string messageTemplate, params object[] propertyValues) 330 | { 331 | throw new NotImplementedException(); 332 | } 333 | 334 | public void Error(Exception exception, string messageTemplate) 335 | { 336 | throw new NotImplementedException(); 337 | } 338 | 339 | public void Error(Exception exception, string messageTemplate, T propertyValue) 340 | { 341 | throw new NotImplementedException(); 342 | } 343 | 344 | public void Error(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) 345 | { 346 | throw new NotImplementedException(); 347 | } 348 | 349 | public void Error(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, 350 | T2 propertyValue2) 351 | { 352 | throw new NotImplementedException(); 353 | } 354 | 355 | public void Error(Exception exception, string messageTemplate, params object[] propertyValues) 356 | { 357 | throw new NotImplementedException(); 358 | } 359 | 360 | public void Fatal(string messageTemplate) 361 | { 362 | throw new NotImplementedException(); 363 | } 364 | 365 | public void Fatal(string messageTemplate, T propertyValue) 366 | { 367 | throw new NotImplementedException(); 368 | } 369 | 370 | public void Fatal(string messageTemplate, T0 propertyValue0, T1 propertyValue1) 371 | { 372 | throw new NotImplementedException(); 373 | } 374 | 375 | public void Fatal(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) 376 | { 377 | throw new NotImplementedException(); 378 | } 379 | 380 | public void Fatal(string messageTemplate, params object[] propertyValues) 381 | { 382 | throw new NotImplementedException(); 383 | } 384 | 385 | public void Fatal(Exception exception, string messageTemplate) 386 | { 387 | throw new NotImplementedException(); 388 | } 389 | 390 | public void Fatal(Exception exception, string messageTemplate, T propertyValue) 391 | { 392 | throw new NotImplementedException(); 393 | } 394 | 395 | public void Fatal(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) 396 | { 397 | throw new NotImplementedException(); 398 | } 399 | 400 | public void Fatal(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, 401 | T2 propertyValue2) 402 | { 403 | throw new NotImplementedException(); 404 | } 405 | 406 | public void Fatal(Exception exception, string messageTemplate, params object[] propertyValues) 407 | { 408 | throw new NotImplementedException(); 409 | } 410 | 411 | public bool BindMessageTemplate(string messageTemplate, object[] propertyValues, out MessageTemplate parsedTemplate, 412 | out IEnumerable boundProperties) 413 | { 414 | throw new NotImplementedException(); 415 | } 416 | 417 | public bool BindProperty(string propertyName, object value, bool destructureObjects, out LogEventProperty property) 418 | { 419 | throw new NotImplementedException(); 420 | } 421 | } 422 | } -------------------------------------------------------------------------------- /test/Serilog.Sinks.RollingFile.Tests/Support/DisposeTrackingSink.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Serilog.Core; 3 | using Serilog.Events; 4 | 5 | namespace Serilog.Sinks.RollingFile.Tests.Support 6 | { 7 | class DisposeTrackingSink : ILogEventSink, IDisposable 8 | { 9 | public bool IsDisposed { get; set; } 10 | 11 | public void Emit(LogEvent logEvent) 12 | { 13 | } 14 | 15 | public void Dispose() 16 | { 17 | IsDisposed = true; 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /test/Serilog.Sinks.RollingFile.Tests/Support/Extensions.cs: -------------------------------------------------------------------------------- 1 | using Serilog.Events; 2 | 3 | namespace Serilog.Sinks.RollingFile.Tests.Support 4 | { 5 | public static class Extensions 6 | { 7 | public static object LiteralValue(this LogEventPropertyValue @this) 8 | { 9 | return ((ScalarValue)@this).Value; 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /test/Serilog.Sinks.RollingFile.Tests/Support/Some.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Threading; 5 | using Serilog.Events; 6 | using Serilog.Parsing; 7 | 8 | namespace Serilog.Sinks.RollingFile.Tests.Support 9 | { 10 | static class Some 11 | { 12 | static int Counter; 13 | 14 | public static int Int() 15 | { 16 | return Interlocked.Increment(ref Counter); 17 | } 18 | 19 | public static decimal Decimal() 20 | { 21 | return Int() + 0.123m; 22 | } 23 | 24 | public static string String(string tag = null) 25 | { 26 | return (tag ?? "") + "__" + Int(); 27 | } 28 | 29 | public static TimeSpan TimeSpan() 30 | { 31 | return System.TimeSpan.FromMinutes(Int()); 32 | } 33 | 34 | public static DateTime Instant() 35 | { 36 | return new DateTime(2012, 10, 28) + TimeSpan(); 37 | } 38 | 39 | public static DateTimeOffset OffsetInstant() 40 | { 41 | return new DateTimeOffset(Instant()); 42 | } 43 | 44 | public static LogEvent LogEvent(DateTimeOffset? timestamp = null, LogEventLevel level = LogEventLevel.Information) 45 | { 46 | return new LogEvent(timestamp ?? OffsetInstant(), level, 47 | null, MessageTemplate(), Enumerable.Empty()); 48 | } 49 | 50 | public static LogEvent InformationEvent(DateTimeOffset? timestamp = null) 51 | { 52 | return LogEvent(timestamp, LogEventLevel.Information); 53 | } 54 | 55 | public static LogEvent DebugEvent(DateTimeOffset? timestamp = null) 56 | { 57 | return LogEvent(timestamp, LogEventLevel.Debug); 58 | } 59 | 60 | public static LogEventProperty LogEventProperty() 61 | { 62 | return new LogEventProperty(String(), new ScalarValue(Int())); 63 | } 64 | 65 | public static string NonexistentTempFilePath() 66 | { 67 | return Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".txt"); 68 | } 69 | 70 | public static string TempFilePath() 71 | { 72 | return Path.GetTempFileName(); 73 | } 74 | 75 | public static string TempFolderPath() 76 | { 77 | var dir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); 78 | Directory.CreateDirectory(dir); 79 | return dir; 80 | } 81 | 82 | public static MessageTemplate MessageTemplate() 83 | { 84 | return new MessageTemplateParser().Parse(String()); 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /test/Serilog.Sinks.RollingFile.Tests/Support/TempFolder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.IO; 4 | using System.Runtime.CompilerServices; 5 | 6 | namespace Serilog.Sinks.RollingFile.Tests.Support 7 | { 8 | class TempFolder : IDisposable 9 | { 10 | static readonly Guid Session = Guid.NewGuid(); 11 | 12 | readonly string _tempFolder; 13 | 14 | public TempFolder(string name) 15 | { 16 | _tempFolder = System.IO.Path.Combine( 17 | Environment.GetEnvironmentVariable("TMP"), 18 | "Serilog.Sinks.RollingFile.Tests", 19 | Session.ToString("n"), 20 | name); 21 | 22 | Directory.CreateDirectory(_tempFolder); 23 | } 24 | 25 | public string Path => _tempFolder; 26 | 27 | public void Dispose() 28 | { 29 | try 30 | { 31 | if (Directory.Exists(_tempFolder)) 32 | Directory.Delete(_tempFolder, true); 33 | } 34 | catch (Exception ex) 35 | { 36 | Debug.WriteLine(ex); 37 | } 38 | } 39 | 40 | public static TempFolder ForCaller([CallerMemberName] string caller = null) 41 | { 42 | if (caller == null) throw new ArgumentNullException(nameof(caller)); 43 | return new TempFolder(caller); 44 | } 45 | 46 | public string AllocateFilename(string ext = null) 47 | { 48 | return System.IO.Path.Combine(Path, Guid.NewGuid().ToString("n") + "." + (ext ?? "tmp")); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /test/Serilog.Sinks.RollingFile.Tests/TemplatedPathRollerTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | using Xunit; 5 | 6 | namespace Serilog.Sinks.RollingFile.Tests 7 | { 8 | public class TemplatedPathRollerTests 9 | { 10 | [Fact] 11 | public void SpecifierCannotBeProvidedInDirectory() 12 | { 13 | var ex = Assert.Throws(() => new TemplatedPathRoller("{Date}\\log.txt")); 14 | Assert.True(ex.Message.Contains("directory")); 15 | } 16 | 17 | [Fact] 18 | public void TheLogFileIncludesDateToken() 19 | { 20 | var roller = new TemplatedPathRoller("Logs\\log.{Date}.txt"); 21 | var now = new DateTime(2013, 7, 14, 3, 24, 9, 980); 22 | string path; 23 | roller.GetLogFilePath(now, 0, out path); 24 | AssertEqualAbsolute("Logs\\log.20130714.txt", path); 25 | } 26 | 27 | [Fact] 28 | public void ANonZeroIncrementIsIncludedAndPadded() 29 | { 30 | var roller = new TemplatedPathRoller("Logs\\log.{Date}.txt"); 31 | var now = new DateTime(2013, 7, 14, 3, 24, 9, 980); 32 | string path; 33 | roller.GetLogFilePath(now, 12, out path); 34 | AssertEqualAbsolute("Logs\\log.20130714_012.txt", path); 35 | } 36 | 37 | static void AssertEqualAbsolute(string path1, string path2) 38 | { 39 | var abs1 = Path.GetFullPath(path1); 40 | var abs2 = Path.GetFullPath(path2); 41 | Assert.Equal(abs1, abs2); 42 | } 43 | 44 | [Fact] 45 | public void TheRollerReturnsTheLogFileDirectory() 46 | { 47 | var roller = new TemplatedPathRoller("Logs\\log.{Date}.txt"); 48 | AssertEqualAbsolute("Logs", roller.LogFileDirectory); 49 | } 50 | 51 | [Fact] 52 | public void IfNoTokenIsSpecifiedDashFollowedByTheDateIsImplied() 53 | { 54 | var roller = new TemplatedPathRoller("Logs\\log.txt"); 55 | var now = new DateTime(2013, 7, 14, 3, 24, 9, 980); 56 | string path; 57 | roller.GetLogFilePath(now, 0, out path); 58 | AssertEqualAbsolute("Logs\\log-20130714.txt", path); 59 | } 60 | 61 | [Fact] 62 | public void TheLogFileIsNotRequiredToIncludeAnExtension() 63 | { 64 | var roller = new TemplatedPathRoller("Logs\\log-{Date}"); 65 | var now = new DateTime(2013, 7, 14, 3, 24, 9, 980); 66 | string path; 67 | roller.GetLogFilePath(now, 0, out path); 68 | AssertEqualAbsolute("Logs\\log-20130714", path); 69 | } 70 | 71 | [Fact] 72 | public void TheLogFileIsNotRequiredToIncludeADirectory() 73 | { 74 | var roller = new TemplatedPathRoller("log-{Date}"); 75 | var now = new DateTime(2013, 7, 14, 3, 24, 9, 980); 76 | string path; 77 | roller.GetLogFilePath(now, 0, out path); 78 | AssertEqualAbsolute("log-20130714", path); 79 | } 80 | 81 | [Fact] 82 | public void MatchingExcludesSimilarButNonmatchingFiles() 83 | { 84 | var roller = new TemplatedPathRoller("log-{Date}.txt"); 85 | const string similar1 = "log-0.txt"; 86 | const string similar2 = "log-helloyou.txt"; 87 | var matched = roller.SelectMatches(new[] { similar1, similar2 }); 88 | Assert.Equal(0, matched.Count()); 89 | } 90 | 91 | [Theory] 92 | [InlineData("Logs\\log-{Date}.txt")] 93 | [InlineData("Logs\\log-{Hour}.txt")] 94 | [InlineData("Logs\\log-{HalfHour}.txt")] 95 | public void TheDirectorSearchPatternUsesWildcardInPlaceOfDate(string template) 96 | { 97 | var roller = new TemplatedPathRoller(template); 98 | Assert.Equal("log-*.txt", roller.DirectorySearchPattern); 99 | } 100 | 101 | [Theory] 102 | [InlineData("log-{Date}.txt", "log-20131210.txt", "log-20131210_031.txt")] 103 | [InlineData("log-{Hour}.txt", "log-2013121013.txt", "log-2013121013_031.txt")] 104 | [InlineData("log-{HalfHour}.txt", "log-201312100100.txt", "log-201312100230_031.txt")] 105 | public void MatchingSelectsFiles(string template, string zeroth, string thirtyFirst) 106 | { 107 | var roller = new TemplatedPathRoller(template); 108 | var matched = roller.SelectMatches(new[] { zeroth, thirtyFirst }).ToArray(); 109 | Assert.Equal(2, matched.Count()); 110 | Assert.Equal(0, matched[0].SequenceNumber); 111 | Assert.Equal(31, matched[1].SequenceNumber); 112 | } 113 | 114 | [Theory] 115 | [InlineData("log-{Date}.txt", "log-20150101.txt", "log-20141231.txt")] 116 | [InlineData("log-{Hour}.txt", "log-2015010110.txt", "log-2015010109.txt")] 117 | [InlineData("log-{HalfHour}.txt", "log-201501011400.txt", "log-201501011330.txt")] 118 | public void MatchingParsesSubstitutions(string template, string newer, string older) 119 | { 120 | var roller = new TemplatedPathRoller(template); 121 | var matched = roller.SelectMatches(new[] { older, newer }).OrderByDescending(m => m.DateTime).Select(m => m.Filename).ToArray(); 122 | Assert.Equal(new[] { newer, older }, matched); 123 | } 124 | } 125 | } 126 | 127 | --------------------------------------------------------------------------------