Skip to content

Commit

Permalink
Merge branch 'dev' into whitespace
Browse files Browse the repository at this point in the history
  • Loading branch information
nblumhardt authored Nov 27, 2024
2 parents 1ea7606 + bf9b41b commit 0a5bb87
Show file tree
Hide file tree
Showing 33 changed files with 1,371 additions and 887 deletions.
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -286,3 +286,6 @@ __pycache__/
*.odx.cs
*.xsd.cs
/samples/WebApplicationSample/logs/

.DS_Store

93 changes: 58 additions & 35 deletions Build.ps1
Original file line number Diff line number Diff line change
@@ -1,56 +1,79 @@
echo "build: Build started"
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) {
echo "build: Cleaning .\artifacts"
Remove-Item .\artifacts -Force -Recurse
}
& dotnet restore --no-cache

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

Write-Output "build: Package version prefix is $versionPrefix"

$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 ""]

& dotnet restore --no-cache
Write-Output "build: Package version suffix is $suffix"
Write-Output "build: Build version suffix is $buildSuffix"

$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];
$suffix = @{ $true = ""; $false = "$($branch.Substring(0, [math]::Min(10,$branch.Length)))-$revision"}[$branch -eq "main" -and $revision -ne "local"]
& dotnet build -c Release --version-suffix=$buildSuffix /p:ContinuousIntegrationBuild=true
if($LASTEXITCODE -ne 0) { throw "Build failed" }

echo "build: Version suffix is $suffix"
foreach ($src in Get-ChildItem src/*) {
Push-Location $src

foreach ($src in ls src/*) {
Push-Location $src
Write-Output "build: Packaging project in $src"

echo "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" }

if($suffix) {
& dotnet pack -c Release --include-source -o ..\..\artifacts --version-suffix=$suffix
} else {
& dotnet pack -c Release --include-source -o ..\..\artifacts
Pop-Location
}

if($LASTEXITCODE -ne 0) { exit 1 }

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

foreach ($test in ls test/*.PerformanceTests) {
Push-Location $test
Write-Output "build: Testing project in $test"

echo "build: Building performance test project in $test"
& dotnet test -c Release --no-build --no-restore
if($LASTEXITCODE -ne 0) { throw "Testing failed" }

& dotnet build -c Release
if($LASTEXITCODE -ne 0) { exit 2 }
Pop-Location
}

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 ls test/*.Tests) {
Push-Location $test
Write-Output "build: Publishing NuGet packages"

echo "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) { exit 3 }
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
25 changes: 25 additions & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<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>
<!-- 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>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="Microsoft.CSharp" />
</ItemGroup>
</Project>
6 changes: 6 additions & 0 deletions Directory.Version.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<Project>
<PropertyGroup>
<!-- This must match the major and minor components of the referenced Microsoft.Extensions.Hosting package. -->
<VersionPrefix>9.0.0</VersionPrefix>
</PropertyGroup>
</Project>
82 changes: 35 additions & 47 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

Serilog logging for _Microsoft.Extensions.Hosting_. This package routes framework log messages through Serilog, so you can get information about the framework's internal operations written to the same Serilog sinks as your application events.

**ASP.NET Core** applications should consider [using _Serilog.AspNetCore_ instead](https://github.com/serilog/serilog-aspnetcore), which bundles this package and includes other ASP.NET Core-specific features.
**Versioning:** This package tracks the versioning and target framework support of its
[_Microsoft.Extensions.Hosting_](https://nuget.org/packages/Microsoft.Extensions.Hosting) dependency. Most users should choose the version of _Serilog.Extensions.Hosting_ that matches
their application's target framework. I.e. if you're targeting .NET 7.x, choose a 7.x version of _Serilog.Extensions.Hosting_. If
you're targeting .NET 8.x, choose an 8.x _Serilog.Extensions.Hosting_ version, and so on.

### Instructions

Expand All @@ -13,46 +16,37 @@ dotnet add package Serilog.Extensions.Hosting
dotnet add package Serilog.Sinks.Console
```

**Next**, in your application's _Program.cs_ file, configure Serilog first. A `try`/`catch` block will ensure any configuration issues are appropriately logged:
**Next**, in your application's _Program.cs_ file, configure Serilog first. A `try`/`catch` block will ensure any configuration issues are appropriately logged. Call `AddSerilog()` on the host application builder:

```csharp
public class Program
using Serilog;

Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();

try
{
public static int Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();

try
{
Log.Information("Starting host");
BuildHost(args).Run();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
return 1;
}
finally
{
Log.CloseAndFlush();
}
}
```
Log.Information("Starting host");

**Then**, add `UseSerilog()` to the host builder in `BuildHost()`.
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddHostedService<PrintTimeService>();
builder.Services.AddSerilog();

```csharp
public static IHost BuildHost(string[] args) =>
new HostBuilder()
.ConfigureServices(services => services.AddSingleton<IHostedService, PrintTimeService>())
.UseSerilog() // <- Add this line
.Build();
var app = builder.Build();

await app.RunAsync();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
return 1;
}
finally
{
await Log.CloseAndFlushAsync();
}
```

Expand All @@ -71,24 +65,18 @@ A more complete example, showing _appsettings.json_ configuration, can be found

With _Serilog.Extensions.Hosting_ installed and configured, you can write log messages directly through Serilog or any `ILogger` interface injected by .NET. All loggers will use the same underlying implementation, levels, and destinations.

**Tip:** change the minimum level for `Microsoft` to `Warning`

### Inline initialization

You can alternatively configure Serilog using a delegate as shown below:

```csharp
// dotnet add package Serilog.Settings.Configuration
.UseSerilog((hostingContext, services, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext()
.WriteTo.Console())
builder.Services.AddSerilog((services, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(builder.Configuration)
.Enrich.FromLogContext()
.WriteTo.Console())
```

This has the advantage of making the `hostingContext`'s `Configuration` object available for configuration of the logger, but at the expense of ignoring `Exception`s raised earlier in program startup.
This has the advantage of making `builder`'s `Configuration` object available for configuration of the logger, but at the expense of ignoring `Exception`s raised earlier in program startup.

If this method is used, `Log.Logger` is assigned implicitly, and closed when the app is shut down.

### Versioning

This package tracks the versioning and target framework support of its [_Microsoft.Extensions.Hosting_](https://nuget.org/packages/Microsoft.Extensions.Hosting) dependency.
28 changes: 0 additions & 28 deletions appveyor.yml

This file was deleted.

11 changes: 0 additions & 11 deletions build.sh

This file was deleted.

2 changes: 1 addition & 1 deletion global.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"sdk": {
"version": "9.0.100",
"allowPrerelease": false,
"version": "8.0.100",
"rollForward": "latestFeature"
}
}
Loading

0 comments on commit 0a5bb87

Please sign in to comment.