|
| 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 | +#if OS_MUTEX |
| 16 | + |
| 17 | +using System; |
| 18 | +using System.IO; |
| 19 | +using System.Text; |
| 20 | +using Serilog.Core; |
| 21 | +using Serilog.Events; |
| 22 | +using Serilog.Formatting; |
| 23 | +using System.Threading; |
| 24 | +using Serilog.Debugging; |
| 25 | + |
| 26 | +namespace Serilog.Sinks.File |
| 27 | +{ |
| 28 | + /// <summary> |
| 29 | + /// Write log events to a disk file. |
| 30 | + /// </summary> |
| 31 | + public sealed class SharedFileSink : ILogEventSink, IFlushableFileSink, IDisposable |
| 32 | + { |
| 33 | + readonly TextWriter _output; |
| 34 | + readonly FileStream _underlyingStream; |
| 35 | + readonly ITextFormatter _textFormatter; |
| 36 | + readonly long? _fileSizeLimitBytes; |
| 37 | + readonly object _syncRoot = new object(); |
| 38 | + |
| 39 | + const string MutexNameSuffix = ".serilog"; |
| 40 | + const int MutexWaitTimeout = 10000; |
| 41 | + readonly Mutex _mutex; |
| 42 | + |
| 43 | + /// <summary>Construct a <see cref="FileSink"/>.</summary> |
| 44 | + /// <param name="path">Path to the file.</param> |
| 45 | + /// <param name="textFormatter">Formatter used to convert log events to text.</param> |
| 46 | + /// <param name="fileSizeLimitBytes">The approximate maximum size, in bytes, to which a log file will be allowed to grow. |
| 47 | + /// For unrestricted growth, pass null. The default is 1 GB. To avoid writing partial events, the last event within the limit |
| 48 | + /// will be written in full even if it exceeds the limit.</param> |
| 49 | + /// <param name="encoding">Character encoding used to write the text file. The default is UTF-8 without BOM.</param> |
| 50 | + /// <returns>Configuration object allowing method chaining.</returns> |
| 51 | + /// <remarks>The file will be written using the UTF-8 character set.</remarks> |
| 52 | + /// <exception cref="IOException"></exception> |
| 53 | + public SharedFileSink(string path, ITextFormatter textFormatter, long? fileSizeLimitBytes, Encoding encoding = null) |
| 54 | + { |
| 55 | + if (path == null) throw new ArgumentNullException(nameof(path)); |
| 56 | + if (textFormatter == null) throw new ArgumentNullException(nameof(textFormatter)); |
| 57 | + if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 0) |
| 58 | + throw new ArgumentException("Negative value provided; file size limit must be non-negative"); |
| 59 | + |
| 60 | + _textFormatter = textFormatter; |
| 61 | + _fileSizeLimitBytes = fileSizeLimitBytes; |
| 62 | + |
| 63 | + var directory = Path.GetDirectoryName(path); |
| 64 | + if (!string.IsNullOrWhiteSpace(directory) && !Directory.Exists(directory)) |
| 65 | + { |
| 66 | + Directory.CreateDirectory(directory); |
| 67 | + } |
| 68 | + |
| 69 | + var mutexName = Path.GetFullPath(path).Replace(Path.DirectorySeparatorChar, ':') + MutexNameSuffix; |
| 70 | + _mutex = new Mutex(false, mutexName); |
| 71 | + _underlyingStream = System.IO.File.Open(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); |
| 72 | + _output = new StreamWriter(_underlyingStream, encoding ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); |
| 73 | + } |
| 74 | + |
| 75 | + /// <summary> |
| 76 | + /// Emit the provided log event to the sink. |
| 77 | + /// </summary> |
| 78 | + /// <param name="logEvent">The log event to write.</param> |
| 79 | + public void Emit(LogEvent logEvent) |
| 80 | + { |
| 81 | + if (logEvent == null) throw new ArgumentNullException(nameof(logEvent)); |
| 82 | + |
| 83 | + lock (_syncRoot) |
| 84 | + { |
| 85 | + if (!TryAcquireMutex()) |
| 86 | + return; |
| 87 | + |
| 88 | + try |
| 89 | + { |
| 90 | + _underlyingStream.Seek(0, SeekOrigin.End); |
| 91 | + if (_fileSizeLimitBytes != null) |
| 92 | + { |
| 93 | + if (_underlyingStream.Length >= _fileSizeLimitBytes.Value) |
| 94 | + return; |
| 95 | + } |
| 96 | + |
| 97 | + _textFormatter.Format(logEvent, _output); |
| 98 | + _output.Flush(); |
| 99 | + _underlyingStream.Flush(); |
| 100 | + } |
| 101 | + finally |
| 102 | + { |
| 103 | + ReleaseMutex(); |
| 104 | + } |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + /// <inheritdoc /> |
| 109 | + public void Dispose() |
| 110 | + { |
| 111 | + lock (_syncRoot) |
| 112 | + { |
| 113 | + _output.Dispose(); |
| 114 | + _mutex.Dispose(); |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + /// <inheritdoc /> |
| 119 | + public void FlushToDisk() |
| 120 | + { |
| 121 | + lock (_syncRoot) |
| 122 | + { |
| 123 | + if (!TryAcquireMutex()) |
| 124 | + return; |
| 125 | + |
| 126 | + try |
| 127 | + { |
| 128 | + _underlyingStream.Flush(true); |
| 129 | + } |
| 130 | + finally |
| 131 | + { |
| 132 | + ReleaseMutex(); |
| 133 | + } |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + bool TryAcquireMutex() |
| 138 | + { |
| 139 | + try |
| 140 | + { |
| 141 | + if (!_mutex.WaitOne(MutexWaitTimeout)) |
| 142 | + { |
| 143 | + SelfLog.WriteLine("Shared file mutex could not be acquired within {0} ms", MutexWaitTimeout); |
| 144 | + return false; |
| 145 | + } |
| 146 | + } |
| 147 | + catch (AbandonedMutexException) |
| 148 | + { |
| 149 | + SelfLog.WriteLine("Inherited shared file mutex after abandonment by another process"); |
| 150 | + } |
| 151 | + |
| 152 | + return true; |
| 153 | + } |
| 154 | + |
| 155 | + void ReleaseMutex() |
| 156 | + { |
| 157 | + _mutex.ReleaseMutex(); |
| 158 | + } |
| 159 | + } |
| 160 | +} |
| 161 | + |
| 162 | +#endif |
0 commit comments