Skip to content

Support ILoggingFailureListener #342

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# If this file is renamed, the incrementing run attempt number will be reset.

name: CI

on:
push:
branches: [ "dev", "main" ]
pull_request:
branches: [ "dev", "main" ]

env:
CI_BUILD_NUMBER_BASE: ${{ github.run_number }}
CI_TARGET_BRANCH: ${{ github.head_ref || github.ref_name }}

jobs:
build:

# The build must run on Windows so that .NET Framework targets can be built and tested.
runs-on: windows-latest

permissions:
contents: write

steps:
- uses: actions/checkout@v4
- name: Setup
uses: actions/setup-dotnet@v4
with:
dotnet-version: 9.0.x
- name: Compute build number
shell: bash
run: |
echo "CI_BUILD_NUMBER=$(($CI_BUILD_NUMBER_BASE+2300))" >> $GITHUB_ENV
- name: Build and Publish
env:
DOTNET_CLI_TELEMETRY_OPTOUT: true
NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
shell: pwsh
run: |
./Build.ps1
87 changes: 61 additions & 26 deletions Build.ps1
Original file line number Diff line number Diff line change
@@ -1,44 +1,79 @@
Write-Output "build: Tool versions follow"

dotnet --version
dotnet --list-sdks

Write-Output "build: Build started"

Push-Location $PSScriptRoot
try {
if(Test-Path .\artifacts) {
Write-Output "build: Cleaning ./artifacts"
Remove-Item ./artifacts -Force -Recurse
}

if(Test-Path .\artifacts) {
Write-Output "build: Cleaning ./artifacts"
Remove-Item ./artifacts -Force -Recurse
}
& dotnet restore --no-cache

& dotnet restore --no-cache
$dbp = [Xml] (Get-Content .\Directory.Version.props)
$versionPrefix = $dbp.Project.PropertyGroup.VersionPrefix

$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"]
Write-Output "build: Package version prefix is $versionPrefix"

Write-Output "build: Package version suffix is $suffix"
$branch = @{ $true = $env:CI_TARGET_BRANCH; $false = $(git symbolic-ref --short -q HEAD) }[$NULL -ne $env:CI_TARGET_BRANCH];
$revision = @{ $true = "{0:00000}" -f [convert]::ToInt32("0" + $env:CI_BUILD_NUMBER, 10); $false = "local" }[$NULL -ne $env:CI_BUILD_NUMBER];
$suffix = @{ $true = ""; $false = "$($branch.Substring(0, [math]::Min(10,$branch.Length)) -replace '([^a-zA-Z0-9\-]*)', '')-$revision"}[$branch -eq "main" -and $revision -ne "local"]
$commitHash = $(git rev-parse --short HEAD)
$buildSuffix = @{ $true = "$($suffix)-$($commitHash)"; $false = "$($branch)-$($commitHash)" }[$suffix -ne ""]
Comment on lines +22 to +26
Copy link
Contributor

@Falco20019 Falco20019 Mar 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NIT: Only a suggestion to comply better with SemVer 2.0.0
https://learn.microsoft.com/en-us/nuget/concepts/package-versioning?tabs=semver20sort#pre-release-versions suggests to use the version in the format 7.0.0-selflog-on.1+04ac85d instead of 7.0.0-selflog-on-00001-04ac85d. Doing this will also allow you to just use $suffix instead of differentiating with $buildSuffix since the nuget package (and any relevant other part) will drop the metadata part as documented by https://learn.microsoft.com/en-us/nuget/concepts/package-versioning?tabs=semver20sort#normalized-version-numbers

Using the . instead of - before the CI number also signifies it's a numeric and should be sorted as such. NuGet/VisualStudio/... is aware of that, which makes it nicer than padding it to 5 digits. This is widely supported since VS 2017.

Suggested change
$branch = @{ $true = $env:CI_TARGET_BRANCH; $false = $(git symbolic-ref --short -q HEAD) }[$NULL -ne $env:CI_TARGET_BRANCH];
$revision = @{ $true = "{0:00000}" -f [convert]::ToInt32("0" + $env:CI_BUILD_NUMBER, 10); $false = "local" }[$NULL -ne $env:CI_BUILD_NUMBER];
$suffix = @{ $true = ""; $false = "$($branch.Substring(0, [math]::Min(10,$branch.Length)) -replace '([^a-zA-Z0-9\-]*)', '')-$revision"}[$branch -eq "main" -and $revision -ne "local"]
$commitHash = $(git rev-parse --short HEAD)
$buildSuffix = @{ $true = "$($suffix)-$($commitHash)"; $false = "$($branch)-$($commitHash)" }[$suffix -ne ""]
$branch = @{ $true = $env:CI_TARGET_BRANCH; $false = $(git symbolic-ref --short -q HEAD) }[$NULL -ne $env:CI_TARGET_BRANCH];
$revision = @{ $true = "{0}" -f [convert]::ToInt32("0" + $env:CI_BUILD_NUMBER, 10); $false = "local" }[$NULL -ne $env:CI_BUILD_NUMBER];
$suffix = @{ $true = ""; $false = "$($branch.Substring(0, [math]::Min(10,$branch.Length)) -replace '([^a-zA-Z0-9\-]*)', '').$revision"}[$branch -eq "main" -and $revision -ne "local"]
$buildSuffix = @{ $true = "$($suffix)"; $false = "$($branch)" }[$suffix -ne ""]

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Personally I would use 7.0.0-ci.1+04ac85d-selflog-on-open-failure, but tried to keep the suggestion closer to what you do right now.

Copy link
Contributor

@Falco20019 Falco20019 Mar 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Additionally, there seems to be something in place that adds the full revision anyway:
The result locally was: 7.0.0-selflog-on.1+04ac85d60ddb0e109312ca820a113b599d286dc9 with my change and 7.0.0-selflog-on-00001-04ac85d+04ac85d60ddb0e109312ca820a113b599d286dc9 with your current code.

I did check if this was local-only or also from the official packages, and the latest version on NuGet is 6.0.0+c7b9bc3d87f9bb98572a52286135efda1e608ad6.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for digging into this! These scripts are from the upstream serilog/serilog and we're trying to avoid configuration drift by making any changes up there. I agree this could be better 👍 - I'll leave this as-is here but take a look in the next round of maintenance on the Serilog package.


foreach ($src in Get-ChildItem src/*) {
Push-Location $src
Write-Output "build: Package version suffix is $suffix"
Write-Output "build: Build version suffix is $buildSuffix"

Write-Output "build: Packaging project in $src"
& dotnet build -c Release --version-suffix=$buildSuffix /p:ContinuousIntegrationBuild=true
if($LASTEXITCODE -ne 0) { throw "Build failed" }

if ($suffix) {
& dotnet pack -c Release --include-source -o ../../artifacts --version-suffix=$suffix
} else {
& dotnet pack -c Release --include-source -o ../../artifacts
foreach ($src in Get-ChildItem src/*) {
Push-Location $src

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

if ($suffix) {
& dotnet pack -c Release --no-build --no-restore -o ../../artifacts --version-suffix=$suffix
} else {
& dotnet pack -c Release --no-build --no-restore -o ../../artifacts
}
if($LASTEXITCODE -ne 0) { throw "Packaging failed" }

Pop-Location
}
if($LASTEXITCODE -ne 0) { throw "Packaging failed" }

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

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

& dotnet test -c Release --no-build --no-restore
if($LASTEXITCODE -ne 0) { throw "Testing failed" }

Pop-Location
}

if ($env:NUGET_API_KEY) {
# GitHub Actions will only supply this to branch builds and not PRs. We publish
# builds from any branch this action targets (i.e. main and dev).

foreach ($test in Get-ChildItem test/*.Tests) {
Push-Location $test
Write-Output "build: Publishing NuGet packages"

Write-Output "build: Testing project in $test"
foreach ($nupkg in Get-ChildItem artifacts/*.nupkg) {
& dotnet nuget push -k $env:NUGET_API_KEY -s https://api.nuget.org/v3/index.json "$nupkg"
if($LASTEXITCODE -ne 0) { throw "Publishing failed" }
}

& dotnet test -c Release
if($LASTEXITCODE -ne 0) { throw "Testing failed" }
if (!($suffix)) {
Write-Output "build: Creating release for version $versionPrefix"

iex "gh release create v$versionPrefix --title v$versionPrefix --generate-notes $(get-item ./artifacts/*.nupkg) $(get-item ./artifacts/*.snupkg)"
}
}
} finally {
Pop-Location
}

Pop-Location
14 changes: 11 additions & 3 deletions Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
<Project>
<!-- Properties in this file are expected to be identical for all Serilog organization projects. If
a property value is project-specific, please record it in the CSPROJ file instead. -->
<Import Project="$(MSBuildThisFileDirectory)Directory.Version.props" />
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>True</TreatWarningsAsErrors>
<SignAssembly>true</SignAssembly>
<PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
<!-- The condition is required to support BenchmarkDotNet -->
<SignAssembly Condition="Exists('$(MSBuildThisFileDirectory)assets/Serilog.snk')">true</SignAssembly>
<AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)assets/Serilog.snk</AssemblyOriginatorKeyFile>
<CheckEolTargetFramework>false</CheckEolTargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>latest</LangVersion>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
<Reference Include="System" />
Expand Down
5 changes: 5 additions & 0 deletions Directory.Version.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<Project>
<PropertyGroup>
<VersionPrefix>7.0.0</VersionPrefix>
</PropertyGroup>
</Project>
31 changes: 0 additions & 31 deletions appveyor.yml

This file was deleted.

17 changes: 0 additions & 17 deletions build.sh

This file was deleted.

7 changes: 7 additions & 0 deletions global.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"sdk": {
"version": "9.0.200",
"allowPrerelease": false,
"rollForward": "latestFeature"
}
}
16 changes: 12 additions & 4 deletions serilog-sinks-file.sln
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ VisualStudioVersion = 17.5.33424.131
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{037440DE-440B-4129-9F7A-09B42D00397E}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "assets", "assets", "{E9D1B5E1-DEB9-4A04-8BAB-24EC7240ADAF}"
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sln", "sln", "{E9D1B5E1-DEB9-4A04-8BAB-24EC7240ADAF}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
appveyor.yml = appveyor.yml
Build.ps1 = Build.ps1
build.sh = build.sh
Directory.Build.props = Directory.Build.props
Directory.Build.targets = Directory.Build.targets
README.md = README.md
assets\Serilog.snk = assets\Serilog.snk
global.json = global.json
Build.ps1 = Build.ps1
Directory.Version.props = Directory.Version.props
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{7B927378-9F16-4F6F-B3F6-156395136646}"
Expand All @@ -27,6 +27,13 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.Sinks.File.Tests",
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sample", "example\Sample\Sample.csproj", "{A34235A2-A717-4A1C-BF5C-F4A9E06E1260}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".github", ".github", "{3827A9BD-6D28-4A12-B1C0-32A9BD246EA6}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{E5028523-6E46-4A86-AAB9-BF4B1FA5D41D}"
ProjectSection(SolutionItems) = preProject
.github\workflows\ci.yml = .github\workflows\ci.yml
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -53,6 +60,7 @@ Global
{57E0ED0E-0F45-48AB-A73D-6A92B7C32095} = {037440DE-440B-4129-9F7A-09B42D00397E}
{3C2D8E01-5580-426A-BDD9-EC59CD98E618} = {7B927378-9F16-4F6F-B3F6-156395136646}
{A34235A2-A717-4A1C-BF5C-F4A9E06E1260} = {196B1544-C617-4D7C-96D1-628713BDD52A}
{E5028523-6E46-4A86-AAB9-BF4B1FA5D41D} = {3827A9BD-6D28-4A12-B1C0-32A9BD246EA6}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {EA0197B4-FCA8-4DF2-BF34-274FA41333D1}
Expand Down
13 changes: 11 additions & 2 deletions src/Serilog.Sinks.File/FileLoggerConfigurationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -549,17 +549,26 @@ static LoggerConfiguration ConfigureFile(
}
catch (Exception ex)
{
SelfLog.WriteLine("Unable to open file sink for {0}: {1}", path, ex);
// No logging failure listener can be configured here; in future we might allow for a static
// default listener, but in the meantime this improves `SelfLog` usefulness and consistency.
SelfLog.FailureListener.OnLoggingFailed(
typeof(FileLoggerConfigurationExtensions),
LoggingFailureKind.Final,
$"unable to open file sink for {path}",
events: null,
ex);

if (propagateExceptions)
throw;

return addSink(new NullSink(), LevelAlias.Maximum, null);
return addSink(new FailedSink(), restrictedToMinimumLevel, levelSwitch);
}

if (flushToDiskInterval.HasValue)
{
#pragma warning disable 618
// `LoggerSinkConfiguration.Wrap()` is not used here because the target sink is expected
// to support `ILogEventSink`.
sink = new PeriodicFlushToDiskSink(sink, flushToDiskInterval.Value);
#pragma warning restore 618
}
Expand Down
19 changes: 7 additions & 12 deletions src/Serilog.Sinks.File/Serilog.Sinks.File.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,22 @@

<PropertyGroup>
<Description>Write Serilog events to text files in plain or JSON format.</Description>
<VersionPrefix>6.0.1</VersionPrefix>
<Authors>Serilog Contributors</Authors>
<!-- .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>
<TargetFrameworks>$(TargetFrameworks);net9.0;net8.0;net6.0;netstandard2.0</TargetFrameworks>
<PackageTags>serilog;file</PackageTags>
<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>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<IncludeSymbols>True</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<PackageIcon>serilog-sink-nuget.png</PackageIcon>
<PackageReadmeFile>README.md</PackageReadmeFile>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Serilog" Version="4.0.0" />
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Nullable" Version="1.3.1" PrivateAssets="All" />
</ItemGroup>

Expand All @@ -46,6 +37,10 @@
<DefineConstants>$(DefineConstants);ENUMERABLE_MAXBY</DefineConstants>
</PropertyGroup>

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

<ItemGroup>
<None Include="..\..\assets\serilog-sink-nuget.png" Pack="true" Visible="false" PackagePath="/" />
<None Include="..\..\README.md" Pack="true" Visible="false" PackagePath="/" />
Expand Down
34 changes: 34 additions & 0 deletions src/Serilog.Sinks.File/Sinks/File/FailedSink.cs
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do like the concept of having every log still appearing somewhere if everything went wrong. Thanks!

Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright © 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.Debugging;
using Serilog.Events;

namespace Serilog.Sinks.File;

sealed class FailedSink : ILogEventSink, ISetLoggingFailureListener
{
ILoggingFailureListener _failureListener = SelfLog.FailureListener;

public void Emit(LogEvent logEvent)
{
_failureListener.OnLoggingFailed(this, LoggingFailureKind.Final, "the sink could not be initialized", [logEvent], exception: null);
}

public void SetFailureListener(ILoggingFailureListener failureListener)
{
_failureListener = failureListener ?? throw new ArgumentNullException(nameof(failureListener));
}
}
Loading