-
Notifications
You must be signed in to change notification settings - Fork 125
FileLifecycleHooks
#80
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 11 commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
f7bfe4e
Enabled FileSink and RollingFileSink's output stream in another strea…
cocowalla 9eee731
Rename StreamWrapper to FileLifecycleHooks
cocowalla 83d817f
Ignore Rider cache/options files
cocowalla 63c3601
Add docs re wrapped stream ownership
cocowalla fca6eb9
Check for directory existence before attempting access.
billrob 0c65484
Merge pull request #88 from billrob/dev
nblumhardt e604418
Improve log message when FileLifecycleHooks provided for a shared log…
cocowalla 873f6d4
Throw clear exception when wrapping the output stream returns null
cocowalla e310ab9
Throw when using hooks with a shared file
cocowalla 1864db1
Merge branch 'feature/stream-wrapper' of https://github.com/cocowalla…
nblumhardt b660b51
Make FileSink constructor changes non-breaking; fix a bug whereby a s…
nblumhardt b904968
Reenable an old test that was lost
nblumhardt b6090cc
A test for the encoding fix
nblumhardt 34344ad
Move FileLifecycleHooks down under Serilog.Sinks.File - avoids namesp…
nblumhardt 0ae234e
Enable hooks and encoding for auditing methods
nblumhardt 55fcb2b
Add backwards-compatible configuration overloads
nblumhardt d4fa80a
Expose encoding to OnOpened() hook; switch to AppVeyor Linux builds
nblumhardt 9f7352d
Fix Linux build script targets
nblumhardt ca0ac8c
Test for header writing
nblumhardt 5b3d64a
OnOpened() -> OnFileOpened()
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
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,37 @@ | ||
// Copyright 2019 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. | ||
|
||
using System.IO; | ||
|
||
namespace Serilog | ||
{ | ||
/// <summary> | ||
/// Enables hooking into log file lifecycle events. | ||
/// </summary> | ||
public abstract class FileLifecycleHooks | ||
{ | ||
/// <summary> | ||
/// Initialize or wrap the <paramref name="underlyingStream"/> opened on the log file. This can be used to write | ||
/// file headers, or wrap the stream in another that adds buffering, compression, encryption, etc. The underlying | ||
/// file may or may not be empty when this method is called. | ||
/// </summary> | ||
/// <remarks> | ||
/// A value must be returned from overrides of this method. Serilog will flush and/or dispose the returned value, but will not | ||
/// dispose the stream initially passed in unless it is itself returned. | ||
/// </remarks> | ||
/// <param name="underlyingStream">The underlying <see cref="Stream"/> opened on the log file.</param> | ||
/// <returns>The <see cref="Stream"/> Serilog should use when writing events to the log file.</returns> | ||
public virtual Stream OnOpened(Stream underlyingStream) => underlyingStream; | ||
} | ||
} |
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 |
---|---|---|
|
@@ -135,11 +135,12 @@ public static LoggerConfiguration File( | |
/// <param name="shared">Allow the log file to be shared by multiple processes. The default is false.</param> | ||
/// <param name="flushToDiskInterval">If provided, a full disk flush will be performed periodically at the specified interval.</param> | ||
/// <param name="rollingInterval">The interval at which logging will roll over to a new file.</param> | ||
/// <param name="rollOnFileSizeLimit">If <code>true</code>, a new file will be created when the file size limit is reached. Filenames | ||
/// <param name="rollOnFileSizeLimit">If <code>true</code>, a new file will be created when the file size limit is reached. Filenames | ||
/// will have a number appended in the format <code>_NNN</code>, with the first filename given no number.</param> | ||
/// <param name="retainedFileCountLimit">The maximum number of log files that will be retained, | ||
/// including the current log file. For unlimited retention, pass null. The default is 31.</param> | ||
/// <param name="encoding">Character encoding used to write the text file. The default is UTF-8 without BOM.</param> | ||
/// <param name="hooks">Optionally enables hooking into log file lifecycle events.</param> | ||
/// <returns>Configuration object allowing method chaining.</returns> | ||
/// <remarks>The file will be written using the UTF-8 character set.</remarks> | ||
public static LoggerConfiguration File( | ||
|
@@ -156,7 +157,8 @@ public static LoggerConfiguration File( | |
RollingInterval rollingInterval = RollingInterval.Infinite, | ||
bool rollOnFileSizeLimit = false, | ||
int? retainedFileCountLimit = DefaultRetainedFileCountLimit, | ||
Encoding encoding = null) | ||
Encoding encoding = null, | ||
FileLifecycleHooks hooks = null) | ||
{ | ||
if (sinkConfiguration == null) throw new ArgumentNullException(nameof(sinkConfiguration)); | ||
if (path == null) throw new ArgumentNullException(nameof(path)); | ||
|
@@ -165,7 +167,7 @@ public static LoggerConfiguration File( | |
var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider); | ||
return File(sinkConfiguration, formatter, path, restrictedToMinimumLevel, fileSizeLimitBytes, | ||
levelSwitch, buffered, shared, flushToDiskInterval, | ||
rollingInterval, rollOnFileSizeLimit, retainedFileCountLimit, encoding); | ||
rollingInterval, rollOnFileSizeLimit, retainedFileCountLimit, encoding, hooks); | ||
} | ||
|
||
/// <summary> | ||
|
@@ -174,7 +176,7 @@ public static LoggerConfiguration File( | |
/// <param name="sinkConfiguration">Logger sink configuration.</param> | ||
/// <param name="formatter">A formatter, such as <see cref="JsonFormatter"/>, to convert the log events into | ||
/// text for the file. If control of regular text formatting is required, use the other | ||
/// overload of <see cref="File(LoggerSinkConfiguration, string, LogEventLevel, string, IFormatProvider, long?, LoggingLevelSwitch, bool, bool, TimeSpan?, RollingInterval, bool, int?, Encoding)"/> | ||
/// overload of <see cref="File(LoggerSinkConfiguration, string, LogEventLevel, string, IFormatProvider, long?, LoggingLevelSwitch, bool, bool, TimeSpan?, RollingInterval, bool, int?, Encoding, FileLifecycleHooks)"/> | ||
/// and specify the outputTemplate parameter instead. | ||
/// </param> | ||
/// <param name="path">Path to the file.</param> | ||
|
@@ -190,11 +192,12 @@ public static LoggerConfiguration File( | |
/// <param name="shared">Allow the log file to be shared by multiple processes. The default is false.</param> | ||
/// <param name="flushToDiskInterval">If provided, a full disk flush will be performed periodically at the specified interval.</param> | ||
/// <param name="rollingInterval">The interval at which logging will roll over to a new file.</param> | ||
/// <param name="rollOnFileSizeLimit">If <code>true</code>, a new file will be created when the file size limit is reached. Filenames | ||
/// <param name="rollOnFileSizeLimit">If <code>true</code>, a new file will be created when the file size limit is reached. Filenames | ||
/// will have a number appended in the format <code>_NNN</code>, with the first filename given no number.</param> | ||
/// <param name="retainedFileCountLimit">The maximum number of log files that will be retained, | ||
/// including the current log file. For unlimited retention, pass null. The default is 31.</param> | ||
/// <param name="encoding">Character encoding used to write the text file. The default is UTF-8 without BOM.</param> | ||
/// <param name="hooks">Optionally enables hooking into log file lifecycle events.</param> | ||
/// <returns>Configuration object allowing method chaining.</returns> | ||
/// <remarks>The file will be written using the UTF-8 character set.</remarks> | ||
public static LoggerConfiguration File( | ||
|
@@ -210,10 +213,12 @@ public static LoggerConfiguration File( | |
RollingInterval rollingInterval = RollingInterval.Infinite, | ||
bool rollOnFileSizeLimit = false, | ||
int? retainedFileCountLimit = DefaultRetainedFileCountLimit, | ||
Encoding encoding = null) | ||
Encoding encoding = null, | ||
FileLifecycleHooks hooks = null) | ||
{ | ||
return ConfigureFile(sinkConfiguration.Sink, formatter, path, restrictedToMinimumLevel, fileSizeLimitBytes, levelSwitch, | ||
buffered, false, shared, flushToDiskInterval, encoding, rollingInterval, rollOnFileSizeLimit, retainedFileCountLimit); | ||
buffered, false, shared, flushToDiskInterval, encoding, rollingInterval, rollOnFileSizeLimit, | ||
retainedFileCountLimit, hooks); | ||
} | ||
|
||
/// <summary> | ||
|
@@ -270,7 +275,7 @@ public static LoggerConfiguration File( | |
LoggingLevelSwitch levelSwitch = null) | ||
{ | ||
return ConfigureFile(sinkConfiguration.Sink, formatter, path, restrictedToMinimumLevel, null, levelSwitch, false, true, | ||
false, null, null, RollingInterval.Infinite, false, null); | ||
false, null, null, RollingInterval.Infinite, false, null, null); | ||
} | ||
|
||
static LoggerConfiguration ConfigureFile( | ||
|
@@ -287,35 +292,37 @@ static LoggerConfiguration ConfigureFile( | |
Encoding encoding, | ||
RollingInterval rollingInterval, | ||
bool rollOnFileSizeLimit, | ||
int? retainedFileCountLimit) | ||
int? retainedFileCountLimit, | ||
FileLifecycleHooks hooks) | ||
{ | ||
if (addSink == null) throw new ArgumentNullException(nameof(addSink)); | ||
if (formatter == null) throw new ArgumentNullException(nameof(formatter)); | ||
if (path == null) throw new ArgumentNullException(nameof(path)); | ||
if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 0) throw new ArgumentException("Negative value provided; file size limit must be non-negative.", nameof(fileSizeLimitBytes)); | ||
if (retainedFileCountLimit.HasValue && retainedFileCountLimit < 1) throw new ArgumentException("At least one file must be retained.", nameof(retainedFileCountLimit)); | ||
if (shared && buffered) throw new ArgumentException("Buffered writes are not available when file sharing is enabled.", nameof(buffered)); | ||
if (shared && hooks != null) throw new ArgumentException("File lifecycle hooks are not currently supported for shared log files.", nameof(hooks)); | ||
|
||
ILogEventSink sink; | ||
|
||
if (rollOnFileSizeLimit || rollingInterval != RollingInterval.Infinite) | ||
{ | ||
sink = new RollingFileSink(path, formatter, fileSizeLimitBytes, retainedFileCountLimit, encoding, buffered, shared, rollingInterval, rollOnFileSizeLimit); | ||
sink = new RollingFileSink(path, formatter, fileSizeLimitBytes, retainedFileCountLimit, encoding, buffered, shared, rollingInterval, rollOnFileSizeLimit, hooks); | ||
} | ||
else | ||
{ | ||
try | ||
{ | ||
#pragma warning disable 618 | ||
if (shared) | ||
{ | ||
sink = new SharedFileSink(path, formatter, fileSizeLimitBytes); | ||
#pragma warning disable 618 | ||
sink = new SharedFileSink(path, formatter, fileSizeLimitBytes, encoding); | ||
#pragma warning restore 618 | ||
} | ||
else | ||
{ | ||
sink = new FileSink(path, formatter, fileSizeLimitBytes, buffered: buffered); | ||
sink = new FileSink(path, formatter, fileSizeLimitBytes, encoding, buffered, hooks); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I am not sure why |
||
} | ||
#pragma warning restore 618 | ||
} | ||
catch (Exception ex) | ||
{ | ||
|
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
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
Oops, something went wrong.
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.
One of the target use cases is writing headers e.g. to CSV/W3C log files, so the name
Wrap()
might be too specific. I've triedOnOpened()
here, with the possibility of addingOnOpening(path)
and possibly anOnClosing(stream)
/OnClosed(path)
pair later on.If we make this
virtual
rather thanabstract
, we won't introduce inconsistencies when future hooks are added (since these must bevirtual
to avoid breakage).All sounds sane?
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.
Actually, we discussed this a while back in this thread, and it looks like I just forgot to rename this!
virtual
reasoning also makes sense.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.
Back when we started discussing this there was the question of streaming vs 'static' extensibility points and this PR solves the streaming part.
Later bolting on
OnOpening(path)
,OnClosing(stream)
/OnClosed(path)
would solve the 'static' part, enabling scenarios such as cryptographically signing files before they are closed, shipping closed files to WORM media, perform (non-streaming) compression and/or encryption etc 👍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.
Ha! I actually like the name we were using in the earlier comments a little better, on reflection. I'll rename to
OnFileOpened()
and merge away! :-)