|
| 1 | +// Copyright 2019 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.Text; |
| 18 | + |
| 19 | +namespace Serilog.Sinks.File |
| 20 | +{ |
| 21 | + /// <summary> |
| 22 | + /// FileLifecycleHooks extension methods |
| 23 | + /// </summary> |
| 24 | + public static class FileLifecycleHooksExtensions |
| 25 | + { |
| 26 | + /// <summary> |
| 27 | + /// Creates a chain of <see cref="FileLifecycleHooks"/> that have their methods called sequentially |
| 28 | + /// Can be used to compose <see cref="FileLifecycleHooks"/> together; e.g. add header information to each log file and |
| 29 | + /// compress it. |
| 30 | + /// </summary> |
| 31 | + /// <example> |
| 32 | + /// <code> |
| 33 | + /// var hooks = new GZipHooks().ChainTo(new HeaderWriter("File Header")); |
| 34 | + /// </code> |
| 35 | + /// </example> |
| 36 | + /// <param name="first">The first <see cref="FileLifecycleHooks"/> to have its methods called in the chain</param> |
| 37 | + /// <param name="second">The second <see cref="FileLifecycleHooks"/> to have its methods called in the chain</param> |
| 38 | + /// <returns></returns> |
| 39 | + public static FileLifecycleHooks ChainTo(this FileLifecycleHooks first, FileLifecycleHooks second) |
| 40 | + { |
| 41 | + return new FileLifeCycleHookChain(first, second); |
| 42 | + } |
| 43 | + |
| 44 | + class FileLifeCycleHookChain : FileLifecycleHooks |
| 45 | + { |
| 46 | + private readonly FileLifecycleHooks[] hooks; |
| 47 | + |
| 48 | + public FileLifeCycleHookChain(params FileLifecycleHooks[] hooks) |
| 49 | + { |
| 50 | + this.hooks = hooks ?? throw new ArgumentNullException(nameof(hooks)); |
| 51 | + } |
| 52 | + |
| 53 | + public override Stream OnFileOpened(Stream underlyingStream, Encoding encoding) |
| 54 | + { |
| 55 | + for (int i = 0; i < hooks.Length; i++) |
| 56 | + { |
| 57 | + underlyingStream = hooks[i].OnFileOpened(underlyingStream, encoding); |
| 58 | + } |
| 59 | + return underlyingStream; |
| 60 | + } |
| 61 | + |
| 62 | + public override void OnFileDeleting(string path) |
| 63 | + { |
| 64 | + for (int i = 0; i < hooks.Length; i++) |
| 65 | + { |
| 66 | + hooks[i].OnFileDeleting(path); |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments