Skip to content

Commit 2d9fd8f

Browse files
authored
Merge pull request #311 from nblumhardt/serilog-4
Updates for Serilog 4
2 parents 08e9025 + 58939c6 commit 2d9fd8f

28 files changed

+461
-948
lines changed

Build.ps1

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,42 @@
1-
echo "build: Build started"
1+
Write-Output "build: Build started"
22

33
Push-Location $PSScriptRoot
44

55
if(Test-Path .\artifacts) {
6-
echo "build: Cleaning .\artifacts"
7-
Remove-Item .\artifacts -Force -Recurse
6+
Write-Output "build: Cleaning ./artifacts"
7+
Remove-Item ./artifacts -Force -Recurse
88
}
99

1010
& dotnet restore --no-cache
1111

12-
$branch = @{ $true = $env:APPVEYOR_REPO_BRANCH; $false = $(git symbolic-ref --short -q HEAD) }[$env:APPVEYOR_REPO_BRANCH -ne $NULL];
13-
$revision = @{ $true = "{0:00000}" -f [convert]::ToInt32("0" + $env:APPVEYOR_BUILD_NUMBER, 10); $false = "local" }[$env:APPVEYOR_BUILD_NUMBER -ne $NULL];
12+
$branch = @{ $true = $env:APPVEYOR_REPO_BRANCH; $false = $(git symbolic-ref --short -q HEAD) }[$NULL -ne $env:APPVEYOR_REPO_BRANCH];
13+
$revision = @{ $true = "{0:00000}" -f [convert]::ToInt32("0" + $env:APPVEYOR_BUILD_NUMBER, 10); $false = "local" }[$NULL -ne $env:APPVEYOR_BUILD_NUMBER];
1414
$suffix = @{ $true = ""; $false = "$($branch.Substring(0, [math]::Min(10,$branch.Length)))-$revision"}[$branch -eq "main" -and $revision -ne "local"]
15-
$commitHash = $(git rev-parse --short HEAD)
16-
$buildSuffix = @{ $true = "$($suffix)-$($commitHash)"; $false = "$($branch)-$($commitHash)" }[$suffix -ne ""]
1715

18-
echo "build: Package version suffix is $suffix"
19-
echo "build: Build version suffix is $buildSuffix"
16+
Write-Output "build: Package version suffix is $suffix"
2017

