Skip to content

Commit

Permalink
Merge pull request #311 from nblumhardt/serilog-4
Browse files Browse the repository at this point in the history
Updates for Serilog 4
  • Loading branch information
nblumhardt authored Jun 19, 2024
2 parents 08e9025 + 58939c6 commit 2d9fd8f
Show file tree
Hide file tree
Showing 28 changed files with 461 additions and 948 deletions.
32 changes: 14 additions & 18 deletions Build.ps1
Original file line number Diff line number Diff line change
@@ -1,46 +1,42 @@
echo "build: Build started"
Write-Output "build: Build started"

Push-Location $PSScriptRoot

if(Test-Path .\artifacts) {
echo "build: Cleaning .\artifacts"
Remove-Item .\artifacts -Force -Recurse
Write-Output "build: Cleaning ./artifacts"
Remove-Item ./artifacts -Force -Recurse
}

& dotnet restore --no-cache

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

echo "build: Package version suffix is $suffix"
echo "build: Build version suffix is $buildSuffix"
Write-Output "build: Package version suffix is $suffix"

foreach ($src in ls src/*) {
foreach ($src in Get-ChildItem src/*) {
Push-Location $src

echo "build: Packaging project in $src"
Write-Output "build: Packaging project in $src"

& dotnet build -c Release --version-suffix=$buildSuffix -p:EnableSourceLink=true
if ($suffix) {
& dotnet pack -c Release -o ..\..\artifacts --version-suffix=$suffix --no-build
& dotnet pack -c Release --include-source -o ../../artifacts --version-suffix=$suffix
} else {
& dotnet pack -c Release -o ..\..\artifacts --no-build
& dotnet pack -c Release --include-source -o ../../artifacts
}
if($LASTEXITCODE -ne 0) { exit 1 }
if($LASTEXITCODE -ne 0) { throw "Packaging failed" }

Pop-Location
}

foreach ($test in ls test/*.Tests) {
foreach ($test in Get-ChildItem test/*.Tests) {
Push-Location $test

echo "build: Testing project in $test"
Write-Output "build: Testing project in $test"

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

Pop-Location
}
Expand Down
1 change: 1 addition & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)assets/Serilog.snk</AssemblyOriginatorKeyFile>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
<Reference Include="System" />
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Writes [Serilog](https://serilog.net) events to one or more text files.
Install the [Serilog.Sinks.File](https://www.nuget.org/packages/Serilog.Sinks.File/) package from NuGet:

```powershell
Install-Package Serilog.Sinks.File
dotnet add package Serilog.Sinks.File
```

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

```csharp
.WriteTo.File("log.txt", fileSizeLimitBytes: null)
```
```

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.

Expand Down
6 changes: 3 additions & 3 deletions appveyor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ version: '{build}'
skip_tags: true
image:
- Visual Studio 2022
- Ubuntu
- Ubuntu2204
build_script:
- ps: ./Build.ps1
- pwsh: ./Build.ps1
for:
-
matrix:
Expand All @@ -19,7 +19,7 @@ artifacts:
deploy:
- provider: NuGet
api_key:
secure: LE+O+3Zs0nz2F/+M4eDvKBhEBUpUV0t864vN/2dxwa7aIVqeU3pKSMjWRX+JWJ49
secure: sDnchSg4TZIOK7oIUI6BJwFPNENTOZrGNsroGO1hehLJSvlHpFmpTwiX8+bgPD+Q
on:
branch: /^(main|dev)$/
- provider: GitHub
Expand Down
40 changes: 16 additions & 24 deletions example/Sample/Program.cs
Original file line number Diff line number Diff line change
@@ -1,35 +1,27 @@
using Serilog;
using Serilog.Debugging;

namespace Sample;
SelfLog.Enable(Console.Out);

public class Program
{
public static void Main(string[] args)
{
SelfLog.Enable(Console.Out);

var sw = System.Diagnostics.Stopwatch.StartNew();
var sw = System.Diagnostics.Stopwatch.StartNew();

Log.Logger = new LoggerConfiguration()
.WriteTo.File("log.txt")
.CreateLogger();
Log.Logger = new LoggerConfiguration()
.WriteTo.File("log.txt")
.CreateLogger();

for (var i = 0; i < 1000000; ++i)
{
Log.Information("Hello, file logger!");
}
for (var i = 0; i < 1000000; ++i)
{
Log.Information("Hello, file logger!");
}

Log.CloseAndFlush();
Log.CloseAndFlush();

sw.Stop();
sw.Stop();

Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds} ms");
Console.WriteLine($"Size: {new FileInfo("log.txt").Length}");
Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds} ms");
Console.WriteLine($"Size: {new FileInfo("log.txt").Length}");

Console.WriteLine("Press any key to delete the temporary log file...");
Console.ReadKey(true);
Console.WriteLine("Press any key to delete the temporary log file...");
Console.ReadKey(true);

File.Delete("log.txt");
}
}
File.Delete("log.txt");
2 changes: 1 addition & 1 deletion example/Sample/Sample.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net48;net6.0</TargetFrameworks>
<TargetFrameworks>net48;net8.0</TargetFrameworks>
<OutputType>Exe</OutputType>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
Expand Down
4 changes: 2 additions & 2 deletions src/Serilog.Sinks.File/FileLoggerConfigurationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -518,8 +518,8 @@ static LoggerConfiguration ConfigureFile(
if (addSink == null) throw new ArgumentNullException(nameof(addSink));
if (formatter == null) throw new ArgumentNullException(nameof(formatter));
if (path == null) throw new ArgumentNullException(nameof(path));
if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 1) throw new ArgumentException("Invalid value provided; file size limit must be at least 1 byte, or null.", nameof(fileSizeLimitBytes));
if (retainedFileCountLimit.HasValue && retainedFileCountLimit < 1) throw new ArgumentException("At least one file must be retained.", nameof(retainedFileCountLimit));
if (fileSizeLimitBytes is < 1) throw new ArgumentException("Invalid value provided; file size limit must be at least 1 byte, or null.", nameof(fileSizeLimitBytes));
if (retainedFileCountLimit is < 1) throw new ArgumentException("At least one file must be retained.", nameof(retainedFileCountLimit));
if (retainedFileTimeLimit.HasValue && retainedFileTimeLimit < TimeSpan.Zero) throw new ArgumentException("Negative value provided; retained file time limit must be non-negative.", nameof(retainedFileTimeLimit));
if (shared && buffered) throw new ArgumentException("Buffered writes are not available when file sharing is enabled.", nameof(buffered));
if (shared && hooks != null) throw new ArgumentException("File lifecycle hooks are not currently supported for shared log files.", nameof(hooks));
Expand Down
33 changes: 22 additions & 11 deletions src/Serilog.Sinks.File/Serilog.Sinks.File.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,42 +2,53 @@

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

<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" />
<PackageReference Include="Serilog" Version="2.10.0" />
<PackageReference Include="Serilog" Version="4.0.0" />
<PackageReference Include="Nullable" Version="1.3.1" PrivateAssets="All" />
</ItemGroup>

<PropertyGroup Condition=" '$(TargetFramework)' == 'net45' ">
<PropertyGroup Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' ">
<DefineConstants>$(DefineConstants);ATOMIC_APPEND;HRESULTS</DefineConstants>
</PropertyGroup>

<PropertyGroup Condition=" '$(TargetFramework)' != 'net45' ">
<PropertyGroup Condition=" '$(TargetFrameworkIdentifier)' != '.NETFramework' ">
<DefineConstants>$(DefineConstants);OS_MUTEX</DefineConstants>
</PropertyGroup>

<PropertyGroup Condition=" '$(TargetFramework)' == 'net6.0' ">
<DefineConstants>$(DefineConstants);ENUMERABLE_MAXBY</DefineConstants>
</PropertyGroup>

<PropertyGroup Condition=" '$(TargetFramework)' == 'net8.0' ">
<DefineConstants>$(DefineConstants);ENUMERABLE_MAXBY</DefineConstants>
</PropertyGroup>

<ItemGroup>
<None Include="..\..\assets\serilog-sink-nuget.png" Pack="true" Visible="false" PackagePath="images\icon.png" />
<None Include="..\..\assets\serilog-sink-nuget.png" Pack="true" Visible="false" PackagePath="/" />
<None Include="..\..\README.md" Pack="true" Visible="false" PackagePath="/" />
</ItemGroup>

</Project>
6 changes: 3 additions & 3 deletions src/Serilog.Sinks.File/Sinks/File/FileLifeCycleHookChain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@

namespace Serilog.Sinks.File;

class FileLifeCycleHookChain : FileLifecycleHooks
sealed class FileLifeCycleHookChain : FileLifecycleHooks
{
private readonly FileLifecycleHooks _first;
private readonly FileLifecycleHooks _second;
readonly FileLifecycleHooks _first;
readonly FileLifecycleHooks _second;

public FileLifeCycleHookChain(FileLifecycleHooks first, FileLifecycleHooks second)
{
Expand Down
1 change: 1 addition & 0 deletions src/Serilog.Sinks.File/Sinks/File/FileLifecycleHooks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
// limitations under the License.

using System.Text;
// ReSharper disable UnusedMember.Global

namespace Serilog.Sinks.File;

Expand Down
2 changes: 1 addition & 1 deletion src/Serilog.Sinks.File/Sinks/File/FileSink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ internal FileSink(
FileLifecycleHooks? hooks)
{
if (path == null) throw new ArgumentNullException(nameof(path));
if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 1) throw new ArgumentException("Invalid value provided; file size limit must be at least 1 byte, or null.");
if (fileSizeLimitBytes is < 1) throw new ArgumentException("Invalid value provided; file size limit must be at least 1 byte, or null.");
_textFormatter = textFormatter ?? throw new ArgumentNullException(nameof(textFormatter));
_fileSizeLimitBytes = fileSizeLimitBytes;
_buffered = buffered;
Expand Down
4 changes: 2 additions & 2 deletions src/Serilog.Sinks.File/Sinks/File/NullSink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ namespace Serilog.Sinks.File;
/// An instance of this sink may be substituted when an instance of the
/// <see cref="FileSink"/> is unable to be constructed.
/// </summary>
class NullSink : ILogEventSink
sealed class NullSink : ILogEventSink
{
public void Emit(LogEvent logEvent)
{
}
}
}
2 changes: 1 addition & 1 deletion src/Serilog.Sinks.File/Sinks/File/PathRoller.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

namespace Serilog.Sinks.File;

class PathRoller
sealed class PathRoller
{
const string PeriodMatchGroup = "period";
const string SequenceNumberMatchGroup = "sequence";
Expand Down
14 changes: 10 additions & 4 deletions src/Serilog.Sinks.File/Sinks/File/RollingFileSink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ public RollingFileSink(string path,
TimeSpan? retainedFileTimeLimit)
{
if (path == null) throw new ArgumentNullException(nameof(path));
if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 1) throw new ArgumentException("Invalid value provided; file size limit must be at least 1 byte, or null.");
if (retainedFileCountLimit.HasValue && retainedFileCountLimit < 1) throw new ArgumentException("Zero or negative value provided; retained file count limit must be at least 1");
if (fileSizeLimitBytes is < 1) throw new ArgumentException("Invalid value provided; file size limit must be at least 1 byte, or null.");
if (retainedFileCountLimit is < 1) throw new ArgumentException("Zero or negative value provided; retained file count limit must be at least 1.");
if (retainedFileTimeLimit.HasValue && retainedFileTimeLimit < TimeSpan.Zero) throw new ArgumentException("Negative value provided; retained file time limit must be non-negative.", nameof(retainedFileTimeLimit));

_roller = new PathRoller(path, rollingInterval);
Expand Down Expand Up @@ -121,17 +121,22 @@ void OpenFile(DateTime now, int? minSequence = null)
{
if (Directory.Exists(_roller.LogFileDirectory))
{
// ReSharper disable once ConvertClosureToMethodGroup
existingFiles = Directory.GetFiles(_roller.LogFileDirectory, _roller.DirectorySearchPattern)
.Select(f => Path.GetFileName(f));
.Select(f => Path.GetFileName(f));
}
}
catch (DirectoryNotFoundException) { }

var latestForThisCheckpoint = _roller
.SelectMatches(existingFiles)
.Where(m => m.DateTime == currentCheckpoint)
#if ENUMERABLE_MAXBY
.MaxBy(m => m.SequenceNumber);
#else
.OrderByDescending(m => m.SequenceNumber)
.FirstOrDefault();
#endif

var sequence = latestForThisCheckpoint?.SequenceNumber;
if (minSequence != null)
Expand All @@ -149,7 +154,7 @@ void OpenFile(DateTime now, int? minSequence = null)
{
_currentFile = _shared ?
#pragma warning disable 618
(IFileSink)new SharedFileSink(path, _textFormatter, _fileSizeLimitBytes, _encoding) :
new SharedFileSink(path, _textFormatter, _fileSizeLimitBytes, _encoding) :
#pragma warning restore 618
new FileSink(path, _textFormatter, _fileSizeLimitBytes, _encoding, _buffered, _hooks);

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

// 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.
// ReSharper disable once ConvertClosureToMethodGroup
var potentialMatches = Directory.GetFiles(_roller.LogFileDirectory, _roller.DirectorySearchPattern)
.Select(f => Path.GetFileName(f))
.Union(new[] { currentFileName });
Expand Down
Loading

0 comments on commit 2d9fd8f

Please sign in to comment.