From 94d3b46fe652ad1007aa86428edff20c68d2b6b3 Mon Sep 17 00:00:00 2001 From: Matthew Erbs Date: Thu, 17 Mar 2016 14:28:33 +1000 Subject: [PATCH] Removed remaining sinks and specific sink tests. --- Serilog.sln | 42 --- .../FileLoggerConfigurationExtensions.cs | 80 ----- .../Properties/AssemblyInfo.cs | 14 - .../Serilog.Sinks.File.xproj | 18 -- .../File/CharacterCountLimitedTextWriter.cs | 74 ----- src/Serilog.Sinks.File/Sinks/File/FileSink.cs | 110 ------- src/Serilog.Sinks.File/Sinks/File/NullSink.cs | 30 -- src/Serilog.Sinks.File/project.json | 26 -- ...ObservableLoggerConfigurationExtensions.cs | 49 --- .../Properties/AssemblyInfo.cs | 14 - .../Serilog.Sinks.Observable.xproj | 18 -- .../Sinks/Observable/ObservableSink.cs | 135 -------- src/Serilog.Sinks.Observable/project.json | 24 -- .../Properties/AssemblyInfo.cs | 14 - .../Serilog.Sinks.PeriodicBatching.xproj | 18 -- .../BatchedConnectionStatus.cs | 95 ------ .../PeriodicBatching/PeriodicBatchingSink.cs | 289 ------------------ .../Sinks/PeriodicBatching/PortableTimer.cs | 110 ------- .../project.json | 27 -- .../Properties/AssemblyInfo.cs | 14 - ...ollingFileLoggerConfigurationExtensions.cs | 71 ----- .../Serilog.Sinks.RollingFile.xproj | 20 -- .../Sinks/RollingFile/Clock.cs | 38 --- .../Sinks/RollingFile/RollingFileSink.cs | 233 -------------- .../Sinks/RollingFile/RollingLogFile.cs | 34 --- .../Sinks/RollingFile/TemplatedPathRoller.cs | 126 -------- src/Serilog.Sinks.RollingFile/project.json | 26 -- .../Properties/AssemblyInfo.cs | 14 - .../Serilog.Sinks.TextWriter.xproj | 18 -- .../Sinks/TextWriter/TextWriterSink.cs | 46 --- ...TextWriterLoggerConfigurationExtensions.cs | 58 ---- src/Serilog.Sinks.TextWriter/project.json | 24 -- .../Sinks/IOFile/FileSinkTests.cs | 91 ------ .../Sinks/Observable/ObservableSinkTests.cs | 25 -- .../BatchedConnectionStatusTests.cs | 80 ----- .../PeriodicBatchingSinkTests.cs | 105 ------- .../Sinks/RollingFile/RollingFileSinkTests.cs | 116 ------- .../RollingFile/TemplatedPathRollerTests.cs | 132 -------- .../Sinks/TextWriter/TextWriterSinkTests.cs | 44 --- test/Serilog.Tests/project.json | 13 +- 40 files changed, 6 insertions(+), 2509 deletions(-) delete mode 100644 src/Serilog.Sinks.File/FileLoggerConfigurationExtensions.cs delete mode 100644 src/Serilog.Sinks.File/Properties/AssemblyInfo.cs delete mode 100644 src/Serilog.Sinks.File/Serilog.Sinks.File.xproj delete mode 100644 src/Serilog.Sinks.File/Sinks/File/CharacterCountLimitedTextWriter.cs delete mode 100644 src/Serilog.Sinks.File/Sinks/File/FileSink.cs delete mode 100644 src/Serilog.Sinks.File/Sinks/File/NullSink.cs delete mode 100644 src/Serilog.Sinks.File/project.json delete mode 100644 src/Serilog.Sinks.Observable/ObservableLoggerConfigurationExtensions.cs delete mode 100644 src/Serilog.Sinks.Observable/Properties/AssemblyInfo.cs delete mode 100644 src/Serilog.Sinks.Observable/Serilog.Sinks.Observable.xproj delete mode 100644 src/Serilog.Sinks.Observable/Sinks/Observable/ObservableSink.cs delete mode 100644 src/Serilog.Sinks.Observable/project.json delete mode 100644 src/Serilog.Sinks.PeriodicBatching/Properties/AssemblyInfo.cs delete mode 100644 src/Serilog.Sinks.PeriodicBatching/Serilog.Sinks.PeriodicBatching.xproj delete mode 100644 src/Serilog.Sinks.PeriodicBatching/Sinks/PeriodicBatching/BatchedConnectionStatus.cs delete mode 100644 src/Serilog.Sinks.PeriodicBatching/Sinks/PeriodicBatching/PeriodicBatchingSink.cs delete mode 100644 src/Serilog.Sinks.PeriodicBatching/Sinks/PeriodicBatching/PortableTimer.cs delete mode 100644 src/Serilog.Sinks.PeriodicBatching/project.json delete mode 100644 src/Serilog.Sinks.RollingFile/Properties/AssemblyInfo.cs delete mode 100644 src/Serilog.Sinks.RollingFile/RollingFileLoggerConfigurationExtensions.cs delete mode 100644 src/Serilog.Sinks.RollingFile/Serilog.Sinks.RollingFile.xproj delete mode 100644 src/Serilog.Sinks.RollingFile/Sinks/RollingFile/Clock.cs delete mode 100644 src/Serilog.Sinks.RollingFile/Sinks/RollingFile/RollingFileSink.cs delete mode 100644 src/Serilog.Sinks.RollingFile/Sinks/RollingFile/RollingLogFile.cs delete mode 100644 src/Serilog.Sinks.RollingFile/Sinks/RollingFile/TemplatedPathRoller.cs delete mode 100644 src/Serilog.Sinks.RollingFile/project.json delete mode 100644 src/Serilog.Sinks.TextWriter/Properties/AssemblyInfo.cs delete mode 100644 src/Serilog.Sinks.TextWriter/Serilog.Sinks.TextWriter.xproj delete mode 100644 src/Serilog.Sinks.TextWriter/Sinks/TextWriter/TextWriterSink.cs delete mode 100644 src/Serilog.Sinks.TextWriter/TextWriterLoggerConfigurationExtensions.cs delete mode 100644 src/Serilog.Sinks.TextWriter/project.json delete mode 100644 test/Serilog.Tests/Sinks/IOFile/FileSinkTests.cs delete mode 100644 test/Serilog.Tests/Sinks/Observable/ObservableSinkTests.cs delete mode 100644 test/Serilog.Tests/Sinks/PeriodicBatching/BatchedConnectionStatusTests.cs delete mode 100644 test/Serilog.Tests/Sinks/PeriodicBatching/PeriodicBatchingSinkTests.cs delete mode 100644 test/Serilog.Tests/Sinks/RollingFile/RollingFileSinkTests.cs delete mode 100644 test/Serilog.Tests/Sinks/RollingFile/TemplatedPathRollerTests.cs delete mode 100644 test/Serilog.Tests/Sinks/TextWriter/TextWriterSinkTests.cs diff --git a/Serilog.sln b/Serilog.sln index 9cc99eceb..d1d8d145c 100644 --- a/Serilog.sln +++ b/Serilog.sln @@ -21,18 +21,6 @@ Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Serilog", "src\Serilog\Seri EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Serilog.Tests", "test\Serilog.Tests\Serilog.Tests.xproj", "{3C2D8E01-5580-426A-BDD9-EC59CD98E618}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Serilog.Sinks.RollingFile", "src\Serilog.Sinks.RollingFile\Serilog.Sinks.RollingFile.xproj", "{A3E6E5B4-995F-4C3D-9673-A4B6000F4E21}" -EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Serilog.Sinks.PeriodicBatching", "src\Serilog.Sinks.PeriodicBatching\Serilog.Sinks.PeriodicBatching.xproj", "{324C2F52-D9F7-4844-9BC4-9906E228D380}" -EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Serilog.Sinks.Observable", "src\Serilog.Sinks.Observable\Serilog.Sinks.Observable.xproj", "{8D6C0BB9-D04D-49B6-9043-4A776AD275D5}" -EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Serilog.Sinks.File", "src\Serilog.Sinks.File\Serilog.Sinks.File.xproj", "{57E0ED0E-0F45-48AB-A73D-6A92B7C32095}" -EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Serilog.Sinks.TextWriter", "src\Serilog.Sinks.TextWriter\Serilog.Sinks.TextWriter.xproj", "{E85ABEC7-9B4C-432C-9A04-AC5BE9205D9F}" -EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Serilog.Sinks.Trace", "src\Serilog.Sinks.Trace\Serilog.Sinks.Trace.xproj", "{8849C92D-2120-4C82-8226-22DF40195237}" -EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Serilog.Settings.AppSettings", "src\Serilog.Settings.AppSettings\Serilog.Settings.AppSettings.xproj", "{0D9F37E3-2CB4-4C0D-A307-32BB71DEFDD4}" EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Serilog.Enrichers.Environment", "src\Serilog.Enrichers.Environment\Serilog.Enrichers.Environment.xproj", "{B884782D-6C07-4779-9074-D97F622799A9}" @@ -55,30 +43,6 @@ Global {3C2D8E01-5580-426A-BDD9-EC59CD98E618}.Debug|Any CPU.Build.0 = Debug|Any CPU {3C2D8E01-5580-426A-BDD9-EC59CD98E618}.Release|Any CPU.ActiveCfg = Release|Any CPU {3C2D8E01-5580-426A-BDD9-EC59CD98E618}.Release|Any CPU.Build.0 = Release|Any CPU - {A3E6E5B4-995F-4C3D-9673-A4B6000F4E21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A3E6E5B4-995F-4C3D-9673-A4B6000F4E21}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A3E6E5B4-995F-4C3D-9673-A4B6000F4E21}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A3E6E5B4-995F-4C3D-9673-A4B6000F4E21}.Release|Any CPU.Build.0 = Release|Any CPU - {324C2F52-D9F7-4844-9BC4-9906E228D380}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {324C2F52-D9F7-4844-9BC4-9906E228D380}.Debug|Any CPU.Build.0 = Debug|Any CPU - {324C2F52-D9F7-4844-9BC4-9906E228D380}.Release|Any CPU.ActiveCfg = Release|Any CPU - {324C2F52-D9F7-4844-9BC4-9906E228D380}.Release|Any CPU.Build.0 = Release|Any CPU - {8D6C0BB9-D04D-49B6-9043-4A776AD275D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8D6C0BB9-D04D-49B6-9043-4A776AD275D5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8D6C0BB9-D04D-49B6-9043-4A776AD275D5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8D6C0BB9-D04D-49B6-9043-4A776AD275D5}.Release|Any CPU.Build.0 = Release|Any CPU - {57E0ED0E-0F45-48AB-A73D-6A92B7C32095}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {57E0ED0E-0F45-48AB-A73D-6A92B7C32095}.Debug|Any CPU.Build.0 = Debug|Any CPU - {57E0ED0E-0F45-48AB-A73D-6A92B7C32095}.Release|Any CPU.ActiveCfg = Release|Any CPU - {57E0ED0E-0F45-48AB-A73D-6A92B7C32095}.Release|Any CPU.Build.0 = Release|Any CPU - {E85ABEC7-9B4C-432C-9A04-AC5BE9205D9F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E85ABEC7-9B4C-432C-9A04-AC5BE9205D9F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E85ABEC7-9B4C-432C-9A04-AC5BE9205D9F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E85ABEC7-9B4C-432C-9A04-AC5BE9205D9F}.Release|Any CPU.Build.0 = Release|Any CPU - {8849C92D-2120-4C82-8226-22DF40195237}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8849C92D-2120-4C82-8226-22DF40195237}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8849C92D-2120-4C82-8226-22DF40195237}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8849C92D-2120-4C82-8226-22DF40195237}.Release|Any CPU.Build.0 = Release|Any CPU {0D9F37E3-2CB4-4C0D-A307-32BB71DEFDD4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0D9F37E3-2CB4-4C0D-A307-32BB71DEFDD4}.Debug|Any CPU.Build.0 = Debug|Any CPU {0D9F37E3-2CB4-4C0D-A307-32BB71DEFDD4}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -102,12 +66,6 @@ Global GlobalSection(NestedProjects) = preSolution {803CD13A-D54B-4CEC-A55F-E22AE3D93B3C} = {037440DE-440B-4129-9F7A-09B42D00397E} {3C2D8E01-5580-426A-BDD9-EC59CD98E618} = {0D135C0C-A60B-454A-A2F4-CD74A30E04B0} - {A3E6E5B4-995F-4C3D-9673-A4B6000F4E21} = {037440DE-440B-4129-9F7A-09B42D00397E} - {324C2F52-D9F7-4844-9BC4-9906E228D380} = {037440DE-440B-4129-9F7A-09B42D00397E} - {8D6C0BB9-D04D-49B6-9043-4A776AD275D5} = {037440DE-440B-4129-9F7A-09B42D00397E} - {57E0ED0E-0F45-48AB-A73D-6A92B7C32095} = {037440DE-440B-4129-9F7A-09B42D00397E} - {E85ABEC7-9B4C-432C-9A04-AC5BE9205D9F} = {037440DE-440B-4129-9F7A-09B42D00397E} - {8849C92D-2120-4C82-8226-22DF40195237} = {037440DE-440B-4129-9F7A-09B42D00397E} {0D9F37E3-2CB4-4C0D-A307-32BB71DEFDD4} = {037440DE-440B-4129-9F7A-09B42D00397E} {B884782D-6C07-4779-9074-D97F622799A9} = {037440DE-440B-4129-9F7A-09B42D00397E} {2312A998-5E53-4355-9CB6-6014252B3E88} = {037440DE-440B-4129-9F7A-09B42D00397E} diff --git a/src/Serilog.Sinks.File/FileLoggerConfigurationExtensions.cs b/src/Serilog.Sinks.File/FileLoggerConfigurationExtensions.cs deleted file mode 100644 index 38ad9cf9b..000000000 --- a/src/Serilog.Sinks.File/FileLoggerConfigurationExtensions.cs +++ /dev/null @@ -1,80 +0,0 @@ -// 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. - -using System; -using Serilog.Configuration; -using Serilog.Core; -using Serilog.Debugging; -using Serilog.Events; -using Serilog.Formatting.Display; -using Serilog.Sinks.File; - -namespace Serilog -{ - public static class FileLoggerConfigurationExtensions - { - const long DefaultFileSizeLimitBytes = 1L * 1024 * 1024 * 1024; - const string DefaultOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"; - - /// - /// Write log events to the specified file. - /// - /// Logger sink configuration. - /// Path to the file. - /// The minimum level for - /// events passed through the sink. Ignored when is specified. - /// A switch allowing the pass-through minimum level - /// to be changed at runtime. - /// Supplies culture-specific formatting information, or null. - /// A message template describing the format used to write to the sink. - /// the default is "{Timestamp} [{Level}] {Message}{NewLine}{Exception}". - /// The maximum size, in bytes, to which a log file will be allowed to grow. - /// For unrestricted growth, pass null. The default is 1 GB. - /// Indicates if flushing to the output file can be buffered or not. The default - /// is false. - /// Configuration object allowing method chaining. - /// The file will be written using the UTF-8 character set. - public static LoggerConfiguration File( - this LoggerSinkConfiguration sinkConfiguration, - string path, - LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, - string outputTemplate = DefaultOutputTemplate, - IFormatProvider formatProvider = null, - long? fileSizeLimitBytes = DefaultFileSizeLimitBytes, - LoggingLevelSwitch levelSwitch = null, - bool buffered = false) - { - if (sinkConfiguration == null) throw new ArgumentNullException(nameof(sinkConfiguration)); - if (outputTemplate == null) throw new ArgumentNullException(nameof(outputTemplate)); - var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider); - - FileSink sink; - try - { - sink = new FileSink(path, formatter, fileSizeLimitBytes, buffered: buffered); - } - catch (ArgumentException) - { - throw; - } - catch (Exception ex) - { - SelfLog.WriteLine("Unable to open file sink for {0}: {1}", path, ex); - return sinkConfiguration.Sink(new NullSink()); - } - - return sinkConfiguration.Sink(sink, restrictedToMinimumLevel, levelSwitch); - } - } -} \ No newline at end of file diff --git a/src/Serilog.Sinks.File/Properties/AssemblyInfo.cs b/src/Serilog.Sinks.File/Properties/AssemblyInfo.cs deleted file mode 100644 index 1237c0e24..000000000 --- a/src/Serilog.Sinks.File/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Reflection; -using System.Runtime.CompilerServices; - -[assembly: AssemblyVersion("2.0.0.0")] - -[assembly: CLSCompliant(true)] - -[assembly: InternalsVisibleTo("Serilog.Tests, PublicKey=" + - "0024000004800000940000000602000000240000525341310004000001000100fb8d13fd344a1c" + - "6fe0fe83ef33c1080bf30690765bc6eb0df26ebfdf8f21670c64265b30db09f73a0dea5b3db4c9" + - "d18dbf6d5a25af5ce9016f281014d79dc3b4201ac646c451830fc7e61a2dfd633d34c39f87b818" + - "94191652df5ac63cc40c77f3542f702bda692e6e8a9158353df189007a49da0f3cfd55eb250066" + - "b19485ec")] diff --git a/src/Serilog.Sinks.File/Serilog.Sinks.File.xproj b/src/Serilog.Sinks.File/Serilog.Sinks.File.xproj deleted file mode 100644 index 250fa02af..000000000 --- a/src/Serilog.Sinks.File/Serilog.Sinks.File.xproj +++ /dev/null @@ -1,18 +0,0 @@ - - - - 14.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - 57e0ed0e-0f45-48ab-a73d-6a92b7c32095 - Serilog - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ - - - 2.0 - - - \ No newline at end of file diff --git a/src/Serilog.Sinks.File/Sinks/File/CharacterCountLimitedTextWriter.cs b/src/Serilog.Sinks.File/Sinks/File/CharacterCountLimitedTextWriter.cs deleted file mode 100644 index f44431686..000000000 --- a/src/Serilog.Sinks.File/Sinks/File/CharacterCountLimitedTextWriter.cs +++ /dev/null @@ -1,74 +0,0 @@ -// 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. - -using System; -using System.IO; -using System.Text; -using System.Threading; - -namespace Serilog.Sinks.File -{ - sealed class CharacterCountLimitedTextWriter : TextWriter - { - readonly TextWriter _outputWriter; - long _remainingCharacters; - - public CharacterCountLimitedTextWriter(TextWriter outputWriter, long remainingCharacters) - { - if (outputWriter == null) throw new ArgumentNullException(nameof(outputWriter)); - _outputWriter = outputWriter; - _remainingCharacters = remainingCharacters; - } - - public override Encoding Encoding => _outputWriter.Encoding; - - protected override void Dispose(bool disposing) - { - if (disposing) - _outputWriter.Dispose(); - - base.Dispose(disposing); - } - - public override void Write(char value) - { - var remaining = Interlocked.Decrement(ref _remainingCharacters); - if (remaining >= 0) - { - _outputWriter.Write(value); - } - else - { - // Prevent underflow (interlocking prevents torn reads) - Interlocked.Exchange(ref _remainingCharacters, 0L); - } - } - - public override void Write(char[] buffer, int index, int count) - { - var remaining = Interlocked.Add(ref _remainingCharacters, -count); - if (remaining >= 0) - { - _outputWriter.Write(buffer, index, count); - } - else - { - // Prevent underflow (interlocking prevents torn reads) - Interlocked.Exchange(ref _remainingCharacters, 0L); - } - } - - public override void Flush() => _outputWriter.Flush(); - } -} \ No newline at end of file diff --git a/src/Serilog.Sinks.File/Sinks/File/FileSink.cs b/src/Serilog.Sinks.File/Sinks/File/FileSink.cs deleted file mode 100644 index 5c92ff013..000000000 --- a/src/Serilog.Sinks.File/Sinks/File/FileSink.cs +++ /dev/null @@ -1,110 +0,0 @@ -// 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. - -using System; -using System.IO; -using System.Text; -using Serilog.Core; -using Serilog.Debugging; -using Serilog.Events; -using Serilog.Formatting; - -namespace Serilog.Sinks.File -{ - /// - /// Write log events to a disk file. - /// - public sealed class FileSink : ILogEventSink, IDisposable - { - const int BytesPerCharacterApproximate = 1; - readonly TextWriter _output; - readonly ITextFormatter _textFormatter; - readonly bool _buffered; - readonly object _syncRoot = new object(); - - /// Construct a . - /// Path to the file. - /// Formatter used to convert log events to text. - /// The maximum size, in bytes, to which a log file will be allowed to grow. - /// For unrestricted growth, pass null. The default is 1 GB. - /// Character encoding used to write the text file. The default is UTF-8. - /// Indicates if flushing to the output file can be buffered or not. The default - /// is false. - /// Configuration object allowing method chaining. - /// The file will be written using the UTF-8 character set. - /// - public FileSink(string path, ITextFormatter textFormatter, long? fileSizeLimitBytes, Encoding encoding = null, - bool buffered = false) - { - 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; - _buffered = buffered; - - TryCreateDirectory(path); - - var file = System.IO.File.Open(path, FileMode.Append, FileAccess.Write, FileShare.Read); - var outputWriter = new StreamWriter(file, encoding ?? Encoding.UTF8); - if (fileSizeLimitBytes != null) - { - var initialBytes = file.Length; - var remainingCharacters = Math.Max(fileSizeLimitBytes.Value - initialBytes, 0L) / BytesPerCharacterApproximate; - _output = new CharacterCountLimitedTextWriter(outputWriter, remainingCharacters); - } - else - { - _output = outputWriter; - } - } - - static void TryCreateDirectory(string path) - { - try - { - var directory = Path.GetDirectoryName(path); - if (!string.IsNullOrWhiteSpace(directory) && !Directory.Exists(directory)) - { - Directory.CreateDirectory(directory); - } - } - catch (Exception ex) - { - SelfLog.WriteLine("Failed to create directory {0}: {1}", path, ex); - } - } - - /// - /// Emit the provided log event to the sink. - /// - /// The log event to write. - public void Emit(LogEvent logEvent) - { - if (logEvent == null) throw new ArgumentNullException(nameof(logEvent)); - lock (_syncRoot) - { - _textFormatter.Format(logEvent, _output); - if (!_buffered) - _output.Flush(); - } - } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or - /// resetting unmanaged resources. - /// - public void Dispose() => _output.Dispose(); - } -} \ No newline at end of file diff --git a/src/Serilog.Sinks.File/Sinks/File/NullSink.cs b/src/Serilog.Sinks.File/Sinks/File/NullSink.cs deleted file mode 100644 index 5e9bb2ca0..000000000 --- a/src/Serilog.Sinks.File/Sinks/File/NullSink.cs +++ /dev/null @@ -1,30 +0,0 @@ -// 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. - -using Serilog.Core; -using Serilog.Events; - -namespace Serilog.Sinks.File -{ - /// - /// An instance of this sink may be substituted when an instance of the - /// is unable to be constructed. - /// - class NullSink : ILogEventSink - { - public void Emit(LogEvent logEvent) - { - } - } -} \ No newline at end of file diff --git a/src/Serilog.Sinks.File/project.json b/src/Serilog.Sinks.File/project.json deleted file mode 100644 index 905977c86..000000000 --- a/src/Serilog.Sinks.File/project.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "version": "2.0.0-beta-*", - "description": "The file sink for Serilog", - "authors": [ "Serilog Contributors" ], - "tags": [ "serilog", "file", "io" ], - "projectUrl": "http://serilog.net", - "licenseUrl": "http://www.apache.org/licenses/LICENSE-2.0", - "iconUrl": "http://serilog.net/images/serilog-sink-nuget.png", - "dependencies": { - "Serilog": { "target": "project" } - }, - "compilationOptions": { - "keyFile": "../../assets/Serilog.snk" - }, - "frameworks": { - "net45": { - }, - "dotnet5.1": { - "dependencies": { - "System.IO": "4.0.11-beta-23516", - "System.IO.FileSystem": "4.0.0", - "System.IO.FileSystem.Primitives": "4.0.0" - } - } - } -} \ No newline at end of file diff --git a/src/Serilog.Sinks.Observable/ObservableLoggerConfigurationExtensions.cs b/src/Serilog.Sinks.Observable/ObservableLoggerConfigurationExtensions.cs deleted file mode 100644 index 330fe18f5..000000000 --- a/src/Serilog.Sinks.Observable/ObservableLoggerConfigurationExtensions.cs +++ /dev/null @@ -1,49 +0,0 @@ -// 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. - - -using System; -using Serilog.Configuration; -using Serilog.Core; -using Serilog.Events; -using Serilog.Sinks.Observable; - -namespace Serilog -{ - public static class ObservableLoggerConfigurationExtensions - { - /// - /// Write events to Rx observers. - /// - /// Logger sink configuration. - /// An action that provides an observable - /// to which observers can subscribe. - /// The minimum level for - /// events passed through the sink. Ignored when is specified. - /// A switch allowing the pass-through minimum level - /// to be changed at runtime. - /// Configuration object allowing method chaining. - public static LoggerConfiguration Observers( - this LoggerSinkConfiguration sinkConfiguration, - Action> configureObservers, - LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, - LoggingLevelSwitch levelSwitch = null) - { - if (configureObservers == null) throw new ArgumentNullException(nameof(configureObservers)); - var observable = new ObservableSink(); - configureObservers(observable); - return sinkConfiguration.Sink(observable, restrictedToMinimumLevel, levelSwitch); - } - } -} \ No newline at end of file diff --git a/src/Serilog.Sinks.Observable/Properties/AssemblyInfo.cs b/src/Serilog.Sinks.Observable/Properties/AssemblyInfo.cs deleted file mode 100644 index 1237c0e24..000000000 --- a/src/Serilog.Sinks.Observable/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Reflection; -using System.Runtime.CompilerServices; - -[assembly: AssemblyVersion("2.0.0.0")] - -[assembly: CLSCompliant(true)] - -[assembly: InternalsVisibleTo("Serilog.Tests, PublicKey=" + - "0024000004800000940000000602000000240000525341310004000001000100fb8d13fd344a1c" + - "6fe0fe83ef33c1080bf30690765bc6eb0df26ebfdf8f21670c64265b30db09f73a0dea5b3db4c9" + - "d18dbf6d5a25af5ce9016f281014d79dc3b4201ac646c451830fc7e61a2dfd633d34c39f87b818" + - "94191652df5ac63cc40c77f3542f702bda692e6e8a9158353df189007a49da0f3cfd55eb250066" + - "b19485ec")] diff --git a/src/Serilog.Sinks.Observable/Serilog.Sinks.Observable.xproj b/src/Serilog.Sinks.Observable/Serilog.Sinks.Observable.xproj deleted file mode 100644 index 64b919017..000000000 --- a/src/Serilog.Sinks.Observable/Serilog.Sinks.Observable.xproj +++ /dev/null @@ -1,18 +0,0 @@ - - - - 14.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - 8d6c0bb9-d04d-49b6-9043-4a776ad275d5 - Serilog - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ - - - 2.0 - - - \ No newline at end of file diff --git a/src/Serilog.Sinks.Observable/Sinks/Observable/ObservableSink.cs b/src/Serilog.Sinks.Observable/Sinks/Observable/ObservableSink.cs deleted file mode 100644 index c5c874aa5..000000000 --- a/src/Serilog.Sinks.Observable/Sinks/Observable/ObservableSink.cs +++ /dev/null @@ -1,135 +0,0 @@ -// 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. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using Serilog.Core; -using Serilog.Events; - -namespace Serilog.Sinks.Observable -{ - sealed class ObservableSink : IObservable, ILogEventSink, IDisposable - { - // Uses memory barriers for non-blocking reads during Emit, and replaces the - // list of observers completely upon subscribe/unsubscribe. - // Makes the assumption that list iteration is not - // mutating - correct but not guaranteed by the BCL. - readonly object _syncRoot = new object(); - IList> _observers = new List>(); - bool _disposed; - - sealed class Unsubscriber : IDisposable - { - readonly ObservableSink _sink; - readonly IObserver _observer; - - public Unsubscriber(ObservableSink sink, IObserver observer) - { - if (sink == null) throw new ArgumentNullException(nameof(sink)); - if (observer == null) throw new ArgumentNullException(nameof(observer)); - _sink = sink; - _observer = observer; - } - - public void Dispose() - { - _sink.Unsubscribe(_observer); - } - } - - public IDisposable Subscribe(IObserver observer) - { - if (observer == null) throw new ArgumentNullException(nameof(observer)); - - lock (_syncRoot) - { - if (_disposed) - throw new ObjectDisposedException(message: "The Serilog Observable sink is disposed.", innerException: null); - - var old = _observers; - var newObservers = _observers.Concat(new [] { observer}).ToList(); - while (old != Interlocked.Exchange(ref _observers, newObservers)) - { - old = _observers; - newObservers = _observers.Concat(new[] { observer }).ToList(); - } - } - - return new Unsubscriber(this, observer); - } - - void Unsubscribe(IObserver observer) - { - if (observer == null) throw new ArgumentNullException(nameof(observer)); - - lock (_syncRoot) - { - if (_disposed) - throw new ObjectDisposedException(message: "The Serilog Observable sink is disposed.", innerException: null); - - var old = _observers; - var newObservers = _observers.Except(new[] { observer }).ToList(); - while (old != Interlocked.Exchange(ref _observers, newObservers)) - { - old = _observers; - newObservers = _observers.Except(new[] { observer }).ToList(); - } - } - } - - public void Emit(LogEvent logEvent) - { - if (logEvent == null) throw new ArgumentNullException(nameof(logEvent)); - - Interlocked.MemoryBarrier(); - - IList exceptions = null; - - // Mutations are made by replacing _observers wholesale. - // ReSharper disable once InconsistentlySynchronizedField - foreach (var observer in _observers) - { - try - { - observer.OnNext(logEvent); - } - catch (Exception ex) - { - if (exceptions == null) - exceptions = new List(); - exceptions.Add(ex); - } - } - - if (exceptions != null) - throw new AggregateException("At least one observer failed to accept the event", exceptions); - } - - public void Dispose() - { - lock (_syncRoot) - { - if (_disposed) return; - - _disposed = true; - foreach (var observer in _observers) - { - observer.OnCompleted(); - } - } - } - } -} diff --git a/src/Serilog.Sinks.Observable/project.json b/src/Serilog.Sinks.Observable/project.json deleted file mode 100644 index 026274f77..000000000 --- a/src/Serilog.Sinks.Observable/project.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "version": "2.0.0-beta-*", - "description": "The observable sink for Serilog.", - "authors": [ "Serilog Contributors" ], - "tags": [ "serilog", "observable", "reactive" ], - "projectUrl": "http://serilog.net", - "licenseUrl": "http://www.apache.org/licenses/LICENSE-2.0", - "iconUrl": "http://serilog.net/images/serilog-sink-nuget.png", - "dependencies": { - "Serilog": { "target": "project" } - }, - "compilationOptions": { - "keyFile": "../../assets/Serilog.snk" - }, - "frameworks": { - "net45": { - }, - "dotnet5.2": { - "dependencies": { - "System.Collections.Concurrent": "4.0.11-beta-23516" - } - } - } -} \ No newline at end of file diff --git a/src/Serilog.Sinks.PeriodicBatching/Properties/AssemblyInfo.cs b/src/Serilog.Sinks.PeriodicBatching/Properties/AssemblyInfo.cs deleted file mode 100644 index 1237c0e24..000000000 --- a/src/Serilog.Sinks.PeriodicBatching/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Reflection; -using System.Runtime.CompilerServices; - -[assembly: AssemblyVersion("2.0.0.0")] - -[assembly: CLSCompliant(true)] - -[assembly: InternalsVisibleTo("Serilog.Tests, PublicKey=" + - "0024000004800000940000000602000000240000525341310004000001000100fb8d13fd344a1c" + - "6fe0fe83ef33c1080bf30690765bc6eb0df26ebfdf8f21670c64265b30db09f73a0dea5b3db4c9" + - "d18dbf6d5a25af5ce9016f281014d79dc3b4201ac646c451830fc7e61a2dfd633d34c39f87b818" + - "94191652df5ac63cc40c77f3542f702bda692e6e8a9158353df189007a49da0f3cfd55eb250066" + - "b19485ec")] diff --git a/src/Serilog.Sinks.PeriodicBatching/Serilog.Sinks.PeriodicBatching.xproj b/src/Serilog.Sinks.PeriodicBatching/Serilog.Sinks.PeriodicBatching.xproj deleted file mode 100644 index 0bd6dfd90..000000000 --- a/src/Serilog.Sinks.PeriodicBatching/Serilog.Sinks.PeriodicBatching.xproj +++ /dev/null @@ -1,18 +0,0 @@ - - - - 14.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - 324c2f52-d9f7-4844-9bc4-9906e228d380 - Serilog - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ - - - 2.0 - - - \ No newline at end of file diff --git a/src/Serilog.Sinks.PeriodicBatching/Sinks/PeriodicBatching/BatchedConnectionStatus.cs b/src/Serilog.Sinks.PeriodicBatching/Sinks/PeriodicBatching/BatchedConnectionStatus.cs deleted file mode 100644 index d0a73792d..000000000 --- a/src/Serilog.Sinks.PeriodicBatching/Sinks/PeriodicBatching/BatchedConnectionStatus.cs +++ /dev/null @@ -1,95 +0,0 @@ -// 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. - -using System; - -namespace Serilog.Sinks.PeriodicBatching -{ - /// - /// Manages reconnection period and transient fault response for . - /// During normal operation an object of this type will simply echo the configured batch transmission - /// period. When availabilty fluctuates, the class tracks the number of failed attempts, each time - /// increasing the interval before reconnection is attempted (up to a set maximum) and at predefined - /// points indicating that either the current batch, or entire waiting queue, should be dropped. This - /// Serves two purposes - first, a loaded receiver may need a temporary reduction in traffic while coming - /// back online. Second, the sender needs to account for both bad batches (the first fault response) and - /// also overproduction (the second, queue-dropping response). In combination these should provide a - /// reasonable delivery effort but ultimately protect the sender from memory exhaustion. - /// - /// - /// Currently used only by , but may - /// provide the basis for a "smart" exponential backoff timer. There are other factors to consider - /// including the desire to send batches "when full" rather than continuing to buffer, and so-on. - /// - class BatchedConnectionStatus - { - static readonly TimeSpan MinimumBackoffPeriod = TimeSpan.FromSeconds(5); - static readonly TimeSpan MaximumBackoffInterval = TimeSpan.FromMinutes(10); - - const int FailuresBeforeDroppingBatch = 4; - const int FailuresBeforeDroppingQueue = 6; - - readonly TimeSpan _period; - - int _failuresSinceSuccessfulBatch; - - public BatchedConnectionStatus(TimeSpan period) - { - if (period < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(period), "The batching period must be a positive timespan"); - - _period = period; - } - - public void MarkSuccess() - { - _failuresSinceSuccessfulBatch = 0; - } - - public void MarkFailure() - { - ++_failuresSinceSuccessfulBatch; - } - - public TimeSpan NextInterval - { - get - { - // Available, and first failure, just try the batch interval - if (_failuresSinceSuccessfulBatch <= 1) return _period; - - // Second failure, start ramping up the interval - first 2x, then 4x, ... - var backoffFactor = Math.Pow(2, (_failuresSinceSuccessfulBatch - 1)); - - // If the period is ridiculously short, give it a boost so we get some - // visible backoff. - var backoffPeriod = Math.Max(_period.Ticks, MinimumBackoffPeriod.Ticks); - - // The "ideal" interval - var backedOff = (long) (backoffPeriod * backoffFactor); - - // Capped to the maximum interval - var cappedBackoff = Math.Min(MaximumBackoffInterval.Ticks, backedOff); - - // Unless that's shorter than the period, in which case we'll just apply the period - var actual = Math.Max(_period.Ticks, cappedBackoff); - - return TimeSpan.FromTicks(actual); - } - } - - public bool ShouldDropBatch => _failuresSinceSuccessfulBatch >= FailuresBeforeDroppingBatch; - - public bool ShouldDropQueue => _failuresSinceSuccessfulBatch >= FailuresBeforeDroppingQueue; - } -} diff --git a/src/Serilog.Sinks.PeriodicBatching/Sinks/PeriodicBatching/PeriodicBatchingSink.cs b/src/Serilog.Sinks.PeriodicBatching/Sinks/PeriodicBatching/PeriodicBatchingSink.cs deleted file mode 100644 index ae6975031..000000000 --- a/src/Serilog.Sinks.PeriodicBatching/Sinks/PeriodicBatching/PeriodicBatchingSink.cs +++ /dev/null @@ -1,289 +0,0 @@ -// 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. - - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Threading.Tasks; -using Serilog.Core; -using Serilog.Debugging; -using Serilog.Events; -using System.Threading; - -namespace Serilog.Sinks.PeriodicBatching -{ - /// - /// Base class for sinks that log events in batches. Batching is - /// triggered asynchronously on a timer. - /// - /// - /// To avoid unbounded memory growth, events are discarded after attempting - /// to send a batch, regardless of whether the batch succeeded or not. Implementers - /// that want to change this behavior need to either implement from scratch, or - /// embed retry logic in the batch emitting functions. - /// - public abstract class PeriodicBatchingSink : ILogEventSink, IDisposable - { - readonly int _batchSizeLimit; - readonly ConcurrentQueue _queue; - readonly BatchedConnectionStatus _status; - readonly Queue _waitingBatch = new Queue(); - - readonly object _stateLock = new object(); -#if WAITABLE_TIMER - readonly Timer _timer; -#else - readonly PortableTimer _timer; -#endif - bool _unloading; - bool _started; - - /// - /// Construct a sink posting to the specified database. - /// - /// The maximum number of events to include in a single batch. - /// The time to wait between checking for event batches. - protected PeriodicBatchingSink(int batchSizeLimit, TimeSpan period) - { - _batchSizeLimit = batchSizeLimit; - _queue = new ConcurrentQueue(); - _status = new BatchedConnectionStatus(period); - -#if WAITABLE_TIMER - _timer = new Timer(s => OnTick(), null, -1, -1); -#else - _timer = new PortableTimer(cancel => OnTick()); -#endif - -#if APPDOMAIN - AppDomain.CurrentDomain.DomainUnload += OnAppDomainUnloading; - AppDomain.CurrentDomain.ProcessExit += OnAppDomainUnloading; - AppDomain.CurrentDomain.UnhandledException += OnAppDomainUnloading; -#endif - } - -#if APPDOMAIN - void OnAppDomainUnloading(object sender, EventArgs args) - { - var eventArgs = args as UnhandledExceptionEventArgs; - if (eventArgs != null && !eventArgs.IsTerminating) - return; - - CloseAndFlush(); - } -#endif - - void CloseAndFlush() - { - lock (_stateLock) - { - if (!_started || _unloading) - return; - - _unloading = true; - } - -#if APPDOMAIN - AppDomain.CurrentDomain.DomainUnload -= OnAppDomainUnloading; - AppDomain.CurrentDomain.ProcessExit -= OnAppDomainUnloading; - AppDomain.CurrentDomain.UnhandledException -= OnAppDomainUnloading; -#endif - -#if WAITABLE_TIMER - var wh = new ManualResetEvent(false); - if (_timer.Dispose(wh)) - wh.WaitOne(); -#else - _timer.Dispose(); -#endif - - OnTick(); - } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - /// 2 - public void Dispose() - { - Dispose(true); - } - - /// - /// Free resources held by the sink. - /// - /// If true, called because the object is being disposed; if false, - /// the object is being disposed from the finalizer. - protected virtual void Dispose(bool disposing) - { - if (!disposing) return; - CloseAndFlush(); - } - - /// - /// Emit a batch of log events, running to completion synchronously. - /// - /// The events to emit. - /// Override either or , - /// not both. - protected virtual void EmitBatch(IEnumerable events) - { - var prevContext = SynchronizationContext.Current; - SynchronizationContext.SetSynchronizationContext(null); - try - { - // Wait so that the timer thread stays busy and thus - // we know we're working when flushing. - EmitBatchAsync(events).Wait(); - } - finally - { - SynchronizationContext.SetSynchronizationContext(prevContext); - } - } - - /// - /// Emit a batch of log events, running asynchronously. - /// - /// The events to emit. - /// Override either or , - /// not both. Overriding EmitBatch() is preferred. -#pragma warning disable 1998 - protected virtual async Task EmitBatchAsync(IEnumerable events) -#pragma warning restore 1998 - { - } - - void OnTick() - { - try - { - bool batchWasFull; - do - { - LogEvent next; - while (_waitingBatch.Count < _batchSizeLimit && - _queue.TryDequeue(out next)) - { - if (CanInclude(next)) - _waitingBatch.Enqueue(next); - } - - if (_waitingBatch.Count == 0) - { - OnEmptyBatch(); - return; - } - - EmitBatch(_waitingBatch); - - batchWasFull = _waitingBatch.Count >= _batchSizeLimit; - _waitingBatch.Clear(); - _status.MarkSuccess(); - } - while (batchWasFull); // Otherwise, allow the period to elapse - } - catch (Exception ex) - { - SelfLog.WriteLine("Exception while emitting periodic batch from {0}: {1}", this, ex); - _status.MarkFailure(); - } - finally - { - if (_status.ShouldDropBatch) - _waitingBatch.Clear(); - - if (_status.ShouldDropQueue) - { - LogEvent evt; - while (_queue.TryDequeue(out evt)) { } - } - - lock (_stateLock) - { - if (!_unloading) - SetTimer(_status.NextInterval); - } - } - } - - void SetTimer(TimeSpan interval) - { -#if WAITABLE_TIMER - _timer.Change(interval, Timeout.InfiniteTimeSpan); -#else - _timer.Start(interval); -#endif - - } - - /// - /// Emit the provided log event to the sink. If the sink is being disposed or - /// the app domain unloaded, then the event is ignored. - /// - /// Log event to emit. - /// The event is null. - /// - /// The sink implements the contract that any events whose Emit() method has - /// completed at the time of sink disposal will be flushed (or attempted to, - /// depending on app domain state). - /// - public void Emit(LogEvent logEvent) - { - if (logEvent == null) throw new ArgumentNullException(nameof(logEvent)); - - if (_unloading) - return; - - if (!_started) - { - lock (_stateLock) - { - if (_unloading) return; - if (!_started) - { - // Special handling to try to get the first event across as quickly - // as possible to show we're alive! - _queue.Enqueue(logEvent); - _started = true; - SetTimer(TimeSpan.Zero); - return; - } - } - } - - _queue.Enqueue(logEvent); - } - - /// - /// Determine whether a queued log event should be included in the batch. If - /// an override returns false, the event will be dropped. - /// - /// - /// - protected virtual bool CanInclude(LogEvent evt) - { - return true; - } - - /// - /// Allows derived sinks to perform periodic work without requiring additional threads - /// or timers (thus avoiding additional flush/shut-down complexity). - /// - protected virtual void OnEmptyBatch() - { - } - } -} diff --git a/src/Serilog.Sinks.PeriodicBatching/Sinks/PeriodicBatching/PortableTimer.cs b/src/Serilog.Sinks.PeriodicBatching/Sinks/PeriodicBatching/PortableTimer.cs deleted file mode 100644 index f381fbf36..000000000 --- a/src/Serilog.Sinks.PeriodicBatching/Sinks/PeriodicBatching/PortableTimer.cs +++ /dev/null @@ -1,110 +0,0 @@ -// 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 !WAITABLE_TIMER - -using Serilog.Debugging; -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace Serilog.Sinks.PeriodicBatching -{ - class PortableTimer : IDisposable - { - enum PortableTimerState - { - NotWaiting, - Waiting, - Active, - Disposed - } - - readonly object _stateLock = new object(); - PortableTimerState _state = PortableTimerState.NotWaiting; - - readonly Action _onTick; - readonly CancellationTokenSource _cancel = new CancellationTokenSource(); - - public PortableTimer(Action onTick) - { - if (onTick == null) throw new ArgumentNullException(nameof(onTick)); - _onTick = onTick; - } - - public async void Start(TimeSpan interval) - { - if (interval < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(interval)); - - lock (_stateLock) - { - if (_state == PortableTimerState.Disposed) - throw new ObjectDisposedException("PortableTimer"); - - // There's a little bit of raciness here, but it's needed to support the - // current API, which allows the tick handler to reenter and set the next interval. - - if (_state == PortableTimerState.Waiting) - throw new InvalidOperationException("The timer is already set."); - - if (_cancel.IsCancellationRequested) return; - - _state = PortableTimerState.Waiting; - } - - try - { - if (interval > TimeSpan.Zero) - await Task.Delay(interval, _cancel.Token).ConfigureAwait(false); - - _state = PortableTimerState.Active; - - if (!_cancel.Token.IsCancellationRequested) - { - _onTick(_cancel.Token); - } - } - catch (TaskCanceledException tcx) - { - SelfLog.WriteLine("The timer was canceled during invocation: {0}", tcx); - } - finally - { - lock (_stateLock) - _state = PortableTimerState.NotWaiting; - } - } - - public void Dispose() - { - _cancel.Cancel(); - - while (true) - { - lock (_stateLock) - { - if (_state == PortableTimerState.Disposed || - _state == PortableTimerState.NotWaiting) - { - _state = PortableTimerState.Disposed; - return; - } - } - - Thread.Sleep(10); - } - } - } -} -#endif diff --git a/src/Serilog.Sinks.PeriodicBatching/project.json b/src/Serilog.Sinks.PeriodicBatching/project.json deleted file mode 100644 index f748db1a5..000000000 --- a/src/Serilog.Sinks.PeriodicBatching/project.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "version": "2.0.0-beta-*", - "description": "The periodic batching sink for Serilog", - "authors": [ "Serilog Contributors" ], - "tags": [ "serilog", "batching", "timer" ], - "projectUrl": "http://serilog.net", - "licenseUrl": "http://www.apache.org/licenses/LICENSE-2.0", - "iconUrl": "http://serilog.net/images/serilog-sink-nuget.png", - "dependencies": { - "Serilog": { "target": "project" }, - }, - "compilationOptions": { - "keyFile": "../../assets/Serilog.snk" - }, - "frameworks": { - "net45": { - "compilationOptions": { - "define": [ "APPDOMAIN", "WAITABLE_TIMER" ] - } - }, - "dotnet5.2": { - "dependencies": { - "System.Collections.Concurrent": "4.0.11-beta-23516" - } - } - } -} diff --git a/src/Serilog.Sinks.RollingFile/Properties/AssemblyInfo.cs b/src/Serilog.Sinks.RollingFile/Properties/AssemblyInfo.cs deleted file mode 100644 index 1237c0e24..000000000 --- a/src/Serilog.Sinks.RollingFile/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Reflection; -using System.Runtime.CompilerServices; - -[assembly: AssemblyVersion("2.0.0.0")] - -[assembly: CLSCompliant(true)] - -[assembly: InternalsVisibleTo("Serilog.Tests, PublicKey=" + - "0024000004800000940000000602000000240000525341310004000001000100fb8d13fd344a1c" + - "6fe0fe83ef33c1080bf30690765bc6eb0df26ebfdf8f21670c64265b30db09f73a0dea5b3db4c9" + - "d18dbf6d5a25af5ce9016f281014d79dc3b4201ac646c451830fc7e61a2dfd633d34c39f87b818" + - "94191652df5ac63cc40c77f3542f702bda692e6e8a9158353df189007a49da0f3cfd55eb250066" + - "b19485ec")] diff --git a/src/Serilog.Sinks.RollingFile/RollingFileLoggerConfigurationExtensions.cs b/src/Serilog.Sinks.RollingFile/RollingFileLoggerConfigurationExtensions.cs deleted file mode 100644 index e8f264e40..000000000 --- a/src/Serilog.Sinks.RollingFile/RollingFileLoggerConfigurationExtensions.cs +++ /dev/null @@ -1,71 +0,0 @@ -// 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. - -using System; -using Serilog.Configuration; -using Serilog.Core; -using Serilog.Events; -using Serilog.Formatting.Display; - -namespace Serilog.Sinks.RollingFile -{ - public static class RollingFileLoggerConfigurationExtensions - { - const int DefaultRetainedFileCountLimit = 31; // A long month of logs - const long DefaultFileSizeLimitBytes = 1L * 1024 * 1024 * 1024; - const string DefaultOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"; - - /// - /// Write log events to a series of files. Each file will be named according to - /// the date of the first log entry written to it. Only simple date-based rolling is - /// currently supported. - /// - /// Logger sink configuration. - /// String describing the location of the log files, - /// with {Date} in the place of the file date. E.g. "Logs\myapp-{Date}.log" will result in log - /// files such as "Logs\myapp-2013-10-20.log", "Logs\myapp-2013-10-21.log" and so on. - /// The minimum level for - /// events passed through the sink. Ignored when is specified. - /// A switch allowing the pass-through minimum level - /// to be changed at runtime. - /// A message template describing the format used to write to the sink. - /// the default is "{Timestamp} [{Level}] {Message}{NewLine}{Exception}". - /// Supplies culture-specific formatting information, or null. - /// The maximum size, in bytes, to which any single log file will be allowed to grow. - /// For unrestricted growth, pass null. The default is 1 GB. - /// The maximum number of log files that will be retained, - /// including the current log file. For unlimited retention, pass null. The default is 31. - /// Indicates if flushing to the output file can be buffered or not. The default - /// is false. - /// Configuration object allowing method chaining. - /// The file will be written using the UTF-8 character set. - public static LoggerConfiguration RollingFile( - this LoggerSinkConfiguration sinkConfiguration, - string pathFormat, - LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, - string outputTemplate = DefaultOutputTemplate, - IFormatProvider formatProvider = null, - long? fileSizeLimitBytes = DefaultFileSizeLimitBytes, - int? retainedFileCountLimit = DefaultRetainedFileCountLimit, - LoggingLevelSwitch levelSwitch = null, - bool buffered = false) - { - if (sinkConfiguration == null) throw new ArgumentNullException(nameof(sinkConfiguration)); - if (outputTemplate == null) throw new ArgumentNullException(nameof(outputTemplate)); - var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider); - var sink = new RollingFileSink(pathFormat, formatter, fileSizeLimitBytes, retainedFileCountLimit, buffered: buffered); - return sinkConfiguration.Sink(sink, restrictedToMinimumLevel, levelSwitch); - } - } -} \ No newline at end of file diff --git a/src/Serilog.Sinks.RollingFile/Serilog.Sinks.RollingFile.xproj b/src/Serilog.Sinks.RollingFile/Serilog.Sinks.RollingFile.xproj deleted file mode 100644 index 530696272..000000000 --- a/src/Serilog.Sinks.RollingFile/Serilog.Sinks.RollingFile.xproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - 14.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - - a3e6e5b4-995f-4c3d-9673-a4b6000f4e21 - Serilog.Sinks.RollingFile - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ - - - - 2.0 - - - diff --git a/src/Serilog.Sinks.RollingFile/Sinks/RollingFile/Clock.cs b/src/Serilog.Sinks.RollingFile/Sinks/RollingFile/Clock.cs deleted file mode 100644 index 4815252ef..000000000 --- a/src/Serilog.Sinks.RollingFile/Sinks/RollingFile/Clock.cs +++ /dev/null @@ -1,38 +0,0 @@ -// 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. - -using System; - -namespace Serilog.Sinks.RollingFile -{ - static class Clock - { - static Func _dateTimeNow = () => DateTime.Now; - - [ThreadStatic] - static DateTime _testDateTimeNow; - - public static DateTime DateTimeNow => _dateTimeNow(); - - // Time is set per thread to support parallel - // If any thread uses the clock in test mode, all threads - // must use it in test mode; once set to test mode only - // terminating the application returns it to normal use. - public static void SetTestDateTimeNow(DateTime now) - { - _testDateTimeNow = now; - _dateTimeNow = () => _testDateTimeNow; - } - } -} \ No newline at end of file diff --git a/src/Serilog.Sinks.RollingFile/Sinks/RollingFile/RollingFileSink.cs b/src/Serilog.Sinks.RollingFile/Sinks/RollingFile/RollingFileSink.cs deleted file mode 100644 index 3e63e1089..000000000 --- a/src/Serilog.Sinks.RollingFile/Sinks/RollingFile/RollingFileSink.cs +++ /dev/null @@ -1,233 +0,0 @@ -// 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. - - -using System; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices; -using System.Text; -using Serilog.Core; -using Serilog.Debugging; -using Serilog.Events; -using Serilog.Formatting; -using Serilog.Sinks.File; - -namespace Serilog.Sinks.RollingFile -{ - /// - /// Write log events to a series of files. Each file will be named according to - /// the date of the first log entry written to it. Only simple date-based rolling is - /// currently supported. - /// - public sealed class RollingFileSink : ILogEventSink, IDisposable - { - readonly TemplatedPathRoller _roller; - readonly ITextFormatter _textFormatter; - readonly long? _fileSizeLimitBytes; - readonly int? _retainedFileCountLimit; - readonly Encoding _encoding; - readonly bool _buffered; - readonly object _syncRoot = new object(); - - bool _isDisposed; - DateTime? _nextCheckpoint; - FileSink _currentFile; - - /// Construct a . - /// String describing the location of the log files, - /// with {Date} in the place of the file date. E.g. "Logs\myapp-{Date}.log" will result in log - /// files such as "Logs\myapp-2013-10-20.log", "Logs\myapp-2013-10-21.log" and so on. - /// Formatter used to convert log events to text. - /// The maximum size, in bytes, to which a log file will be allowed to grow. - /// For unrestricted growth, pass null. The default is 1 GB. - /// The maximum number of log files that will be retained, - /// including the current log file. For unlimited retention, pass null. The default is 31. - /// Character encoding used to write the text file. The default is UTF-8. - /// Indicates if flushing to the output file can be buffered or not. The default - /// is false. - /// Configuration object allowing method chaining. - /// The file will be written using the UTF-8 character set. - public RollingFileSink(string pathFormat, - ITextFormatter textFormatter, - long? fileSizeLimitBytes, - int? retainedFileCountLimit, - Encoding encoding = null, - bool buffered = false) - { - if (pathFormat == null) throw new ArgumentNullException(nameof(pathFormat)); - if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 0) throw new ArgumentException("Negative value provided; file size limit must be non-negative"); - if (retainedFileCountLimit.HasValue && retainedFileCountLimit < 1) throw new ArgumentException("Zero or negative value provided; retained file count limit must be at least 1"); - - _roller = new TemplatedPathRoller(pathFormat); - _textFormatter = textFormatter; - _fileSizeLimitBytes = fileSizeLimitBytes; - _retainedFileCountLimit = retainedFileCountLimit; - _encoding = encoding ?? Encoding.UTF8; - _buffered = buffered; - } - - /// - /// Emit the provided log event to the sink. - /// - /// The log event to write. - /// Events that come in out-of-order (e.g. around the rollovers) - /// may end up written to a later file than their timestamp - /// would indicate. - public void Emit(LogEvent logEvent) - { - if (logEvent == null) throw new ArgumentNullException(nameof(logEvent)); - - lock (_syncRoot) - { - if (_isDisposed) throw new ObjectDisposedException("The rolling file has been disposed."); - - AlignCurrentFileTo(Clock.DateTimeNow); - - // If the file was unable to be opened on the last attempt, it will remain - // null until the next checkpoint passes, at which time another attempt will be made to - // open it. - if (_currentFile != null) - _currentFile.Emit(logEvent); - } - } - - void AlignCurrentFileTo(DateTime now) - { - if (!_nextCheckpoint.HasValue) - { - OpenFile(now); - } - else if (now >= _nextCheckpoint.Value) - { - CloseFile(); - OpenFile(now); - } - } - - void OpenFile(DateTime now) - { - var date = now.Date; - - // We only take one attempt at it because repeated failures - // to open log files REALLY slow an app down. - _nextCheckpoint = date.AddDays(1); - - var existingFiles = Enumerable.Empty(); - try - { - existingFiles = Directory.GetFiles(_roller.LogFileDirectory, _roller.DirectorySearchPattern) - .Select(Path.GetFileName); - } - catch (DirectoryNotFoundException) { } - - var latestForThisDate = _roller - .SelectMatches(existingFiles) - .Where(m => m.Date == date) - .OrderByDescending(m => m.SequenceNumber) - .FirstOrDefault(); - - var sequence = latestForThisDate != null ? latestForThisDate.SequenceNumber : 0; - - const int maxAttempts = 3; - for (var attempt = 0; attempt < maxAttempts; attempt++) - { - string path; - _roller.GetLogFilePath(now, sequence, out path); - - try - { - _currentFile = new FileSink(path, _textFormatter, _fileSizeLimitBytes, _encoding, _buffered); - } - catch (IOException ex) - { - var errorCode = Marshal.GetHRForException(ex) & ((1 << 16) - 1); - if (errorCode == 32 || errorCode == 33) - { - SelfLog.WriteLine("Rolling file target {0} was locked, attempting to open next in sequence (attempt {1})", path, attempt + 1); - sequence++; - continue; - } - - throw; - } - - ApplyRetentionPolicy(path); - return; - } - } - - void ApplyRetentionPolicy(string currentFilePath) - { - if (_retainedFileCountLimit == null) return; - - var currentFileName = Path.GetFileName(currentFilePath); - - // We consider the current file to exist, even if nothing's been written yet, - // because files are only opened on response to an event being processed. - var potentialMatches = Directory.GetFiles(_roller.LogFileDirectory, _roller.DirectorySearchPattern) - .Select(Path.GetFileName) - .Union(new [] { currentFileName }); - - var newestFirst = _roller - .SelectMatches(potentialMatches) - .OrderByDescending(m => m.Date) - .ThenByDescending(m => m.SequenceNumber) - .Select(m => m.Filename); - - var toRemove = newestFirst - .Where(n => StringComparer.OrdinalIgnoreCase.Compare(currentFileName, n) != 0) - .Skip(_retainedFileCountLimit.Value - 1) - .ToList(); - - foreach (var obsolete in toRemove) - { - var fullPath = Path.Combine(_roller.LogFileDirectory, obsolete); - try - { - System.IO.File.Delete(fullPath); - } - catch (Exception ex) - { - SelfLog.WriteLine("Error {0} while removing obsolete file {1}", ex, fullPath); - } - } - } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or - /// resetting unmanaged resources. - /// - public void Dispose() - { - lock (_syncRoot) - { - if (_currentFile == null) return; - CloseFile(); - _isDisposed = true; - } - } - - void CloseFile() - { - if (_currentFile != null) - { - _currentFile.Dispose(); - _currentFile = null; - } - - _nextCheckpoint = null; - } - } -} \ No newline at end of file diff --git a/src/Serilog.Sinks.RollingFile/Sinks/RollingFile/RollingLogFile.cs b/src/Serilog.Sinks.RollingFile/Sinks/RollingFile/RollingLogFile.cs deleted file mode 100644 index 20d1a6935..000000000 --- a/src/Serilog.Sinks.RollingFile/Sinks/RollingFile/RollingLogFile.cs +++ /dev/null @@ -1,34 +0,0 @@ -// 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. - -using System; - -namespace Serilog.Sinks.RollingFile -{ - class RollingLogFile - { - public RollingLogFile(string filename, DateTime date, int sequenceNumber) - { - Filename = filename; - Date = date; - SequenceNumber = sequenceNumber; - } - - public string Filename { get; } - - public DateTime Date { get; } - - public int SequenceNumber { get; } - } -} \ No newline at end of file diff --git a/src/Serilog.Sinks.RollingFile/Sinks/RollingFile/TemplatedPathRoller.cs b/src/Serilog.Sinks.RollingFile/Sinks/RollingFile/TemplatedPathRoller.cs deleted file mode 100644 index 274053ba7..000000000 --- a/src/Serilog.Sinks.RollingFile/Sinks/RollingFile/TemplatedPathRoller.cs +++ /dev/null @@ -1,126 +0,0 @@ -// 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. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Text.RegularExpressions; - -namespace Serilog.Sinks.RollingFile -{ - // Rolls files based on the current date, using a path - // formatting pattern like: - // Logs/log-{Date}.txt - // - class TemplatedPathRoller - { - const string OldStyleDateSpecifier = "{0}"; - const string DateSpecifier = "{Date}"; - const string DateFormat = "yyyyMMdd"; - const string DefaultSeparator = "-"; - - readonly string _pathTemplate; - readonly Regex _filenameMatcher; - - public TemplatedPathRoller(string pathTemplate) - { - if (pathTemplate == null) throw new ArgumentNullException(nameof(pathTemplate)); - if (pathTemplate.Contains(OldStyleDateSpecifier)) - throw new ArgumentException("The old-style date specifier " + OldStyleDateSpecifier + - " is no longer supported, instead please use " + DateSpecifier); - - var directory = Path.GetDirectoryName(pathTemplate); - if (string.IsNullOrEmpty(directory)) - { -#if !DOTNET5_4 - directory = Environment.CurrentDirectory; -#else - directory = Directory.GetCurrentDirectory(); -#endif - } - - directory = Path.GetFullPath(directory); - - if (directory.Contains(DateSpecifier)) - throw new ArgumentException("The date cannot form part of the directory name"); - - var filenameTemplate = Path.GetFileName(pathTemplate); - if (!filenameTemplate.Contains(DateSpecifier)) - { - filenameTemplate = Path.GetFileNameWithoutExtension(filenameTemplate) + DefaultSeparator + - DateSpecifier + Path.GetExtension(filenameTemplate); - } - - var indexOfSpecifier = filenameTemplate.IndexOf(DateSpecifier, StringComparison.Ordinal); - var prefix = filenameTemplate.Substring(0, indexOfSpecifier); - var suffix = filenameTemplate.Substring(indexOfSpecifier + DateSpecifier.Length); - _filenameMatcher = new Regex( - "^" + - Regex.Escape(prefix) + - "(?\\d{" + DateFormat.Length + "})" + - "(?_[0-9]{3,}){0,1}" + - Regex.Escape(suffix) + - "$"); - - DirectorySearchPattern = filenameTemplate.Replace(DateSpecifier, "*"); - LogFileDirectory = directory; - _pathTemplate = Path.Combine(LogFileDirectory, filenameTemplate); - } - - public string LogFileDirectory { get; } - - public string DirectorySearchPattern { get; } - - public void GetLogFilePath(DateTime date, int sequenceNumber, out string path) - { - var tok = date.ToString(DateFormat, CultureInfo.InvariantCulture); - - if (sequenceNumber != 0) - tok += "_" + sequenceNumber.ToString("000", CultureInfo.InvariantCulture); - - path = _pathTemplate.Replace(DateSpecifier, tok); - } - - public IEnumerable SelectMatches(IEnumerable filenames) - { - foreach (var filename in filenames) - { - var match = _filenameMatcher.Match(filename); - if (match.Success) - { - var inc = 0; - var incGroup = match.Groups["inc"]; - if (incGroup.Captures.Count != 0) - { - var incPart = incGroup.Captures[0].Value.Substring(1); - inc = int.Parse(incPart, CultureInfo.InvariantCulture); - } - - DateTime date; - var datePart = match.Groups["date"].Captures[0].Value; - if (!DateTime.TryParseExact( - datePart, - DateFormat, - CultureInfo.InvariantCulture, - DateTimeStyles.None, - out date)) - continue; - - yield return new RollingLogFile(filename, date, inc); - } - } - } - } -} \ No newline at end of file diff --git a/src/Serilog.Sinks.RollingFile/project.json b/src/Serilog.Sinks.RollingFile/project.json deleted file mode 100644 index ff696164a..000000000 --- a/src/Serilog.Sinks.RollingFile/project.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "version": "2.0.0-beta-*", - "description": "The rolling file sink for Serilog - Simple .NET logging with fully-structured events", - "authors": [ "Serilog Contributors" ], - "tags": [ "serilog", "file", "io", "rolling" ], - "projectUrl": "http://serilog.net", - "licenseUrl": "http://www.apache.org/licenses/LICENSE-2.0", - "iconUrl": "http://serilog.net/images/serilog-sink-nuget.png", - "dependencies": { - "Serilog": { "target": "project" }, - "Serilog.Sinks.File": { "target": "project" } - }, - "compilationOptions": { - "keyFile": "../../assets/Serilog.snk" - }, - "frameworks": { - "net45": { - }, - "dotnet5.4": { - "dependencies": { - "System.IO": "4.0.11-beta-23516", - "System.IO.FileSystem.Primitives": "4.0.1-beta-23516" - } - } - } -} \ No newline at end of file diff --git a/src/Serilog.Sinks.TextWriter/Properties/AssemblyInfo.cs b/src/Serilog.Sinks.TextWriter/Properties/AssemblyInfo.cs deleted file mode 100644 index 1237c0e24..000000000 --- a/src/Serilog.Sinks.TextWriter/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Reflection; -using System.Runtime.CompilerServices; - -[assembly: AssemblyVersion("2.0.0.0")] - -[assembly: CLSCompliant(true)] - -[assembly: InternalsVisibleTo("Serilog.Tests, PublicKey=" + - "0024000004800000940000000602000000240000525341310004000001000100fb8d13fd344a1c" + - "6fe0fe83ef33c1080bf30690765bc6eb0df26ebfdf8f21670c64265b30db09f73a0dea5b3db4c9" + - "d18dbf6d5a25af5ce9016f281014d79dc3b4201ac646c451830fc7e61a2dfd633d34c39f87b818" + - "94191652df5ac63cc40c77f3542f702bda692e6e8a9158353df189007a49da0f3cfd55eb250066" + - "b19485ec")] diff --git a/src/Serilog.Sinks.TextWriter/Serilog.Sinks.TextWriter.xproj b/src/Serilog.Sinks.TextWriter/Serilog.Sinks.TextWriter.xproj deleted file mode 100644 index 26ffe2039..000000000 --- a/src/Serilog.Sinks.TextWriter/Serilog.Sinks.TextWriter.xproj +++ /dev/null @@ -1,18 +0,0 @@ - - - - 14.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - e85abec7-9b4c-432c-9a04-ac5be9205d9f - Serilog - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ - - - 2.0 - - - \ No newline at end of file diff --git a/src/Serilog.Sinks.TextWriter/Sinks/TextWriter/TextWriterSink.cs b/src/Serilog.Sinks.TextWriter/Sinks/TextWriter/TextWriterSink.cs deleted file mode 100644 index 8d35fe1b4..000000000 --- a/src/Serilog.Sinks.TextWriter/Sinks/TextWriter/TextWriterSink.cs +++ /dev/null @@ -1,46 +0,0 @@ -// 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. - -using System; -using System.IO; -using Serilog.Core; -using Serilog.Events; -using Serilog.Formatting; - -namespace Serilog.Sinks.TextWriter -{ - class TextWriterSink : ILogEventSink - { - readonly System.IO.TextWriter _textWriter; - readonly ITextFormatter _textFormatter; - readonly object _syncRoot = new object(); - - public TextWriterSink(System.IO.TextWriter textWriter, ITextFormatter textFormatter) - { - if (textFormatter == null) throw new ArgumentNullException(nameof(textFormatter)); - _textWriter = textWriter; - _textFormatter = textFormatter; - } - - public void Emit(LogEvent logEvent) - { - if (logEvent == null) throw new ArgumentNullException(nameof(logEvent)); - lock (_syncRoot) - { - _textFormatter.Format(logEvent, _textWriter); - _textWriter.Flush(); - } - } - } -} diff --git a/src/Serilog.Sinks.TextWriter/TextWriterLoggerConfigurationExtensions.cs b/src/Serilog.Sinks.TextWriter/TextWriterLoggerConfigurationExtensions.cs deleted file mode 100644 index 3b0e828b3..000000000 --- a/src/Serilog.Sinks.TextWriter/TextWriterLoggerConfigurationExtensions.cs +++ /dev/null @@ -1,58 +0,0 @@ -// 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. - -using System; -using System.IO; -using Serilog.Configuration; -using Serilog.Core; -using Serilog.Events; -using Serilog.Formatting.Display; -using Serilog.Sinks.TextWriter; - -namespace Serilog -{ - public static class TextWriterLoggerConfigurationExtensions - { - const string DefaultOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"; - - /// - /// Write log events to the provided . - /// - /// Logger sink configuration. - /// The text writer to write log events to. - /// Message template describing the output format. - /// The minimum level for - /// events passed through the sink. Ignored when is specified. - /// A switch allowing the pass-through minimum level - /// to be changed at runtime. - /// Configuration object allowing method chaining. - /// Supplies culture-specific formatting information, or null. - /// - public static LoggerConfiguration TextWriter( - this LoggerSinkConfiguration sinkConfiguration, - TextWriter textWriter, - LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, - string outputTemplate = DefaultOutputTemplate, - IFormatProvider formatProvider = null, - LoggingLevelSwitch levelSwitch = null) - { - if (textWriter == null) throw new ArgumentNullException(nameof(textWriter)); - if (outputTemplate == null) throw new ArgumentNullException(nameof(outputTemplate)); - - var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider); - var sink = new TextWriterSink(textWriter, formatter); - return sinkConfiguration.Sink(sink, restrictedToMinimumLevel, levelSwitch); - } - } -} \ No newline at end of file diff --git a/src/Serilog.Sinks.TextWriter/project.json b/src/Serilog.Sinks.TextWriter/project.json deleted file mode 100644 index 6b1aff11c..000000000 --- a/src/Serilog.Sinks.TextWriter/project.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "version": "2.0.0-beta-*", - "description": "The System.IO.TextWriter sink for Serilog", - "authors": [ "Serilog Contributors" ], - "tags": [ "serilog", "IO", "text", "writer" ], - "projectUrl": "http://serilog.net", - "licenseUrl": "http://www.apache.org/licenses/LICENSE-2.0", - "iconUrl": "http://serilog.net/images/serilog-sink-nuget.png", - "dependencies": { - "Serilog": { "target": "project" } - }, - "compilationOptions": { - "keyFile": "../../assets/Serilog.snk" - }, - "frameworks": { - "net45": { - }, - "dotnet5.1": { - "dependencies": { - "System.IO": "4.0.11-beta-23516" - } - } - } -} \ No newline at end of file diff --git a/test/Serilog.Tests/Sinks/IOFile/FileSinkTests.cs b/test/Serilog.Tests/Sinks/IOFile/FileSinkTests.cs deleted file mode 100644 index df4d49eb1..000000000 --- a/test/Serilog.Tests/Sinks/IOFile/FileSinkTests.cs +++ /dev/null @@ -1,91 +0,0 @@ -#if FILE_IO - -using System; -using System.IO; -using System.Linq; -using Xunit; -using Serilog.Events; -using Serilog.Tests.Support; - -namespace Serilog.Tests.Sinks.IOFile -{ - public class FileSinkTests - { - [Fact] - public void FileIsWrittenIfNonexistent() - { - var path = Some.NonexistentTempFilePath(); - TestLoggingAndDelete(path); - } - - [Fact] - public void FileIsAppendedToWhenAlreadyCreated() - { - var path = Some.TempFilePath(); - TestLoggingAndDelete(path); - } - - [Fact] - public void WhenLimitIsSpecifiedFileSizeIsRestricted() - { - const int maxBytes = 100; - var path = Some.NonexistentTempFilePath(); - ExecuteAndCleanUpFile( - path, - p => new LoggerConfiguration() - .WriteTo.File(p, fileSizeLimitBytes: maxBytes) - .CreateLogger(), - log => - { - log.Information(new string('n', maxBytes + 1)); - var size = new FileInfo(path).Length; - Assert.True(size > 0); - Assert.True(size < maxBytes); - }); - } - - static void TestLoggingAndDelete(string path) - { - ExecuteAndCleanUpFile( - path, - p => new LoggerConfiguration() - .WriteTo.File(p) - .CreateLogger(), - log => - { - var message = Some.MessageTemplate(); - - log.Write(new LogEvent( - DateTimeOffset.Now, - LogEventLevel.Information, - null, - message, - Enumerable.Empty())); - - var refile = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - var content = new StreamReader(refile).ReadToEnd(); - refile.Dispose(); - - Assert.True(content.Contains(message.Text)); - }); - } - - static void ExecuteAndCleanUpFile(string path, Func configure, Action test) - { - ILogger log = null; - - try - { - log = configure(path); - test(log); - } - finally - { - var disposable = (IDisposable) log; - if (disposable != null) disposable.Dispose(); - File.Delete(path); - } - } - } -} -#endif diff --git a/test/Serilog.Tests/Sinks/Observable/ObservableSinkTests.cs b/test/Serilog.Tests/Sinks/Observable/ObservableSinkTests.cs deleted file mode 100644 index 3ad137905..000000000 --- a/test/Serilog.Tests/Sinks/Observable/ObservableSinkTests.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.Reactive.Linq; -using Xunit; -using Serilog.Tests.Support; - -namespace Serilog.Tests.Sinks.Observable -{ - public class ObservableSinkTests - { - [Fact] - public void EventsAreWrittenToObservers() - { - var eventSeen = false; - - var log = new LoggerConfiguration() - .WriteTo.Observers(events => events - .Do(evt => { eventSeen = true; }) - .Subscribe()) - .CreateLogger(); - - log.Write(Some.InformationEvent()); - Assert.True(eventSeen); - } - } -} diff --git a/test/Serilog.Tests/Sinks/PeriodicBatching/BatchedConnectionStatusTests.cs b/test/Serilog.Tests/Sinks/PeriodicBatching/BatchedConnectionStatusTests.cs deleted file mode 100644 index 9bc8307ad..000000000 --- a/test/Serilog.Tests/Sinks/PeriodicBatching/BatchedConnectionStatusTests.cs +++ /dev/null @@ -1,80 +0,0 @@ -#if PERIODIC_BATCHING && INTERNAL_TESTS -using System; -using Xunit; -using Serilog.Sinks.PeriodicBatching; - -namespace Serilog.Tests.Sinks.PeriodicBatching -{ - public class BatchedConnectionStatusTests - { - readonly TimeSpan DefaultPeriod = TimeSpan.FromSeconds(2); - - [Fact] - public void WhenNoFailuresHaveOccurredTheRegularIntervalIsUsed() - { - var bcs = new BatchedConnectionStatus(DefaultPeriod); - Assert.Equal(DefaultPeriod, bcs.NextInterval); - } - - [Fact] - public void WhenOneFailureHasOccurredTheRegularIntervalIsUsed() - { - var bcs = new BatchedConnectionStatus(DefaultPeriod); - bcs.MarkFailure(); - Assert.Equal(DefaultPeriod, bcs.NextInterval); - } - - [Fact] - public void WhenTwoFailuresHaveOccurredTheIntervalBacksOff() - { - var bcs = new BatchedConnectionStatus(DefaultPeriod); - bcs.MarkFailure(); - bcs.MarkFailure(); - Assert.Equal(TimeSpan.FromSeconds(10), bcs.NextInterval); - } - - [Fact] - public void WhenABatchSucceedsTheStatusResets() - { - var bcs = new BatchedConnectionStatus(DefaultPeriod); - bcs.MarkFailure(); - bcs.MarkFailure(); - bcs.MarkSuccess(); - Assert.Equal(DefaultPeriod, bcs.NextInterval); - } - - [Fact] - public void WhenThreeFailuresHaveOccurredTheIntervalBacksOff() - { - var bcs = new BatchedConnectionStatus(DefaultPeriod); - bcs.MarkFailure(); - bcs.MarkFailure(); - bcs.MarkFailure(); - Assert.Equal(TimeSpan.FromSeconds(20), bcs.NextInterval); - Assert.False(bcs.ShouldDropBatch); - } - - [Fact] - public void WhenFourFailuresHaveOccurredTheIntervalBacksOffAndBatchIsDropped() - { - var bcs = new BatchedConnectionStatus(DefaultPeriod); - bcs.MarkFailure(); - bcs.MarkFailure(); - bcs.MarkFailure(); - bcs.MarkFailure(); - Assert.Equal(TimeSpan.FromSeconds(40), bcs.NextInterval); - Assert.True(bcs.ShouldDropBatch); - Assert.False(bcs.ShouldDropQueue); - } - - [Fact] - public void WhenSixFailuresHaveOccurredTheQueueIsDropped() - { - var bcs = new BatchedConnectionStatus(DefaultPeriod); - for (var i = 0; i < 6; ++i ) - bcs.MarkFailure(); - Assert.True(bcs.ShouldDropQueue); - } - } -} -#endif diff --git a/test/Serilog.Tests/Sinks/PeriodicBatching/PeriodicBatchingSinkTests.cs b/test/Serilog.Tests/Sinks/PeriodicBatching/PeriodicBatchingSinkTests.cs deleted file mode 100644 index 1fbb6bc64..000000000 --- a/test/Serilog.Tests/Sinks/PeriodicBatching/PeriodicBatchingSinkTests.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Xunit; -using Serilog.Events; -using Serilog.Sinks.PeriodicBatching; -using Serilog.Tests.Support; - -namespace Serilog.Tests.Sinks.PeriodicBatching -{ - class InMemoryPeriodicBatchingSink : PeriodicBatchingSink - { - readonly TimeSpan _batchEmitDelay; - readonly object _stateLock = new object(); - bool _isDisposed; - bool _stopped; - - // Post-mortem only - public bool WasCalledAfterDisposal { get; private set; } - public IList> Batches { get; } - - public InMemoryPeriodicBatchingSink(int batchSizeLimit, TimeSpan period, TimeSpan batchEmitDelay) - : base(batchSizeLimit, period) - { - _batchEmitDelay = batchEmitDelay; - Batches = new List>(); - } - - public void Stop() - { - lock (_stateLock) - { - _stopped = true; - } - } - - protected override void EmitBatch(IEnumerable events) - { - lock (_stateLock) - { - if (_stopped) - return; - - if (_isDisposed) - WasCalledAfterDisposal = true; - - Thread.Sleep(_batchEmitDelay); - Batches.Add(events.ToList()); - } - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - _isDisposed = true; - } - } - - public class PeriodicBatchingSinkTests - { - static readonly TimeSpan TinyWait = TimeSpan.FromMilliseconds(200); - static readonly TimeSpan MicroWait = TimeSpan.FromMilliseconds(1); - - // Some very, very approximate tests here :) - - [Fact] - public void WhenAnEventIsEnqueuedItIsWrittenToABatch_OnFlush() - { - var pbs = new InMemoryPeriodicBatchingSink(2, TinyWait, TimeSpan.Zero); - var evt = Some.InformationEvent(); - pbs.Emit(evt); - pbs.Dispose(); - Assert.Equal(1, pbs.Batches.Count); - Assert.Equal(1, pbs.Batches[0].Count); - Assert.Same(evt, pbs.Batches[0][0]); - Assert.False(pbs.WasCalledAfterDisposal); - } - - [Fact] - public void WhenAnEventIsEnqueuedItIsWrittenToABatch_OnTimer() - { - var pbs = new InMemoryPeriodicBatchingSink(2, TinyWait, TimeSpan.Zero); - var evt = Some.InformationEvent(); - pbs.Emit(evt); - Thread.Sleep(TinyWait + TinyWait); - pbs.Stop(); - Assert.Equal(1, pbs.Batches.Count); - Assert.False(pbs.WasCalledAfterDisposal); - } - - [Fact] - public void WhenAnEventIsEnqueuedItIsWrittenToABatch_FlushWhileRunning() - { - var pbs = new InMemoryPeriodicBatchingSink(2, MicroWait, TinyWait + TinyWait); - var evt = Some.InformationEvent(); - pbs.Emit(evt); - Thread.Sleep(TinyWait); - pbs.Dispose(); - Assert.Equal(1, pbs.Batches.Count); - Assert.False(pbs.WasCalledAfterDisposal); - } - } -} diff --git a/test/Serilog.Tests/Sinks/RollingFile/RollingFileSinkTests.cs b/test/Serilog.Tests/Sinks/RollingFile/RollingFileSinkTests.cs deleted file mode 100644 index 38f054c14..000000000 --- a/test/Serilog.Tests/Sinks/RollingFile/RollingFileSinkTests.cs +++ /dev/null @@ -1,116 +0,0 @@ -#if FILE_IO && INTERNAL_TESTS - -using System; -using System.Collections.Generic; -using System.IO; -using Xunit; -using Serilog.Events; -using Serilog.Sinks.RollingFile; -using Serilog.Tests.Support; - -namespace Serilog.Tests.Sinks.RollingFile -{ - public class RollingFileSinkTests - { - [Fact] - public void LogEventsAreEmittedToTheFileNamedAccordingToTheEventTimestamp() - { - TestRollingEventSequence(Some.InformationEvent()); - } - - [Fact] - public void WhenTheDateChangesTheCorrectFileIsWritten() - { - var e1 = Some.InformationEvent(); - var e2 = Some.InformationEvent(e1.Timestamp.AddDays(1)); - TestRollingEventSequence(e1, e2); - } - - [Fact] - public void WhenRetentionCountIsSetOldFilesAreDeleted() - { - LogEvent e1 = Some.InformationEvent(), - e2 = Some.InformationEvent(e1.Timestamp.AddDays(1)), - e3 = Some.InformationEvent(e2.Timestamp.AddDays(5)); - - TestRollingEventSequence(new[] { e1, e2, e3 }, 2, - files => - { - Assert.Equal(3, files.Count); - Assert.True(!File.Exists(files[0])); - Assert.True(File.Exists(files[1])); - Assert.True(File.Exists(files[2])); - }); - } - - [Fact] - public void IfTheLogFolderDoesNotExistItWillBeCreated() - { - var fileName = Some.String() + "-{Date}.txt"; - var temp = Some.TempFolderPath(); - var folder = Path.Combine(temp, Guid.NewGuid().ToString()); - var pathFormat = Path.Combine(folder, fileName); - - ILogger log = null; - - try - { - log = new LoggerConfiguration() - .WriteTo.RollingFile(pathFormat, retainedFileCountLimit: 3) - .CreateLogger(); - - log.Write(Some.InformationEvent()); - - Assert.True(Directory.Exists(folder)); - } - finally - { - var disposable = (IDisposable)log; - if (disposable != null) disposable.Dispose(); - Directory.Delete(temp, true); - } - } - - static void TestRollingEventSequence(params LogEvent[] events) - { - TestRollingEventSequence(events, null, f => {}); - } - - static void TestRollingEventSequence( - IEnumerable events, - int? retainedFiles, - Action> verifyWritten) - { - var fileName = Some.String() + "-{Date}.txt"; - var folder = Some.TempFolderPath(); - var pathFormat = Path.Combine(folder, fileName); - - var log = new LoggerConfiguration() - .WriteTo.RollingFile(pathFormat, retainedFileCountLimit: retainedFiles) - .CreateLogger(); - - var verified = new List(); - - try - { - foreach (var @event in events) - { - Clock.SetTestDateTimeNow(@event.Timestamp.DateTime); - log.Write(@event); - - var expected = pathFormat.Replace("{Date}", @event.Timestamp.ToString("yyyyMMdd")); - Assert.True(File.Exists(expected)); - - verified.Add(expected); - } - } - finally - { - ((IDisposable)log).Dispose(); - verifyWritten(verified); - Directory.Delete(folder, true); - } - } - } -} -#endif diff --git a/test/Serilog.Tests/Sinks/RollingFile/TemplatedPathRollerTests.cs b/test/Serilog.Tests/Sinks/RollingFile/TemplatedPathRollerTests.cs deleted file mode 100644 index 5e0332708..000000000 --- a/test/Serilog.Tests/Sinks/RollingFile/TemplatedPathRollerTests.cs +++ /dev/null @@ -1,132 +0,0 @@ -#if INTERNAL_TESTS - -using System; -using System.IO; -using System.Linq; -using Xunit; -using Serilog.Sinks.RollingFile; - -namespace Serilog.Tests.Sinks.RollingFile -{ - public class TemplatedPathRollerTests - { - [Fact] - public void WhenOldStyleSpecifierIsSuppliedTheExceptionIsInformative() - { - var ex = Assert.Throws(() => new TemplatedPathRoller("log-{0}.txt")); - Assert.True(ex.Message.Contains("{Date}")); - } - - [Fact] - public void NewStyleSpecifierCannotBeProvidedInDirectory() - { - var ex = Assert.Throws(() => new TemplatedPathRoller("{Date}\\log.txt")); - Assert.True(ex.Message.Contains("directory")); - } - - [Fact] - public void TheLogFileIncludesDateToken() - { - var roller = new TemplatedPathRoller("Logs\\log.{Date}.txt"); - var now = new DateTime(2013, 7, 14, 3, 24, 9, 980); - string path; - roller.GetLogFilePath(now, 0, out path); - AssertEqualAbsolute("Logs\\log.20130714.txt", path); - } - - [Fact] - public void ANonZeroIncrementIsIncludedAndPadded() - { - var roller = new TemplatedPathRoller("Logs\\log.{Date}.txt"); - var now = new DateTime(2013, 7, 14, 3, 24, 9, 980); - string path; - roller.GetLogFilePath(now, 12, out path); - AssertEqualAbsolute("Logs\\log.20130714_012.txt", path); - } - - static void AssertEqualAbsolute(string path1, string path2) - { - var abs1 = Path.GetFullPath(path1); - var abs2 = Path.GetFullPath(path2); - Assert.Equal(abs1, abs2); - } - - [Fact] - public void TheRollerReturnsTheLogFileDirectory() - { - var roller = new TemplatedPathRoller("Logs\\log.{Date}.txt"); - AssertEqualAbsolute("Logs", roller.LogFileDirectory); - } - - [Fact] - public void IfNoTokenIsSpecifiedDashFollowedByTheDateIsImplied() - { - var roller = new TemplatedPathRoller("Logs\\log.txt"); - var now = new DateTime(2013, 7, 14, 3, 24, 9, 980); - string path; - roller.GetLogFilePath(now, 0, out path); - AssertEqualAbsolute("Logs\\log-20130714.txt", path); - } - - [Fact] - public void TheLogFileIsNotRequiredToIncludeAnExtension() - { - var roller = new TemplatedPathRoller("Logs\\log-{Date}"); - var now = new DateTime(2013, 7, 14, 3, 24, 9, 980); - string path; - roller.GetLogFilePath(now, 0, out path); - AssertEqualAbsolute("Logs\\log-20130714", path); - } - - [Fact] - public void TheLogFileIsNotRequiredToIncludeADirectory() - { - var roller = new TemplatedPathRoller("log-{Date}"); - var now = new DateTime(2013, 7, 14, 3, 24, 9, 980); - string path; - roller.GetLogFilePath(now, 0, out path); - AssertEqualAbsolute("log-20130714", path); - } - - [Fact] - public void TheDirectorSearchPatternUsesWildcardInPlaceOfDate() - { - var roller = new TemplatedPathRoller("Logs\\log-{Date}.txt"); - Assert.Equal("log-*.txt", roller.DirectorySearchPattern); - } - - [Fact] - public void MatchingSelectsFiles() - { - var roller = new TemplatedPathRoller("log-{Date}.txt"); - const string example1 = "log-20131210.txt"; - const string example2 = "log-20131210_031.txt"; - var matched = roller.SelectMatches(new[] { example1, example2 }).ToArray(); - Assert.Equal(2, matched.Count()); - Assert.Equal(0, matched[0].SequenceNumber); - Assert.Equal(31, matched[1].SequenceNumber); - } - - [Fact] - public void MatchingExcludesSimilarButNonmatchingFiles() - { - var roller = new TemplatedPathRoller("log-{Date}.txt"); - const string similar1 = "log-0.txt"; - const string similar2 = "log-helloyou.txt"; - var matched = roller.SelectMatches(new[] { similar1, similar2 }); - Assert.Equal(0, matched.Count()); - } - - [Fact] - public void MatchingParsesDates() - { - var roller = new TemplatedPathRoller("log-{Date}.txt"); - const string newer = "log-20150101.txt"; - const string older = "log-20141231.txt"; - var matched = roller.SelectMatches(new[] { older, newer }).OrderByDescending(m => m.Date).Select(m => m.Filename).ToArray(); - Assert.Equal(new[] { newer, older }, matched); - } - } -} - -#endif diff --git a/test/Serilog.Tests/Sinks/TextWriter/TextWriterSinkTests.cs b/test/Serilog.Tests/Sinks/TextWriter/TextWriterSinkTests.cs deleted file mode 100644 index 9a5b0d475..000000000 --- a/test/Serilog.Tests/Sinks/TextWriter/TextWriterSinkTests.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Globalization; -using System.IO; -using Xunit; -using Serilog.Tests.Support; - -namespace Serilog.Tests.Sinks.TextWriter -{ - public class TextWriterSinkTests - { - [Fact] - public void EventsAreWrittenToTheTextWriter() - { - var sw = new StringWriter(); - - var log = new LoggerConfiguration() - .WriteTo.TextWriter(sw) - .CreateLogger(); - - var mt = Some.String(); - log.Information(mt); - - var s = sw.ToString(); - Assert.True(s.Contains(mt)); - } - - [Fact] - public void EventsAreWrittenToTheTextWriterUsingFormatProvider() - { - var sw = new StringWriter(); - - var french = new CultureInfo("fr-FR"); - var log = new LoggerConfiguration() - .WriteTo.TextWriter(sw, formatProvider: french) - .CreateLogger(); - - var mt = String.Format(french, "{0}", 12.345); - log.Information("{0}", 12.345); - - var s = sw.ToString(); - Assert.True(s.Contains(mt)); - } - } -} diff --git a/test/Serilog.Tests/project.json b/test/Serilog.Tests/project.json index 99cb81e8f..c9320f51a 100644 --- a/test/Serilog.Tests/project.json +++ b/test/Serilog.Tests/project.json @@ -10,15 +10,14 @@ "Serilog": { "target": "project" }, "xunit": "2.1.0", "xunit.runner.visualstudio": "2.1.0", - "xunit.runner.dnx": "2.1.0-rc1-build204", - "Serilog.Sinks.File": { "target": "project" }, - "Serilog.Sinks.RollingFile": { "target": "project" }, - "Serilog.Sinks.PeriodicBatching": { "target": "project" }, - "Serilog.Sinks.Observable": { "target": "project" }, - "Serilog.Sinks.TextWriter": { "target": "project" }, + "xunit.runner.dnx": "2.1.0-rc1-build204", "Serilog.Enrichers.Environment": { "target": "project" }, "Serilog.Enrichers.Thread": { "target": "project" }, - "Serilog.Enrichers.Process": { "target": "project"} + "Serilog.Enrichers.Process": { "target": "project" }, + "Serilog.Sinks.TextWriter": "2.0.0-beta-519", + "Serilog.Sinks.RollingFile": "2.0.0-beta-519", + "Serilog.Sinks.PeriodicBatching": "2.0.0-beta-519", + "Serilog.Sinks.Observable": "2.0.0-beta-519" }, "frameworks": { "dnx452": {