21-
foreach ($src in ls src/*) {
18+
foreach ($src in Get-ChildItem src/*) {
2219
Push-Location $src
2320

24-
echo "build: Packaging project in $src"
21+
Write-Output "build: Packaging project in $src"
2522

26-
& dotnet build -c Release --version-suffix=$buildSuffix -p:EnableSourceLink=true
2723
if ($suffix) {
28-
& dotnet pack -c Release -o ..\..\artifacts --version-suffix=$suffix --no-build
24+
& dotnet pack -c Release --include-source -o ../../artifacts --version-suffix=$suffix
2925
} else {
30-
& dotnet pack -c Release -o ..\..\artifacts --no-build
26+
& dotnet pack -c Release --include-source -o ../../artifacts
3127
}
32-
if($LASTEXITCODE -ne 0) { exit 1 }
28+
if($LASTEXITCODE -ne 0) { throw "Packaging failed" }
3329

3430
Pop-Location
3531
}
3632

37-
foreach ($test in ls test/*.Tests) {
33+
foreach ($test in Get-ChildItem test/*.Tests) {
3834
Push-Location $test
3935

40-
echo "build: Testing project in $test"
36+
Write-Output "build: Testing project in $test"
4137

4238
& dotnet test -c Release
43-
if($LASTEXITCODE -ne 0) { exit 3 }
39+
if($LASTEXITCODE -ne 0) { throw "Testing failed" }
4440

4541
Pop-Location
4642
}

Directory.Build.props

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
<AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)assets/Serilog.snk</AssemblyOriginatorKeyFile>
88
<Nullable>enable</Nullable>
99
<ImplicitUsings>enable</ImplicitUsings>
10+
<LangVersion>latest</LangVersion>
1011
</PropertyGroup>
1112
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
1213
<Reference Include="System" />

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ Writes [Serilog](https://serilog.net) events to one or more text files.
77
Install the [Serilog.Sinks.File](https://www.nuget.org/packages/Serilog.Sinks.File/) package from NuGet:
88

99
```powershell
10-
Install-Package Serilog.Sinks.File
10+
dotnet add package Serilog.Sinks.File
1111
```
1212

1313
To configure the sink in C# code, call `WriteTo.File()` during logger configuration:
@@ -36,7 +36,7 @@ The limit can be changed or removed using the `fileSizeLimitBytes` parameter.
3636

3737
```csharp
3838
.WriteTo.File("log.txt", fileSizeLimitBytes: null)
39-
```
39+
```
4040

4141
For the same reason, only **the most recent 31 files** are retained by default (i.e. one long month). To change or remove this limit, pass the `retainedFileCountLimit` parameter.
4242

appveyor.yml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ version: '{build}'
22
skip_tags: true
33
image:
44
- Visual Studio 2022
5-
- Ubuntu
5+
- Ubuntu2204
66
build_script:
7-
- ps: ./Build.ps1
7+
- pwsh: ./Build.ps1
88
for:
99
-
1010
matrix:
@@ -19,7 +19,7 @@ artifacts:
1919
deploy:
2020
- provider: NuGet
2121
api_key:
22-
secure: LE+O+3Zs0nz2F/+M4eDvKBhEBUpUV0t864vN/2dxwa7aIVqeU3pKSMjWRX+JWJ49
22+
secure: sDnchSg4TZIOK7oIUI6BJwFPNENTOZrGNsroGO1hehLJSvlHpFmpTwiX8+bgPD+Q
2323
on:
2424
branch: /^(main|dev)$/
2525
- provider: GitHub

example/Sample/Program.cs

Lines changed: 16 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,27 @@
11
using Serilog;
22
using Serilog.Debugging;
33

4-
namespace Sample;
4+
SelfLog.Enable(Console.Out);
55

6-
public class Program
7-
{
8-
public static void Main(string[] args)
9-
{
10-
SelfLog.Enable(Console.Out);
11-
12-
var sw = System.Diagnostics.Stopwatch.StartNew();
6+
var sw = System.Diagnostics.Stopwatch.StartNew();
137

14-
Log.Logger = new LoggerConfiguration()
15-
.WriteTo.File("log.txt")
16-
.CreateLogger();
8+
Log.Logger = new LoggerConfiguration()
9+
.WriteTo.File("log.txt")
10+
.CreateLogger();
1711

18-
for (var i = 0; i < 1000000; ++i)
19-
{
20-
Log.Information("Hello, file logger!");
21-
}
12+
for (var i = 0; i < 1000000; ++i)
13+
{
14+
Log.Information("Hello, file logger!");
15+
}
2216

23-
Log.CloseAndFlush();
17+
Log.CloseAndFlush();
2418

25-
sw.Stop();
19+
sw.Stop();
2620

27-
Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds} ms");
28-
Console.WriteLine($"Size: {new FileInfo("log.txt").Length}");
21+
Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds} ms");
22+
Console.WriteLine($"Size: {new FileInfo("log.txt").Length}");
2923

30-
Console.WriteLine("Press any key to delete the temporary log file...");
31-
Console.ReadKey(true);
24+
Console.WriteLine("Press any key to delete the temporary log file...");
25+
Console.ReadKey(true);
3226

33-
File.Delete("log.txt");
34-
}
35-
}
27+
File.Delete("log.txt");

example/Sample/Sample.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<Project Sdk="Microsoft.NET.Sdk">
22

33
<PropertyGroup>
4-
<TargetFrameworks>net48;net6.0</TargetFrameworks>
4+
<TargetFrameworks>net48;net8.0</TargetFrameworks>
55
<OutputType>Exe</OutputType>
66
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
77
</PropertyGroup>

src/Serilog.Sinks.File/FileLoggerConfigurationExtensions.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -518,8 +518,8 @@ static LoggerConfiguration ConfigureFile(
518518
if (addSink == null) throw new ArgumentNullException(nameof(addSink));
519519
if (formatter == null) throw new ArgumentNullException(nameof(formatter));
520520
if (path == null) throw new ArgumentNullException(nameof(path));
521-
if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 1) throw new ArgumentException("Invalid value provided; file size limit must be at least 1 byte, or null.", nameof(fileSizeLimitBytes));
522-
if (retainedFileCountLimit.HasValue && retainedFileCountLimit < 1) throw new ArgumentException("At least one file must be retained.", nameof(retainedFileCountLimit));
521+
if (fileSizeLimitBytes is < 1) throw new ArgumentException("Invalid value provided; file size limit must be at least 1 byte, or null.", nameof(fileSizeLimitBytes));
522+
if (retainedFileCountLimit is < 1) throw new ArgumentException("At least one file must be retained.", nameof(retainedFileCountLimit));
523523
if (retainedFileTimeLimit.HasValue && retainedFileTimeLimit < TimeSpan.Zero) throw new ArgumentException("Negative value provided; retained file time limit must be non-negative.", nameof(retainedFileTimeLimit));
524524
if (shared && buffered) throw new ArgumentException("Buffered writes are not available when file sharing is enabled.", nameof(buffered));
525525
if (shared && hooks != null) throw new ArgumentException("File lifecycle hooks are not currently supported for shared log files.", nameof(hooks));

src/Serilog.Sinks.File/Serilog.Sinks.File.csproj

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,42 +2,53 @@
22

33
<PropertyGroup>
44
<Description>Write Serilog events to text files in plain or JSON format.</Description>
5-
<VersionPrefix>5.0.1</VersionPrefix>
5+
<VersionPrefix>6.0.0</VersionPrefix>
66
<Authors>Serilog Contributors</Authors>
7-
<TargetFrameworks>net45;netstandard1.3;netstandard2.0;netstandard2.1;net5.0;net6.0</TargetFrameworks>
7+
<!-- .NET Framework version targeting is frozen at these two TFMs. -->
8+
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT'">net471;net462</TargetFrameworks>
9+
<!-- Policy is to trim TFM-specific builds to `netstandard2.0`, `net6.0`,
10+
all active LTS versions, and optionally the latest RTM version, when releasing new
11+
major Serilog versions. -->
12+
<TargetFrameworks>$(TargetFrameworks);net8.0;net6.0;netstandard2.0</TargetFrameworks>
813
<GenerateDocumentationFile>true</GenerateDocumentationFile>
914
<PackageTags>serilog;file</PackageTags>
10-
<PackageIcon>images\icon.png</PackageIcon>
15+
<PackageIcon>serilog-sink-nuget.png</PackageIcon>
1116
<PackageIconUrl>https://serilog.net/images/serilog-sink-nuget.png</PackageIconUrl>
1217
<PackageProjectUrl>https://github.com/serilog/serilog-sinks-file</PackageProjectUrl>
1318
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
1419
<RepositoryUrl>https://github.com/serilog/serilog-sinks-file</RepositoryUrl>
1520
<RepositoryType>git</RepositoryType>
1621
<RootNamespace>Serilog</RootNamespace>
17-
<DisableImplicitFrameworkReferences Condition=" '$(TargetFramework)' == 'netstandard1.3' ">true</DisableImplicitFrameworkReferences>
18-
<EnableSourceLink Condition="'$(EnableSourceLink)' == ''">false</EnableSourceLink>
1922
<PublishRepositoryUrl>true</PublishRepositoryUrl>
20-
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
2123
<IncludeSymbols>True</IncludeSymbols>
2224
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
25+
<PackageReadmeFile>README.md</PackageReadmeFile>
2326
</PropertyGroup>
2427

2528
<ItemGroup>
26-
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" />
27-
<PackageReference Include="Serilog" Version="2.10.0" />
29+
<PackageReference Include="Serilog" Version="4.0.0" />
2830
<PackageReference Include="Nullable" Version="1.3.1" PrivateAssets="All" />
2931
</ItemGroup>
3032

31-
<PropertyGroup Condition=" '$(TargetFramework)' == 'net45' ">
33+
<PropertyGroup Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' ">
3234
<DefineConstants>$(DefineConstants);ATOMIC_APPEND;HRESULTS</DefineConstants>
3335
</PropertyGroup>
3436

35-
<PropertyGroup Condition=" '$(TargetFramework)' != 'net45' ">
37+
<PropertyGroup Condition=" '$(TargetFrameworkIdentifier)' != '.NETFramework' ">
3638
<DefineConstants>$(DefineConstants);OS_MUTEX</DefineConstants>
3739
</PropertyGroup>
3840

41+
<PropertyGroup Condition=" '$(TargetFramework)' == 'net6.0' ">
42+
<DefineConstants>$(DefineConstants);ENUMERABLE_MAXBY</DefineConstants>
43+
</PropertyGroup>
44+
45+
<PropertyGroup Condition=" '$(TargetFramework)' == 'net8.0' ">
46+
<DefineConstants>$(DefineConstants);ENUMERABLE_MAXBY</DefineConstants>
47+
</PropertyGroup>
48+
3949
<ItemGroup>
40-
<None Include="..\..\assets\serilog-sink-nuget.png" Pack="true" Visible="false" PackagePath="images\icon.png" />
50+
<None Include="..\..\assets\serilog-sink-nuget.png" Pack="true" Visible="false" PackagePath="/" />
51+
<None Include="..\..\README.md" Pack="true" Visible="false" PackagePath="/" />
4152
</ItemGroup>
4253

4354
</Project>

src/Serilog.Sinks.File/Sinks/File/FileLifeCycleHookChain.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@
1616

1717
namespace Serilog.Sinks.File;
1818

19-
class FileLifeCycleHookChain : FileLifecycleHooks
19+
sealed class FileLifeCycleHookChain : FileLifecycleHooks
2020
{
21-
private readonly FileLifecycleHooks _first;
22-
private readonly FileLifecycleHooks _second;
21+
readonly FileLifecycleHooks _first;
22+
readonly FileLifecycleHooks _second;
2323

2424
public FileLifeCycleHookChain(FileLifecycleHooks first, FileLifecycleHooks second)
2525
{

src/Serilog.Sinks.File/Sinks/File/FileLifecycleHooks.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
// limitations under the License.
1414

1515
using System.Text;
16+
// ReSharper disable UnusedMember.Global
1617

1718
namespace Serilog.Sinks.File;
1819

src/Serilog.Sinks.File/Sinks/File/FileSink.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ internal FileSink(
6767
FileLifecycleHooks? hooks)
6868
{
6969
if (path == null) throw new ArgumentNullException(nameof(path));
70-
if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 1) throw new ArgumentException("Invalid value provided; file size limit must be at least 1 byte, or null.");
70+
if (fileSizeLimitBytes is < 1) throw new ArgumentException("Invalid value provided; file size limit must be at least 1 byte, or null.");
7171
_textFormatter = textFormatter ?? throw new ArgumentNullException(nameof(textFormatter));
7272
_fileSizeLimitBytes = fileSizeLimitBytes;
7373
_buffered = buffered;

src/Serilog.Sinks.File/Sinks/File/NullSink.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@ namespace Serilog.Sinks.File;
2121
/// An instance of this sink may be substituted when an instance of the
2222
/// <see cref="FileSink"/> is unable to be constructed.
2323
/// </summary>
24-
class NullSink : ILogEventSink
24+
sealed class NullSink : ILogEventSink
2525
{
2626
public void Emit(LogEvent logEvent)
2727
{
2828
}
29-
}
29+
}

src/Serilog.Sinks.File/Sinks/File/PathRoller.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
namespace Serilog.Sinks.File;
1919

20-
class PathRoller
20+
sealed class PathRoller
2121
{
2222
const string PeriodMatchGroup = "period";
2323
const string SequenceNumberMatchGroup = "sequence";

src/Serilog.Sinks.File/Sinks/File/RollingFileSink.cs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,8 @@ public RollingFileSink(string path,
5252
TimeSpan? retainedFileTimeLimit)
5353
{
5454
if (path == null) throw new ArgumentNullException(nameof(path));
55-
if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 1) throw new ArgumentException("Invalid value provided; file size limit must be at least 1 byte, or null.");
56-
if (retainedFileCountLimit.HasValue && retainedFileCountLimit < 1) throw new ArgumentException("Zero or negative value provided; retained file count limit must be at least 1");
55+
if (fileSizeLimitBytes is < 1) throw new ArgumentException("Invalid value provided; file size limit must be at least 1 byte, or null.");
56+
if (retainedFileCountLimit is < 1) throw new ArgumentException("Zero or negative value provided; retained file count limit must be at least 1.");
5757
if (retainedFileTimeLimit.HasValue && retainedFileTimeLimit < TimeSpan.Zero) throw new ArgumentException("Negative value provided; retained file time limit must be non-negative.", nameof(retainedFileTimeLimit));
5858

5959
_roller = new PathRoller(path, rollingInterval);
@@ -121,17 +121,22 @@ void OpenFile(DateTime now, int? minSequence = null)
121121
{
122122
if (Directory.Exists(_roller.LogFileDirectory))
123123
{
124+
// ReSharper disable once ConvertClosureToMethodGroup
124125
existingFiles = Directory.GetFiles(_roller.LogFileDirectory, _roller.DirectorySearchPattern)
125-
.Select(f => Path.GetFileName(f));
126+
.Select(f => Path.GetFileName(f));
126127
}
127128
}
128129
catch (DirectoryNotFoundException) { }
129130

130131
var latestForThisCheckpoint = _roller
131132
.SelectMatches(existingFiles)
132133
.Where(m => m.DateTime == currentCheckpoint)
134+
#if ENUMERABLE_MAXBY
135+
.MaxBy(m => m.SequenceNumber);
136+
#else
133137
.OrderByDescending(m => m.SequenceNumber)
134138
.FirstOrDefault();
139+
#endif
135140

136141
var sequence = latestForThisCheckpoint?.SequenceNumber;
137142
if (minSequence != null)
@@ -149,7 +154,7 @@ void OpenFile(DateTime now, int? minSequence = null)
149154
{
150155
_currentFile = _shared ?
151156
#pragma warning disable 618
152-
(IFileSink)new SharedFileSink(path, _textFormatter, _fileSizeLimitBytes, _encoding) :
157+
new SharedFileSink(path, _textFormatter, _fileSizeLimitBytes, _encoding) :
153158
#pragma warning restore 618
154159
new FileSink(path, _textFormatter, _fileSizeLimitBytes, _encoding, _buffered, _hooks);
155160

@@ -180,6 +185,7 @@ void ApplyRetentionPolicy(string currentFilePath, DateTime now)
180185

181186
// We consider the current file to exist, even if nothing's been written yet,
182187
// because files are only opened on response to an event being processed.
188+
// ReSharper disable once ConvertClosureToMethodGroup
183189
var potentialMatches = Directory.GetFiles(_roller.LogFileDirectory, _roller.DirectorySearchPattern)
184190
.Select(f => Path.GetFileName(f))
185191
.Union(new[] { currentFileName });

0 commit comments

Comments
 (0)