├── .editorconfig
├── .gitignore
├── CommonAssemblyInfo.cs
├── Directory.Build.props
├── LICENSE
├── README.md
├── appveyor.yml
├── build.cmd
├── build.sh
├── serilog-sinks-file-archive-test.snk
├── serilog-sinks-file-archive.sln
├── serilog-sinks-file-archive.sln.DotSettings
├── serilog-sinks-file-archive.snk
├── src
└── Serilog.Sinks.File.Archive
│ ├── ArchiveHooks.cs
│ ├── Serilog.Sinks.File.Archive.csproj
│ └── TokenExpander.cs
└── test
└── Serilog.Sinks.File.Archive.Test
├── RollingFileSinkTests.cs
├── Serilog.Sinks.File.Archive.Test.csproj
├── Support
├── Some.cs
├── TestFolder.cs
└── Utils.cs
└── TokenExpanderTests.cs
/.editorconfig:
--------------------------------------------------------------------------------
1 | # EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs
2 | # editorconfig.org
3 |
4 | # top-most EditorConfig file
5 | root = true
6 |
7 | [*]
8 | indent_style = space
9 | charset = utf-8
10 | trim_trailing_whitespace = true
11 | insert_final_newline = true
12 | indent_size = 4
13 |
14 | [*.json]
15 | indent_size = 2
16 |
17 | [*.md]
18 | trim_trailing_whitespace = false
19 |
20 | [*.cs]
21 | # New line preferences
22 | csharp_new_line_before_open_brace = all
23 | csharp_new_line_before_else = true
24 | csharp_new_line_before_catch = true
25 | csharp_new_line_before_finally = true
26 | csharp_new_line_before_members_in_object_initializers = true
27 | csharp_new_line_before_members_in_anonymous_types = true
28 | csharp_new_line_within_query_expression_clauses = true
29 |
30 | # Indentation preferences
31 | csharp_indent_block_contents = true
32 | csharp_indent_braces = false
33 | csharp_indent_case_contents = true
34 | csharp_indent_switch_labels = true
35 | csharp_indent_labels = flush_left
36 |
37 | # Use this. for fields and properties
38 | dotnet_style_qualification_for_field = true:suggestion
39 | dotnet_style_qualification_for_property = true:suggestion
40 | dotnet_style_qualification_for_method = false:suggestion
41 | dotnet_style_qualification_for_event = false:suggestion
42 |
43 | # only use var when it's obvious what the variable type is
44 | csharp_style_var_for_built_in_types = false:none
45 | csharp_style_var_when_type_is_apparent = false:none
46 | csharp_style_var_elsewhere = false:suggestion
47 |
48 | # use language keywords instead of BCL types
49 | dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
50 |
51 | # use BCL types for static member access instead of language keywords
52 | dotnet_style_predefined_type_for_member_access = false:suggestion
53 |
54 | # define naming styles
55 | dotnet_naming_style.pascal_case_style.capitalization = pascal_case
56 | dotnet_naming_style.camel_case_underscore_style.capitalization = camel_case
57 |
58 | # interface names should be PascalCase, and prefixed with 'I'
59 | dotnet_naming_style.interface.required_prefix = I
60 | dotnet_naming_style.interface.capitalization = pascal_case
61 |
62 | # name all constant fields using PascalCase
63 | dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion
64 | dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields
65 | dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style
66 |
67 | dotnet_naming_symbols.constant_fields.applicable_kinds = field
68 | dotnet_naming_symbols.constant_fields.required_modifiers = const
69 |
70 | # name all static, readonly fields using PascalCase
71 | dotnet_naming_rule.static_readonly_fields_should_be_pascal_case.severity = suggestion
72 | dotnet_naming_rule.static_readonly_fields_should_be_pascal_case.symbols = static_readonly_fields
73 | dotnet_naming_rule.static_readonly_fields_should_be_pascal_case.style = pascal_case_style
74 |
75 | dotnet_naming_symbols.static_readonly_fields.applicable_kinds = field
76 | dotnet_naming_symbols.static_readonly_fields.required_modifiers = static, readonly
77 |
78 | # internal and private fields should be camelCase
79 | dotnet_naming_rule.camel_case_for_private_internal_fields.severity = suggestion
80 | dotnet_naming_rule.camel_case_for_private_internal_fields.symbols = private_internal_fields
81 | dotnet_naming_rule.camel_case_for_private_internal_fields.style = camel_case_style
82 |
83 | dotnet_naming_symbols.private_internal_fields.applicable_kinds = field
84 | dotnet_naming_symbols.private_internal_fields.applicable_accessibilities = private, internal
85 |
86 | dotnet_naming_style.camel_case_style.capitalization = camel_case
87 |
88 | # Code style defaults
89 | dotnet_sort_system_directives_first = true
90 | csharp_preserve_single_line_blocks = true
91 | csharp_preserve_single_line_statements = false
92 |
93 | # Expression-level preferences
94 | dotnet_style_object_initializer = true:suggestion
95 | dotnet_style_collection_initializer = true:suggestion
96 | dotnet_style_explicit_tuple_names = true:suggestion
97 | dotnet_style_coalesce_expression = true:suggestion
98 | dotnet_style_null_propagation = true:suggestion
99 |
100 | # Expression-bodied members
101 | csharp_style_expression_bodied_methods = false:none
102 | csharp_style_expression_bodied_constructors = false:none
103 | csharp_style_expression_bodied_operators = false:none
104 | csharp_style_expression_bodied_properties = true:none
105 | csharp_style_expression_bodied_indexers = true:none
106 | csharp_style_expression_bodied_accessors = true:none
107 |
108 | # Pattern matching
109 | csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
110 | csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
111 | csharp_style_inlined_variable_declaration = true:suggestion
112 |
113 | # Null checking preferences
114 | csharp_style_throw_expression = true:suggestion
115 | csharp_style_conditional_delegate_call = true:suggestion
116 |
117 | # Space preferences
118 | csharp_space_after_cast = false
119 | csharp_space_after_colon_in_inheritance_clause = true
120 | csharp_space_after_comma = true
121 | csharp_space_after_dot = false
122 | csharp_space_after_keywords_in_control_flow_statements = true
123 | csharp_space_after_semicolon_in_for_statement = true
124 | csharp_space_around_binary_operators = before_and_after
125 | csharp_space_around_declaration_statements = do_not_ignore
126 | csharp_space_before_colon_in_inheritance_clause = true
127 | csharp_space_before_comma = false
128 | csharp_space_before_dot = false
129 | csharp_space_before_open_square_brackets = false
130 | csharp_space_before_semicolon_in_for_statement = false
131 | csharp_space_between_empty_square_brackets = false
132 | csharp_space_between_method_call_empty_parameter_list_parentheses = false
133 | csharp_space_between_method_call_name_and_opening_parenthesis = false
134 | csharp_space_between_method_call_parameter_list_parentheses = false
135 | csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
136 | csharp_space_between_method_declaration_name_and_open_parenthesis = false
137 | csharp_space_between_method_declaration_parameter_list_parentheses = false
138 | csharp_space_between_parentheses = false
139 | csharp_space_between_square_brackets = false
140 |
141 | # Xml project files
142 | [*.{csproj}]
143 | indent_size = 4
144 |
145 | # Xml config files
146 | [*.{props,targets,config,nuspec}]
147 | indent_size = 4
148 |
149 | # Shell scripts
150 | [*.sh]
151 | end_of_line = lf
152 |
153 | [*.{cmd, bat}]
154 | end_of_line = crlf
155 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | project.lock.json
5 | artifacts/
6 |
7 | # User-specific files
8 | *.suo
9 | *.user
10 | *.sln.docstates
11 |
12 | # Build results
13 | [Dd]ebug/
14 | [Dd]ebugPublic/
15 | [Rr]elease/
16 | [Rr]eleases/
17 | x64/
18 | x86/
19 | bld/
20 | [Bb]in/
21 | [Oo]bj/
22 |
23 | # IDE directories
24 | *.ide/
25 | .vs
26 | .vscode
27 | .idea
28 |
29 | *_i.c
30 | *_p.c
31 | *_i.h
32 | *.ilk
33 | *.meta
34 | *.obj
35 | *.pch
36 | *.pdb
37 | *.pgc
38 | *.pgd
39 | *.rsp
40 | *.sbr
41 | *.tlb
42 | *.tli
43 | *.tlh
44 | *.tmp
45 | *.tmp_proj
46 | *.log
47 | *.vspscc
48 | *.vssscc
49 | .builds
50 | *.pidb
51 | *.svclog
52 | *.scc
53 | *.srl
54 |
55 | # Visual Studio profiler
56 | *.psess
57 | *.vsp
58 | *.vspx
59 |
60 | # ReSharper is a .NET coding add-in
61 | _ReSharper*/
62 | *.[Rr]e[Ss]harper
63 | *.DotSettings.user
64 |
65 | # Click-Once directory
66 | publish/
67 |
68 | # Publish Web Output
69 | *.[Pp]ublish.xml
70 | *.azurePubxml
71 | # TODO: Comment the next line if you want to checkin your web deploy settings
72 | # but database connection strings (with potential passwords) will be unencrypted
73 | *.pubxml
74 | *.publishproj
75 |
76 | # NuGet Packages
77 | *.nupkg
78 | # The packages folder can be ignored because of Package Restore
79 | **/packages/*
80 | # except build/, which is used as an MSBuild target.
81 | !**/packages/build/
82 | # If using the old MSBuild-Integrated Package Restore, uncomment this:
83 | #!**/packages/repositories.config
84 |
85 | # Others
86 | sql/
87 | *.Cache
88 | ClientBin/
89 | [Ss]tyle[Cc]op.*
90 | ~$*
91 | *~
92 | *.dbmdl
93 | *.dbproj.schemaview
94 | *.pfx
95 | *.publishsettings
96 | node_modules/
97 |
98 | # Backup & report files from converting an old project file
99 | # to a newer Visual Studio version. Backup files are not needed,
100 | # because we have git ;-)
101 | _UpgradeReport_Files/
102 | Backup*/
103 | UpgradeLog*.XML
104 | UpgradeLog*.htm
105 |
--------------------------------------------------------------------------------
/CommonAssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | [assembly: AssemblyConfiguration("")]
5 | [assembly: AssemblyProduct("serilog-sinks-file-archive")]
6 | [assembly: AssemblyCopyright("Copyright © Colin Anderson 2020")]
7 | [assembly: AssemblyTrademark("")]
8 |
9 | [assembly: ComVisible(false)]
10 |
11 | [assembly: AssemblyVersion("1.0.0.0")]
12 | [assembly: AssemblyInformationalVersion("1.0.6")]
13 |
14 | [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Serilog.Sinks.File.Archive.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010025498721eb03bb1731fc4b9646dba1ccf8b4200219d34d57cd538162531409077fdfeead7efbeef28c352fa5e08e2010f2bfe3ae75d7a18a736b5a9c075ba69f0d8da5bfab51b53e23b9214eb8957e992dd31ed94d49ba8d6cc72cf79c06e1085a43559b9644a4b7d621c2d64baf6cc2edc2ae754a0f8f77faccb71cbb1d22df")]
15 |
--------------------------------------------------------------------------------
/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | latest
5 | true
6 | false
7 | false
8 |
9 |
10 |
11 |
12 | false
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/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 | Copyright 2018 Ionx Solutions
179 |
180 | Licensed under the Apache License, Version 2.0 (the "License");
181 | you may not use this file except in compliance with the License.
182 | You may obtain a copy of the License at
183 |
184 | http://www.apache.org/licenses/LICENSE-2.0
185 |
186 | Unless required by applicable law or agreed to in writing, software
187 | distributed under the License is distributed on an "AS IS" BASIS,
188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189 | See the License for the specific language governing permissions and
190 | limitations under the License.
191 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Serilog.Sinks.File.Archive
2 | [](https://www.nuget.org/packages/Serilog.Sinks.File.Archive)
3 | [](https://ci.appveyor.com/project/cocowalla/serilog-sinks-file-archive)
4 |
5 | A `FileLifecycleHooks`-based plugin for the [Serilog File Sink](https://github.com/serilog/serilog-sinks-file) that works with rolling log files, archiving completed log files before they are deleted by Serilog's retention mechanism.
6 |
7 | The following archive methods are supported:
8 |
9 | - Compress logs in the same directory (using GZip compression)
10 | - Copying logs to another directory
11 | - Compress logs (using GZip compression) and write them to another directory
12 |
13 | ### Getting started
14 | To get started, install the latest [Serilog.Sinks.File.Archive](https://www.nuget.org/packages/Serilog.Sinks.File.Archive) package from NuGet:
15 |
16 | ```powershell
17 | Install-Package Serilog.Sinks.File.Archive
18 | ```
19 |
20 | To enable archiving, use one of the new `LoggerSinkConfiguration` extensions that has a `FileLifecycleHooks` argument, and create a new `ArchiveHooks`. For example, to write GZip compressed logs to another directory (the directory will be created if it doesn't already exist):
21 |
22 | ```csharp
23 | Log.Logger = new LoggerConfiguration()
24 | .WriteTo.File("my-app.log", hooks: new ArchiveHooks(CompressionLevel.Fastest, "C:\\My\\Archive\\Path"))
25 | .CreateLogger();
26 | ```
27 |
28 | Or to copy logs as-is to another directory:
29 |
30 | ```csharp
31 | Log.Logger = new LoggerConfiguration()
32 | .WriteTo.File("my-app.log", hooks: new ArchiveHooks(CompressionLevel.NoCompression, "C:\\My\\Archive\\Path"))
33 | .CreateLogger();
34 | ```
35 |
36 | Or to write GZip compressed logs to the same directory the logs are written to:
37 |
38 | ```csharp
39 | Log.Logger = new LoggerConfiguration()
40 | .WriteTo.File("my-app.log", hooks: new ArchiveHooks(CompressionLevel.Fastest))
41 | .CreateLogger();
42 | ```
43 |
44 | Note that archival only works with *rolling* log files, as files are only deleted by Serilog's rolling file retention mechanism.
45 |
46 | As is [standard with Serilog](https://github.com/serilog/serilog/wiki/Lifecycle-of-Loggers#in-all-apps), it's important to call `Log.CloseAndFlush();` before your application ends.
47 |
48 | ### Token Replacement
49 | The `targetDirectory` constructor parameter supports replacement of tokens at runtime.
50 |
51 | Tokens take the form `{Name:FormatString}`, where `Name` is the name of a supported token, and `FormatString` defines how the token value should be formatted.
52 |
53 | At present, 2 tokens are supported, `UtcDate` and `Date`. These use [standard .NET date format strings](https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings) to insert components of the current date/time into the path. For example, you may wish to organise archived files into folders based on the current **year** and **month**:
54 |
55 | ```csharp
56 | new ArchiveHooks(CompressionLevel.Fastest, "C:\\Archive\\{UtcDate:yyyy}\\{UtcDate:MM}")
57 | ```
58 |
59 | ### JSON appsettings.json configuration
60 |
61 | It's also possible to enable archival when configuring Serilog from a configuration file using [Serilog.Settings.Configuration](https://github.com/serilog/serilog-settings-configuration/). To do this, you will first need to create a public static class that can provide the configuration system with a configured instance of `ArchiveHooks`:
62 |
63 | ```csharp
64 | using Serilog.Sinks.File.Archive;
65 |
66 | namespace MyApp.Logging
67 | {
68 | public class SerilogHooks
69 | {
70 | public static ArchiveHooks MyArchiveHooks => new ArchiveHooks(CompressionLevel.Fastest, "C:\\My\\Archive\\Path");
71 | }
72 | }
73 | ```
74 |
75 | The `hooks` argument in Your `appsettings.json` file should be configured as follows:
76 |
77 | ```json
78 | {
79 | "Serilog": {
80 | "WriteTo": [
81 | {
82 | "Name": "File",
83 | "Args": {
84 | "path": "my-app.log",
85 | "fileSizeLimitBytes": 10485760,
86 | "rollOnFileSizeLimit": true,
87 | "retainedFileCountLimit": 5,
88 | "hooks": "MyApp.Logging.SerilogHooks::MyArchiveHooks, MyApp"
89 | }
90 | }
91 | ]
92 | }
93 | }
94 | ```
95 |
96 | To break this down a bit, what you are doing is specifying the fully qualified type name of the static class that provides your `ArchiveHooks`, using `Serilog.Settings.Configuration`'s special `::` syntax to point to the `MyArchiveHooks` member.
97 |
98 | ### About `FileLifecycleHooks`
99 | `FileLifecycleHooks` is a Serilog File Sink mechanism that allows hooking into log file lifecycle events, enabling scenarios such as wrapping the Serilog output stream in another stream, or capturing files before they are deleted by Serilog's retention mechanism.
100 |
101 | Other available hooks include:
102 |
103 | - [serilog-sinks-file-header](https://github.com/cocowalla/serilog-sinks-file-header): writes a header to the start of each log file
104 | - [serilog-sinks-file-gzip](https://github.com/cocowalla/serilog-sinks-file-gzip): compresses logs as they are written, using streaming GZIP compression
105 |
--------------------------------------------------------------------------------
/appveyor.yml:
--------------------------------------------------------------------------------
1 | version: '{build}'
2 | image: Visual Studio 2022
3 | configuration: Release
4 | platform: Any CPU
5 | skip_tags: true
6 |
7 | environment:
8 | DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true
9 |
10 | build_script:
11 | - cmd: .\build.cmd
12 |
13 | test: off
14 |
15 | artifacts:
16 | - path: src\Serilog.Sinks.File.Archive\**\Release\Serilog.Sinks.File.Archive.*.nupkg
17 |
--------------------------------------------------------------------------------
/build.cmd:
--------------------------------------------------------------------------------
1 | dotnet restore .\serilog-sinks-file-archive.sln
2 | dotnet build .\src\Serilog.Sinks.File.Archive\Serilog.Sinks.File.Archive.csproj --configuration Release
3 |
4 | dotnet test .\test\Serilog.Sinks.File.Archive.Test\Serilog.Sinks.File.Archive.Test.csproj
5 |
6 | dotnet pack .\src\Serilog.Sinks.File.Archive\Serilog.Sinks.File.Archive.csproj -c Release
7 |
--------------------------------------------------------------------------------
/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | set -ev
3 |
4 | dotnet restore ./serilog-sinks-file-archive.sln --runtime netstandard2.0
5 | dotnet build ./src/Serilog.Sinks.File.Archive/Serilog.Sinks.File.Archive.csproj --runtime netstandard2.0 --configuration Release
6 |
7 | dotnet test ./test/Serilog.Sinks.File.Archive.Test/Serilog.Sinks.File.Archive.Test.csproj --framework netcoreapp2.2
8 |
--------------------------------------------------------------------------------
/serilog-sinks-file-archive-test.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cocowalla/serilog-sinks-file-archive/ba06b1a922bfec21a026cd9188f5503636b86fb7/serilog-sinks-file-archive-test.snk
--------------------------------------------------------------------------------
/serilog-sinks-file-archive.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Serilog.Sinks.File.Archive", "src\Serilog.Sinks.File.Archive\Serilog.Sinks.File.Archive.csproj", "{54A0544A-53F1-40CC-958F-C09513D85B7D}"
4 | EndProject
5 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Serilog.Sinks.File.Archive.Test", "test\Serilog.Sinks.File.Archive.Test\Serilog.Sinks.File.Archive.Test.csproj", "{40D90C54-9E07-4BAD-B1A8-82F7D63555EF}"
6 | EndProject
7 | Global
8 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
9 | Debug|Any CPU = Debug|Any CPU
10 | Release|Any CPU = Release|Any CPU
11 | EndGlobalSection
12 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
13 | {54A0544A-53F1-40CC-958F-C09513D85B7D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
14 | {54A0544A-53F1-40CC-958F-C09513D85B7D}.Debug|Any CPU.Build.0 = Debug|Any CPU
15 | {54A0544A-53F1-40CC-958F-C09513D85B7D}.Release|Any CPU.ActiveCfg = Release|Any CPU
16 | {54A0544A-53F1-40CC-958F-C09513D85B7D}.Release|Any CPU.Build.0 = Release|Any CPU
17 | {40D90C54-9E07-4BAD-B1A8-82F7D63555EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
18 | {40D90C54-9E07-4BAD-B1A8-82F7D63555EF}.Debug|Any CPU.Build.0 = Debug|Any CPU
19 | {40D90C54-9E07-4BAD-B1A8-82F7D63555EF}.Release|Any CPU.ActiveCfg = Release|Any CPU
20 | {40D90C54-9E07-4BAD-B1A8-82F7D63555EF}.Release|Any CPU.Build.0 = Release|Any CPU
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/serilog-sinks-file-archive.sln.DotSettings:
--------------------------------------------------------------------------------
1 |
2 | <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" />
3 | <Policy><Descriptor Staticness="Instance" AccessRightKinds="Private" Description="Instance fields (private)"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></Policy>
4 | True
5 | True
6 | True
--------------------------------------------------------------------------------
/serilog-sinks-file-archive.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cocowalla/serilog-sinks-file-archive/ba06b1a922bfec21a026cd9188f5503636b86fb7/serilog-sinks-file-archive.snk
--------------------------------------------------------------------------------
/src/Serilog.Sinks.File.Archive/ArchiveHooks.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.IO.Compression;
5 | using System.Linq;
6 | using Serilog.Debugging;
7 |
8 | namespace Serilog.Sinks.File.Archive
9 | {
10 | ///
11 | ///
12 | /// Archives log files before they are deleted by Serilog's retention mechanism, copying them to another location
13 | /// and optionally compressing them using GZip
14 | ///
15 | public class ArchiveHooks : FileLifecycleHooks
16 | {
17 | private readonly CompressionLevel compressionLevel;
18 | private readonly int retainedFileCountLimit;
19 | private readonly string targetDirectory;
20 |
21 | ///
22 | /// Create a new ArchiveHooks, which will archive completed log files before they are deleted by Serilog's retention mechanism
23 | ///
24 | ///
25 | /// Level of GZIP compression to use. Use CompressionLevel.NoCompression if no compression is required
26 | ///
27 | ///
28 | /// Directory in which to archive files to. Use null if compressed, archived files should remain in the same folder
29 | ///
30 | public ArchiveHooks(CompressionLevel compressionLevel = CompressionLevel.Fastest, string targetDirectory = null)
31 | {
32 | if (compressionLevel == CompressionLevel.NoCompression && targetDirectory == null)
33 | throw new ArgumentException($"Either {nameof(compressionLevel)} or {nameof(targetDirectory)} must be set");
34 |
35 | this.compressionLevel = compressionLevel;
36 | this.targetDirectory = targetDirectory;
37 | }
38 |
39 | ///
40 | /// Create a new ArchiveHooks, which will archive completed log files before they are deleted by Serilog's retention mechanism
41 | ///
42 | /// Limit of Archived files.
43 | ///
44 | /// Level of GZIP compression to use. Use CompressionLevel.NoCompression if no compression is required
45 | ///
46 | ///
47 | /// Directory in which to archive files to. Use null if compressed, archived files should remain in the same folder
48 | ///
49 | public ArchiveHooks(int retainedFileCountLimit, CompressionLevel compressionLevel = CompressionLevel.Fastest, string targetDirectory = null)
50 | {
51 | if (retainedFileCountLimit <= 0)
52 | throw new ArgumentException($"{nameof(retainedFileCountLimit)} must be greater than zero", nameof(retainedFileCountLimit));
53 | if (targetDirectory is not null && TokenExpander.IsTokenised(targetDirectory))
54 | throw new ArgumentException($"{nameof(targetDirectory)} must not be tokenised when using {nameof(retainedFileCountLimit)}", nameof(targetDirectory));
55 | if (compressionLevel == CompressionLevel.NoCompression && targetDirectory == null)
56 | throw new ArgumentException($"Either {nameof(compressionLevel)} or {nameof(targetDirectory)} must be set");
57 |
58 | this.compressionLevel = compressionLevel;
59 | this.retainedFileCountLimit = retainedFileCountLimit;
60 | this.targetDirectory = targetDirectory;
61 | }
62 |
63 | public override void OnFileDeleting(string path)
64 | {
65 | try
66 | {
67 | // Use .gz file extension if we are going to compress the source file
68 | var filename = this.compressionLevel != CompressionLevel.NoCompression
69 | ? Path.GetFileName(path) + ".gz"
70 | : Path.GetFileName(path);
71 |
72 | // Determine the target path for the current file
73 | var currentTargetDir = this.targetDirectory != null
74 | ? TokenExpander.Expand(this.targetDirectory)
75 | : Path.GetDirectoryName(path);
76 |
77 | // Create the target directory, if it doesn't already exist
78 | if (!Directory.Exists(currentTargetDir))
79 | {
80 | Directory.CreateDirectory(currentTargetDir!);
81 | }
82 |
83 | // Target file path
84 | var targetPath = Path.Combine(currentTargetDir, filename);
85 |
86 | // Do we need to compress the file, or simply copy it as-is?
87 | if (this.compressionLevel == CompressionLevel.NoCompression)
88 | {
89 | System.IO.File.Copy(path, targetPath, true);
90 | }
91 | else
92 | {
93 | using (var sourceStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
94 | using (var targetStream = new FileStream(targetPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
95 | using (var compressStream = new GZipStream(targetStream, this.compressionLevel))
96 | {
97 | sourceStream.CopyTo(compressStream);
98 | }
99 | }
100 |
101 | // Only apply archive file limit if we are archiving to a non-tokenised path (a constant path)
102 | if (this.retainedFileCountLimit > 0 && !this.IsArchivePathTokenised)
103 | {
104 | RemoveExcessFiles(currentTargetDir);
105 | }
106 | }
107 | catch (Exception ex)
108 | {
109 | SelfLog.WriteLine("Error while archiving file {0}: {1}", path, ex);
110 | throw;
111 | }
112 | }
113 |
114 | private bool IsArchivePathTokenised => this.targetDirectory is not null && TokenExpander.IsTokenised(this.targetDirectory);
115 |
116 | private void RemoveExcessFiles(string folder)
117 | {
118 | var searchPattern = this.compressionLevel != CompressionLevel.NoCompression
119 | ? "*.gz"
120 | : "*.*";
121 |
122 | var filesToDelete = Directory.GetFiles(folder, searchPattern)
123 | .Select(f => new FileInfo(f))
124 | .OrderByDescending(f => f, LogFileComparer.Default)
125 | .Skip(this.retainedFileCountLimit)
126 | .ToList();
127 |
128 | foreach (var file in filesToDelete)
129 | {
130 | try
131 | {
132 | file.Delete();
133 | }
134 | catch (Exception ex)
135 | {
136 | SelfLog.WriteLine("Error while deleting file {0}: {1}", file.FullName, ex);
137 | }
138 | }
139 | }
140 |
141 | private class LogFileComparer : IComparer
142 | {
143 | public static readonly IComparer Default = new LogFileComparer();
144 |
145 | // This will not work correctly when the file uses a date format where lexicographical order does not
146 | // correspond to chronological order - but frankly, if you are using non ISO 8601 date formats in your
147 | // files you should be shot :)
148 | public int Compare(FileInfo x, FileInfo y)
149 | {
150 | if (x is null && y is null)
151 | return 0;
152 | if (x is null)
153 | return -1;
154 | if (y is null)
155 | return 1;
156 | if (x.Name.Length > y.Name.Length)
157 | return 1;
158 | if (y.Name.Length > x.Name.Length)
159 | return -1;
160 |
161 | return String.Compare(x.Name, y.Name, StringComparison.OrdinalIgnoreCase);
162 | }
163 | }
164 | }
165 | }
166 |
--------------------------------------------------------------------------------
/src/Serilog.Sinks.File.Archive/Serilog.Sinks.File.Archive.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Plugin for the Serilog File sink that archives completed log files, optionally compressing them.
5 | 1.0.6
6 | false
7 | Colin Anderson
8 | Copyright © Colin Anderson 2020
9 | net45;netstandard1.6;netstandard2.0;net6.0;net8.0
10 | Serilog.Sinks.File.Archive
11 | Serilog.Sinks.File.Archive
12 | true
13 | https://github.com/cocowalla/serilog-sinks-file-archive
14 | git
15 | false
16 | README.md
17 |
18 |
19 |
20 |
21 | true
22 |
23 |
24 |
25 | true
26 | serilog;file;compression;gzip;archive
27 | https://github.com/cocowalla/serilog-sinks-file-archive
28 | Serilog.Sinks.File.Archive
29 | Apache-2.0
30 | True
31 | ../../serilog-sinks-file-archive.snk
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 | <_Parameter1>$(AssemblyName).Test
56 |
57 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/src/Serilog.Sinks.File.Archive/TokenExpander.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text.RegularExpressions;
4 | using Serilog.Debugging;
5 |
6 | namespace Serilog.Sinks.File.Archive
7 | {
8 | ///
9 | /// Expands tokens in a string. Tokens should be in the form "{Name:format}", where "Name" is the name of a supported token, and
10 | /// "format" is a format string for that token.
11 | ///
12 | /// Supported tokens:
13 | /// Date Uses the specified format string to insert a local date/time string at the location in the string
14 | /// UtcDate Uses the specified format string to insert a UTC date/time string at the location in the string
15 | ///
16 | internal static class TokenExpander
17 | {
18 | private static readonly Regex TokenRegex = new Regex("{(?(?[a-zA-Z]+):(?[^}]+))}", RegexOptions.Compiled | RegexOptions.ECMAScript);
19 |
20 | private static readonly IDictionary> Expanders = new Dictionary>
21 | {
22 | { "Date", (source, token) => DateTime.Now.ToString(token.Format) },
23 | { "UtcDate", (source, token) => DateTime.UtcNow.ToString(token.Format) }
24 | };
25 |
26 | public static string Expand(string source)
27 | {
28 | int startIdx = 0;
29 | while (TryFindNextToken(source, startIdx, out var token))
30 | {
31 | // We found a token - is it supported?
32 | if (Expanders.TryGetValue(token.Name, out var expander))
33 | {
34 | var expanded = expander(source, token);
35 | source = source.Remove(token.StartIdx, token.Length);
36 | source = source.Insert(token.StartIdx, expanded);
37 |
38 | startIdx = token.StartIdx + expanded.Length;
39 | }
40 | else
41 | {
42 | SelfLog.WriteLine("Unsupported token: {0}", token.Name);
43 |
44 | startIdx = token.StartIdx + token.Length;
45 | }
46 | }
47 |
48 | return source;
49 | }
50 | public static bool IsTokenised(string source)
51 | {
52 | return TryFindNextToken(source, 0, out var _);
53 | }
54 |
55 | private static bool TryFindNextToken(string source, int startIdx, out Token token)
56 | {
57 | var match = TokenRegex.Match(source, startIdx);
58 |
59 | if (!match.Success)
60 | {
61 | token = null;
62 | return false;
63 | }
64 |
65 | token = new Token
66 | {
67 | StartIdx = match.Index,
68 | Length = match.Length,
69 | Name = match.Groups["Name"].Value,
70 | Format = match.Groups["Format"].Value
71 | };
72 |
73 | return true;
74 | }
75 |
76 | private class Token
77 | {
78 | public int StartIdx { get; set; }
79 | public int Length { get; set; }
80 | public string Name { get; set; }
81 | public string Format { get; set; }
82 | }
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/test/Serilog.Sinks.File.Archive.Test/RollingFileSinkTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.IO.Compression;
5 | using System.Linq;
6 | using Shouldly;
7 | using Xunit;
8 | using Serilog.Events;
9 | using Serilog.Sinks.File.Archive.Tests.Support;
10 |
11 | namespace Serilog.Sinks.File.Archive.Tests
12 | {
13 | public class RollingFileSinkTests
14 | {
15 | private static readonly LogEvent[] LogEvents = GenerateLogEvents(3).ToArray();
16 |
17 | // Test for removing old archive files in the same directory
18 | [Fact]
19 | public void Should_remove_old_archives()
20 | {
21 | const int retainedFiles = 1;
22 | var archiveWrapper = new ArchiveHooks(retainedFiles);
23 |
24 | using (var temp = TempFolder.ForCaller())
25 | {
26 | var path = temp.AllocateFilename("log");
27 |
28 | // Write events, such that we end up with 2 deleted files and 1 retained file
29 | WriteLogEvents(path, archiveWrapper, LogEvents);
30 |
31 | // Get all the files in the test directory
32 | var files = Directory.GetFiles(temp.Path)
33 | .OrderBy(p => p, StringComparer.OrdinalIgnoreCase)
34 | .ToArray();
35 |
36 | // We should have a single log file, and 'retainedFiles' gz files
37 | files.Count(x => x.EndsWith("log")).ShouldBe(1);
38 | files.Count(x => x.EndsWith("gz")).ShouldBe(retainedFiles);
39 |
40 | // Ensure the data was GZip compressed, by decompressing and comparing against what we wrote
41 | int i = LogEvents.Length - retainedFiles - 1;
42 | foreach (var gzipFile in files.Where(x => x.EndsWith("gz")))
43 | {
44 | var lines = Utils.DecompressLines(gzipFile);
45 |
46 | lines.Count.ShouldBe(1);
47 | lines[0].ShouldEndWith(LogEvents[i].MessageTemplate.Text);
48 | i++;
49 | }
50 | }
51 | }
52 |
53 | // Regression test for #19: https://github.com/cocowalla/serilog-sinks-file-archive/issues/19
54 | // Serilog RollingFileSink uses a 3-digit zero-filled suffix to denote the file index, but we want archive
55 | // rolling to continue to work when Serilog is configured to write 1,000+ files.
56 | [Fact]
57 | public void Should_remove_many_old_archives()
58 | {
59 | const int retainedFiles = 1;
60 | var archiveWrapper = new ArchiveHooks(retainedFiles);
61 | var logEvents = GenerateLogEvents(1_002).ToArray();
62 |
63 | using (var temp = TempFolder.ForCaller())
64 | {
65 | var path = temp.AllocateFilename("log");
66 |
67 | // Write events, such that we end up with 1,001 deleted files and 1 retained file
68 | WriteLogEvents(path, archiveWrapper, logEvents);
69 |
70 | // Get all the files in the test directory
71 | var files = Directory.GetFiles(temp.Path)
72 | .OrderBy(p => p, StringComparer.OrdinalIgnoreCase)
73 | .ToArray();
74 |
75 | // We should have a single log file, and 'retainedFiles' 1 gz files
76 | files.Count(x => x.EndsWith("log")).ShouldBe(1);
77 | files.Count(x => x.EndsWith("gz")).ShouldBe(retainedFiles);
78 |
79 | files.Single(x => x.EndsWith("gz")).ShouldEndWith("_1000.log.gz");
80 | files.Single(x => x.EndsWith("log")).ShouldEndWith("_1001.log");
81 |
82 | // Ensure the data was GZip compressed, by decompressing and comparing against what we wrote
83 | int i = logEvents.Length - retainedFiles - 1;
84 | foreach (var gzipFile in files.Where(x => x.EndsWith("gz")))
85 | {
86 | var lines = Utils.DecompressLines(gzipFile);
87 |
88 | lines.Count.ShouldBe(1);
89 | lines[0].ShouldEndWith(logEvents[i].MessageTemplate.Text);
90 | i++;
91 | }
92 | }
93 | }
94 |
95 | // Test for compressing log files in the same directory
96 | [Fact]
97 | public void Should_compress_deleting_log_files_in_place()
98 | {
99 | var archiveWrapper = new ArchiveHooks();
100 |
101 | using (var temp = TempFolder.ForCaller())
102 | {
103 | var path = temp.AllocateFilename("log");
104 |
105 | // Write events, such that we end up with 2 deleted files and 1 retained file
106 | WriteLogEvents(path, archiveWrapper, LogEvents);
107 |
108 | // Get all the files in the test directory
109 | var files = Directory.GetFiles(temp.Path)
110 | .OrderBy(p => p, StringComparer.OrdinalIgnoreCase)
111 | .ToArray();
112 |
113 | // We should have a single log file, and 2 gz files
114 | files.Count(x => x.EndsWith("log")).ShouldBe(1);
115 | files.Count(x => x.EndsWith("gz")).ShouldBe(2);
116 |
117 | // Ensure the data was GZip compressed, by decompressing and comparing against what we wrote
118 | int i = 0;
119 | foreach (var gzipFile in files.Where(x => x.EndsWith("gz")))
120 | {
121 | var lines = Utils.DecompressLines(gzipFile);
122 |
123 | lines.Count.ShouldBe(1);
124 | lines[0].ShouldEndWith(LogEvents[i].MessageTemplate.Text);
125 | i++;
126 | }
127 | }
128 | }
129 |
130 | // Test for copying log files to another directory
131 | [Fact]
132 | public void Should_copy_deleting_log_files()
133 | {
134 | using (var temp = TempFolder.ForCaller())
135 | {
136 | var targetDirPath = temp.AllocateFolderName();
137 | var path = temp.AllocateFilename("log");
138 |
139 | var archiveWrapper = new ArchiveHooks(CompressionLevel.NoCompression, targetDirPath);
140 |
141 | // Write events, such that we end up with 2 deleted files and 1 retained file
142 | WriteLogEvents(path, archiveWrapper, LogEvents);
143 |
144 | // Get all the files in the test directory
145 | var files = Directory.GetFiles(temp.Path)
146 | .OrderBy(p => p, StringComparer.OrdinalIgnoreCase)
147 | .ToArray();
148 |
149 | // We should only have a single log file
150 | files.Length.ShouldBe(1);
151 |
152 | // Get all the files in the target directory
153 | var targetFiles = Directory.GetFiles(targetDirPath)
154 | .OrderBy(p => p, StringComparer.OrdinalIgnoreCase)
155 | .ToArray();
156 |
157 | // We should have 2 log files in the target directory
158 | targetFiles.Length.ShouldBe(2);
159 | targetFiles.ShouldAllBe(x => x.EndsWith(".log"));
160 |
161 | // Ensure the content matches what we wrote
162 | for (var i = 0; i < targetFiles.Length; i++)
163 | {
164 | var lines = System.IO.File.ReadAllLines(targetFiles[i]);
165 |
166 | lines.Length.ShouldBe(1);
167 | lines[0].ShouldEndWith(LogEvents[i].MessageTemplate.Text);
168 | }
169 | }
170 | }
171 |
172 | // Test for writing compressed log files to another directory
173 | [Fact]
174 | public void Should_compress_deleting_log_files_in_target_dir()
175 | {
176 | using (var temp = TempFolder.ForCaller())
177 | {
178 | var targetDirPath = temp.AllocateFolderName();
179 | var path = temp.AllocateFilename("log");
180 |
181 | var archiveWrapper = new ArchiveHooks(CompressionLevel.Fastest, targetDirPath);
182 |
183 | // Write events, such that we end up with 2 deleted files and 1 retained file
184 | WriteLogEvents(path, archiveWrapper, LogEvents);
185 |
186 | // Get all the files in the test directory
187 | var files = Directory.GetFiles(temp.Path)
188 | .OrderBy(p => p, StringComparer.OrdinalIgnoreCase)
189 | .ToArray();
190 |
191 | // We should only have a single log file
192 | files.Length.ShouldBe(1);
193 |
194 | // Get all the files in the target directory
195 | var targetFiles = Directory.GetFiles(targetDirPath)
196 | .OrderBy(p => p, StringComparer.OrdinalIgnoreCase)
197 | .ToArray();
198 |
199 | // We should have 2 gz files in the target directory
200 | targetFiles.Length.ShouldBe(2);
201 | targetFiles.ShouldAllBe(x => x.EndsWith(".gz"));
202 |
203 | // Ensure the data was GZip compressed, by decompressing and comparing against what we wrote
204 | int i = 0;
205 | foreach (var gzipFile in targetFiles)
206 | {
207 | var lines = Utils.DecompressLines(gzipFile);
208 |
209 | lines.Count.ShouldBe(1);
210 | lines[0].ShouldEndWith(LogEvents[i].MessageTemplate.Text);
211 | i++;
212 | }
213 | }
214 | }
215 |
216 | [Fact]
217 | public void Should_expand_tokens_in_target_path()
218 | {
219 | using (var temp = TempFolder.ForCaller())
220 | {
221 | var subfolder = temp.AllocateFolderName();
222 | var targetDirPath = Path.Combine(subfolder, "{Date:yyyy}");
223 | var path = temp.AllocateFilename("log");
224 |
225 | var archiveWrapper = new ArchiveHooks(CompressionLevel.NoCompression, targetDirPath);
226 |
227 | // Write events, such that we end up with 2 deleted files and 1 retained file
228 | WriteLogEvents(path, archiveWrapper, LogEvents);
229 |
230 | // Get the final, expanded target directory
231 | var targetDirs = Directory.GetDirectories(subfolder);
232 | targetDirs.Length.ShouldBe(1);
233 |
234 | // Ensure the directory name contains the expanded date token
235 | targetDirs[0].ShouldEndWith(DateTime.Now.ToString("yyyy"));
236 | }
237 | }
238 |
239 | ///
240 | /// Write log events to Serilog, using a rolling log file configuration with a 1-byte size limit, so we roll
241 | /// after each log event, and with a retained count of 1 so 2 files will be deleted and 1 retained
242 | ///
243 | private static void WriteLogEvents(string path, ArchiveHooks hooks, LogEvent[] logEvents)
244 | {
245 | using (var log = new LoggerConfiguration()
246 | .WriteTo.File(path, rollOnFileSizeLimit: true, fileSizeLimitBytes: 1, retainedFileCountLimit: 1, hooks: hooks)
247 | .CreateLogger())
248 | {
249 | foreach (var logEvent in logEvents)
250 | {
251 | log.Write(logEvent);
252 | }
253 | }
254 | }
255 |
256 | private static IEnumerable GenerateLogEvents(int count)
257 | {
258 | for (var i = 0; i < count; i++)
259 | {
260 | yield return Some.LogEvent();
261 | }
262 | }
263 | }
264 | }
265 |
--------------------------------------------------------------------------------
/test/Serilog.Sinks.File.Archive.Test/Serilog.Sinks.File.Archive.Test.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net452;netcoreapp3.1;net6.0
5 | Serilog.Sinks.File.Archive.Tests
6 | Serilog.Sinks.File.Archive.Tests
7 | True
8 | ../../serilog-sinks-file-archive-test.snk
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/test/Serilog.Sinks.File.Archive.Test/Support/Some.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Threading;
4 | using Serilog.Events;
5 | using Serilog.Parsing;
6 |
7 | namespace Serilog.Sinks.File.Archive.Tests.Support
8 | {
9 | internal static class Some
10 | {
11 | private static int counter;
12 |
13 | public static int Int() =>
14 | Interlocked.Increment(ref counter);
15 |
16 | public static string String(string tag = null) =>
17 | (tag ?? "") + "__" + Int();
18 |
19 | public static DateTimeOffset Instant() =>
20 | new DateTimeOffset(new DateTime(2013, 12, 19) + TimeSpan.FromMinutes(Int()));
21 |
22 | public static LogEvent LogEvent(LogEventLevel level = LogEventLevel.Information, string text = null)
23 | => new LogEvent(Instant(), level, null, MessageTemplate(text), Enumerable.Empty());
24 |
25 | public static MessageTemplate MessageTemplate(string text = null) =>
26 | new MessageTemplateParser().Parse(text ?? String());
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/test/Serilog.Sinks.File.Archive.Test/Support/TestFolder.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Diagnostics;
3 | using System.IO;
4 | using System.Runtime.CompilerServices;
5 |
6 | namespace Serilog.Sinks.File.Archive.Tests.Support
7 | {
8 | internal class TempFolder : IDisposable
9 | {
10 | private static readonly Guid Session = Guid.NewGuid();
11 | public string Path { get; }
12 |
13 | public TempFolder(string name = null)
14 | {
15 | this.Path = System.IO.Path.Combine(
16 | Environment.GetEnvironmentVariable("TMP") ?? Environment.GetEnvironmentVariable("TMPDIR") ?? "/tmp",
17 | "Serilog.Sinks.File.Archive.Tests",
18 | Session.ToString("n"),
19 | name ?? Guid.NewGuid().ToString("n"));
20 |
21 | Directory.CreateDirectory(this.Path);
22 | }
23 |
24 | public void Dispose()
25 | {
26 | try
27 | {
28 | if (Directory.Exists(this.Path))
29 | Directory.Delete(this.Path, true);
30 | }
31 | catch (Exception ex)
32 | {
33 | Debug.WriteLine(ex);
34 | }
35 | }
36 |
37 | public static TempFolder ForCaller([CallerMemberName] string caller = null, [CallerFilePath] string sourceFileName = "")
38 | {
39 | if (caller == null) throw new ArgumentNullException(nameof(caller));
40 | if (sourceFileName == null) throw new ArgumentNullException(nameof(sourceFileName));
41 |
42 | var folderName = System.IO.Path.GetFileNameWithoutExtension(sourceFileName) + "_" + caller;
43 |
44 | return new TempFolder(folderName);
45 | }
46 |
47 | public string AllocateFilename(string ext = null)
48 | => System.IO.Path.Combine(this.Path, Guid.NewGuid().ToString("n") + "." + (ext ?? "tmp"));
49 |
50 | public string AllocateFolderName()
51 | => System.IO.Path.Combine(this.Path, Guid.NewGuid().ToString("n"));
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/test/Serilog.Sinks.File.Archive.Test/Support/Utils.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.IO;
3 | using System.IO.Compression;
4 |
5 | namespace Serilog.Sinks.File.Archive.Tests.Support
6 | {
7 | public static class Utils
8 | {
9 | public static List DecompressLines(string path)
10 | {
11 | using (var textStream = new MemoryStream())
12 | {
13 | using (var fs = System.IO.File.OpenRead(path))
14 | using (var decompressStream = new GZipStream(fs, CompressionMode.Decompress))
15 | {
16 | decompressStream.CopyTo(textStream);
17 | }
18 |
19 | textStream.Position = 0;
20 | var lines = textStream.ReadAllLines();
21 |
22 | return lines;
23 | }
24 | }
25 |
26 | public static List ReadAllLines(this Stream stream)
27 | {
28 | var lines = new List();
29 |
30 | using (var reader = new StreamReader(stream))
31 | {
32 | string line;
33 | while ((line = reader.ReadLine()) != null)
34 | {
35 | lines.Add(line);
36 | }
37 | }
38 |
39 | return lines;
40 | }
41 | }
42 | }
--------------------------------------------------------------------------------
/test/Serilog.Sinks.File.Archive.Test/TokenExpanderTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using Serilog.Debugging;
4 | using Shouldly;
5 | using Xunit;
6 |
7 | namespace Serilog.Sinks.File.Archive.Tests
8 | {
9 | public class TokenExpanderTests
10 | {
11 | [Fact]
12 | public void Should_expand_local_date_tokens()
13 | {
14 | const string input = "/my/path/{Date:yyyy}/{Date:MM}{Date:dd}";
15 | var result = TokenExpander.Expand(input);
16 |
17 | var dt = DateTime.Now;
18 | result.ShouldBe($"/my/path/{dt:yyyy}/{dt:MM}{dt:dd}");
19 | }
20 |
21 | [Fact]
22 | public void Should_expand_utc_date_tokens()
23 | {
24 | const string input = "/my/path/{UtcDate:yyyy}/{UtcDate:MM}{Date:dd}";
25 | var result = TokenExpander.Expand(input);
26 |
27 | var dt = DateTime.UtcNow;
28 | result.ShouldBe($"/my/path/{dt:yyyy}/{dt:MM}{dt:dd}");
29 | }
30 |
31 | // Test that we write diagnostic logs if unsupported token names are used
32 | [Fact]
33 | public void Should_log_unsupported_tokens()
34 | {
35 | var messages = new List();
36 | SelfLog.Enable(x => messages.Add(x));
37 |
38 | const string input = "/my/path/{Myergen:yyyy}/{Meh:MM}";
39 | var result = TokenExpander.Expand(input);
40 |
41 | // Result should be the unchanged input
42 | result.ShouldBe(input);
43 |
44 | // Ensure we wrote diagnostic logs
45 | messages.Count.ShouldBe(2);
46 | messages.ShouldAllBe(x => x.Contains("Unsupported token"));
47 | messages.ShouldContain(x => x.EndsWith("Myergen"));
48 | messages.ShouldContain(x => x.EndsWith("Meh"));
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------