-
Notifications
You must be signed in to change notification settings - Fork 125
Multiprocess sharing on .NET Core #27
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
bce2b62
Fixes https://github.com/serilog/serilog-sinks-rollingfile/issues/37 …
nblumhardt 06e457a
Sharing on netstandard1.3; dispose _mutex; ten second timeout waiting…
nblumhardt b023427
Handle AbandonedMutexException(); exclude path separator char for Linux
nblumhardt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -234,3 +234,4 @@ _Pvt_Extensions | |
|
||
# FAKE - F# Make | ||
.fake/ | ||
example/Sample/log.txt |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
162 changes: 162 additions & 0 deletions
162
src/Serilog.Sinks.File/Sinks/File/SharedFileSink.OSMutex.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,162 @@ | ||
// Copyright 2013-2016 Serilog Contributors | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
#if OS_MUTEX | ||
|
||
using System; | ||
using System.IO; | ||
using System.Text; | ||
using Serilog.Core; | ||
using Serilog.Events; | ||
using Serilog.Formatting; | ||
using System.Threading; | ||
using Serilog.Debugging; | ||
|
||
namespace Serilog.Sinks.File | ||
{ | ||
/// <summary> | ||
/// Write log events to a disk file. | ||
/// </summary> | ||
public sealed class SharedFileSink : ILogEventSink, IFlushableFileSink, IDisposable | ||
{ | ||
readonly TextWriter _output; | ||
readonly FileStream _underlyingStream; | ||
readonly ITextFormatter _textFormatter; | ||
readonly long? _fileSizeLimitBytes; | ||
readonly object _syncRoot = new object(); | ||
|
||
const string MutexNameSuffix = ".serilog"; | ||
const int MutexWaitTimeout = 10000; | ||
readonly Mutex _mutex; | ||
|
||
/// <summary>Construct a <see cref="FileSink"/>.</summary> | ||
/// <param name="path">Path to the file.</param> | ||
/// <param name="textFormatter">Formatter used to convert log events to text.</param> | ||
/// <param name="fileSizeLimitBytes">The approximate maximum size, in bytes, to which a log file will be allowed to grow. | ||
/// For unrestricted growth, pass null. The default is 1 GB. To avoid writing partial events, the last event within the limit | ||
/// will be written in full even if it exceeds the limit.</param> | ||
/// <param name="encoding">Character encoding used to write the text file. The default is UTF-8 without BOM.</param> | ||
/// <returns>Configuration object allowing method chaining.</returns> | ||
/// <remarks>The file will be written using the UTF-8 character set.</remarks> | ||
/// <exception cref="IOException"></exception> | ||
public SharedFileSink(string path, ITextFormatter textFormatter, long? fileSizeLimitBytes, Encoding encoding = null) | ||
{ | ||
if (path == null) throw new ArgumentNullException(nameof(path)); | ||
if (textFormatter == null) throw new ArgumentNullException(nameof(textFormatter)); | ||
if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 0) | ||
throw new ArgumentException("Negative value provided; file size limit must be non-negative"); | ||
|
||
_textFormatter = textFormatter; | ||
_fileSizeLimitBytes = fileSizeLimitBytes; | ||
|
||
var directory = Path.GetDirectoryName(path); | ||
if (!string.IsNullOrWhiteSpace(directory) && !Directory.Exists(directory)) | ||
{ | ||
Directory.CreateDirectory(directory); | ||
} | ||
|
||
var mutexName = Path.GetFullPath(path).Replace(Path.DirectorySeparatorChar, ':') + MutexNameSuffix; | ||
_mutex = new Mutex(false, mutexName); | ||
_underlyingStream = System.IO.File.Open(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); | ||
_output = new StreamWriter(_underlyingStream, encoding ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); | ||
} | ||
|
||
/// <summary> | ||
/// Emit the provided log event to the sink. | ||
/// </summary> | ||
/// <param name="logEvent">The log event to write.</param> | ||
public void Emit(LogEvent logEvent) | ||
{ | ||
if (logEvent == null) throw new ArgumentNullException(nameof(logEvent)); | ||
|
||
lock (_syncRoot) | ||
{ | ||
if (!TryAcquireMutex()) | ||
return; | ||
|
||
try | ||
{ | ||
_underlyingStream.Seek(0, SeekOrigin.End); | ||
if (_fileSizeLimitBytes != null) | ||
{ | ||
if (_underlyingStream.Length >= _fileSizeLimitBytes.Value) | ||
return; | ||
} | ||
|
||
_textFormatter.Format(logEvent, _output); | ||
_output.Flush(); | ||
_underlyingStream.Flush(); | ||
} | ||
finally | ||
{ | ||
ReleaseMutex(); | ||
} | ||
} | ||
} | ||
|
||
/// <inheritdoc /> | ||
public void Dispose() | ||
{ | ||
lock (_syncRoot) | ||
{ | ||
_output.Dispose(); | ||
_mutex.Dispose(); | ||
} | ||
} | ||
|
||
/// <inheritdoc /> | ||
public void FlushToDisk() | ||
{ | ||
lock (_syncRoot) | ||
{ | ||
if (!TryAcquireMutex()) | ||
return; | ||
|
||
try | ||
{ | ||
_underlyingStream.Flush(true); | ||
} | ||
finally | ||
{ | ||
ReleaseMutex(); | ||
} | ||
} | ||
} | ||
|
||
bool TryAcquireMutex() | ||
{ | ||
try | ||
{ | ||
if (!_mutex.WaitOne(MutexWaitTimeout)) | ||
{ | ||
SelfLog.WriteLine("Shared file mutex could not be acquired within {0} ms", MutexWaitTimeout); | ||
return false; | ||
} | ||
} | ||
catch (AbandonedMutexException) | ||
{ | ||
SelfLog.WriteLine("Inherited shared file mutex after abandonment by another process"); | ||
} | ||
|
||
return true; | ||
} | ||
|
||
void ReleaseMutex() | ||
{ | ||
_mutex.ReleaseMutex(); | ||
} | ||
} | ||
} | ||
|
||
#endif |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -19,9 +19,6 @@ | |
] | ||
}, | ||
"net4.5.2": { | ||
"buildOptions": { | ||
"define": ["ATOMIC_APPEND"] | ||
} | ||
} | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I believe you should also handle
AbandonedMutexException
in case of another process crash and also protect against async exceptions with help of return value ofWaitOne()
:There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks, I'll look into it 👍