Skip to content

Commit d660615

Browse files
committed
Initial version
1 parent 1cb3860 commit d660615

24 files changed

+983
-2
lines changed

.gitattributes

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Auto detect text files and perform LF normalization
2+
3+
* text=auto

Build.ps1

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
echo "build: Build started"
2+
3+
Push-Location $PSScriptRoot
4+
5+
if(Test-Path .\artifacts) {
6+
echo "build: Cleaning .\artifacts"
7+
Remove-Item .\artifacts -Force -Recurse
8+
}
9+
10+
& dotnet restore --no-cache
11+
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];
14+
$suffix = @{ $true = ""; $false = "$($branch.Substring(0, [math]::Min(10,$branch.Length)))-$revision"}[$branch -eq "master" -and $revision -ne "local"]
15+
16+
echo "build: Version suffix is $suffix"
17+
18+
foreach ($src in ls src/*) {
19+
Push-Location $src
20+
21+
echo "build: Packaging project in $src"
22+
23+
if($suffix) {
24+
& dotnet pack -c Release --include-source -o ..\..\artifacts --version-suffix=$suffix
25+
} else {
26+
& dotnet pack -c Release --include-source -o ..\..\artifacts
27+
}
28+
29+
if($LASTEXITCODE -ne 0) { exit 1 }
30+
31+
Pop-Location
32+
}
33+
34+
foreach ($test in ls test/*.PerformanceTests) {
35+
Push-Location $test
36+
37+
echo "build: Building performance test project in $test"
38+
39+
& dotnet build -c Release
40+
if($LASTEXITCODE -ne 0) { exit 2 }
41+
42+
Pop-Location
43+
}
44+
45+
foreach ($test in ls test/*.Tests) {
46+
Push-Location $test
47+
48+
echo "build: Testing project in $test"
49+
50+
& dotnet test -c Release
51+
if($LASTEXITCODE -ne 0) { exit 3 }
52+
53+
Pop-Location
54+
}
55+
56+
Pop-Location

CHANGES.md

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
2.0.0
2+
3+
* Initial version for ASP.NET Core 2.
4+

README.md

+88-2
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,88 @@
1-
# serilog-aspnetcore
2-
Serilog integration for ASP.NET Core 2+
1+
# Serilog.AspNetCore [![Build status](https://ci.appveyor.com/api/projects/status/865nohxfiq1rnby0/branch/master?svg=true)](https://ci.appveyor.com/project/serilog/serilog-framework-logging/history) [![NuGet Version](http://img.shields.io/nuget/v/Serilog.Extensions.Logging.svg?style=flat)](https://www.nuget.org/packages/Serilog.Extensions.Logging/)
2+
3+
4+
Serilog logging for ASP.NET Core. This package routes ASP.NET Core log messages through Serilog, so you can get information about ASP.NET's internal operations logged to the same Serilog sinks as your application events.
5+
6+
### Instructions
7+
8+
**First**, install the _Serilog.AspNetCore_ [NuGet package](https://www.nuget.org/packages/Serilog.AspNetCore) into your app. You will need a way to view the log messages - _Serilog.Sinks.Console_ writes these to the console, and _Serilog.Sinks.Debug_ writes to the Visual Studio output window; there are [many more sinks available](https://www.nuget.org/packages?q=Tags%3A%22serilog%22) on NuGet.
9+
10+
```powershell
11+
Install-Package Serilog.AspNetCore -DependencyVersion Highest
12+
Install-Package Serilog.Sinks.Console
13+
Install-Package Serilog.Sinks.Debug
14+
```
15+
16+
**Next**, in your application's _Program.cs_ file, configure Serilog first:
17+
18+
```csharp
19+
public class Program
20+
{
21+
public static int Main(string[] args)
22+
{
23+
Log.Logger = new LoggerConfiguration()
24+
.MinimumLevel.Debug()
25+
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
26+
.Enrich.FromLogContext()
27+
.WriteTo.Console()
28+
.WriteTo.Debug()
29+
.CreateLogger();
30+
```
31+
32+
Then, add `UseSerilog()` to the web host builder. A `try`/`catch` block will ensure any configuration issues are appropriately logged:
33+
34+
```csharp
35+
try
36+
{
37+
Log.Information("Starting web host");
38+
39+
var host = new WebHostBuilder()
40+
.UseKestrel()
41+
.UseContentRoot(Directory.GetCurrentDirectory())
42+
.UseIISIntegration()
43+
.UseStartup<Startup>()
44+
.UseSerilog() // <-- Add this line
45+
.Build();
46+
47+
host.Run();
48+
49+
return 0;
50+
}
51+
catch (Exception ex)
52+
{
53+
Log.Fatal(ex, "Host terminated unexpectedly");
54+
return 1;
55+
}
56+
finally
57+
{
58+
Log.CloseAndFlush();
59+
}
60+
}
61+
}
62+
```
63+
64+
**Finally**, clean up by removing the remaining configuration for the default logger:
65+
66+
* Remove calls to `AddLogging()`
67+
* Remove the `"Logging"` section from _appsettings.json_ files (this can be replaced with [Serilog configuration](https://github.com/serilog/serilog-settings-configuration) as shown in [this example](), if required)
68+
* Remove `ILoggerFactory` parameters and any `Add*()` calls on the logger factory in _Startup.cs_
69+
* Remove `UseApplicationInsights()` (this can be replaced with the [Serilog AI sink](https://github.com/serilog/serilog-sinks-applicationinsights), if required)
70+
71+
That's it! With the level bumped up a little you will see log output like:
72+
73+
```
74+
[22:14:44.646 DBG] RouteCollection.RouteAsync
75+
Routes:
76+
Microsoft.AspNet.Mvc.Routing.AttributeRoute
77+
{controller=Home}/{action=Index}/{id?}
78+
Handled? True
79+
[22:14:44.647 DBG] RouterMiddleware.Invoke
80+
Handled? True
81+
[22:14:45.706 DBG] /lib/jquery/jquery.js not modified
82+
[22:14:45.706 DBG] /css/site.css not modified
83+
[22:14:45.741 DBG] Handled. Status code: 304 File: /css/site.css
84+
```
85+
86+
### Using the package
87+
88+
With _Serilog.AspNetCore_ installed and configured, you can write log messages directly through Serilog or any `ILogger` interface injected by ASP.NET. All loggers will use the same underlying implementation, levels, and destinations.

appveyor.yml

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
version: '{build}'
2+
skip_tags: true
3+
image: Visual Studio 2017 Preview
4+
configuration: Release
5+
install:
6+
- ps: mkdir -Force ".\build\" | Out-Null
7+
#- ps: Invoke-WebRequest "https://raw.githubusercontent.com/dotnet/cli/release/2.0.0/scripts/obtain/dotnet-install.ps1" -OutFile ".\build\installcli.ps1"
8+
#- ps: $env:DOTNET_INSTALL_DIR = "$pwd\.dotnetcli"
9+
#- ps: '& .\build\installcli.ps1 -InstallDir "$env:DOTNET_INSTALL_DIR" -NoPath -Version 2.0.0-preview2-006497'
10+
#- ps: $env:Path = "$env:DOTNET_INSTALL_DIR;$env:Path"
11+
build_script:
12+
- ps: ./Build.ps1
13+
test: off
14+
artifacts:
15+
- path: artifacts/Serilog.*.nupkg
16+
deploy:
17+
- provider: NuGet
18+
api_key:
19+
secure: nvZ/z+pMS91b3kG4DgfES5AcmwwGoBYQxr9kp4XiJHj25SAlgdIxFx++1N0lFH2x
20+
skip_symbols: true
21+
on:
22+
branch: /^(master|dev)$/
23+
- provider: GitHub
24+
auth_token:
25+
secure: p4LpVhBKxGS5WqucHxFQ5c7C8cP74kbNB0Z8k9Oxx/PMaDQ1+ibmoexNqVU5ZlmX
26+
artifact: /Serilog.*\.nupkg/
27+
tag: v$(appveyor_build_version)
28+
on:
29+
branch: master

assets/Serilog.snk

596 Bytes
Binary file not shown.

build.sh

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#!/bin/bash
2+
dotnet --info
3+
dotnet restore
4+
5+
for path in src/**/*.csproj; do
6+
dotnet build -f netstandard2.0 -c Release ${path}
7+
done
8+
9+
for path in test/*.Tests/*.csproj; do
10+
dotnet test -f netcoreapp2.0 -c Release ${path}
11+
done

global.json

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"sdk": {
3+
"version": "2.0.0"
4+
}
5+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
using System.Collections.Generic;
2+
using Microsoft.AspNetCore.Mvc;
3+
using Microsoft.Extensions.Logging;
4+
5+
namespace SimpleWebSample.Controllers
6+
{
7+
[Route("api/[controller]")]
8+
public class ScopesController : Controller
9+
{
10+
ILogger<ScopesController> _logger;
11+
12+
public ScopesController(ILogger<ScopesController> logger)
13+
{
14+
_logger = logger;
15+
}
16+
17+
// GET api/scopes
18+
[HttpGet]
19+
public IEnumerable<string> Get()
20+
{
21+
_logger.LogInformation("Before");
22+
23+
using (_logger.BeginScope("Some name"))
24+
using (_logger.BeginScope(42))
25+
using (_logger.BeginScope("Formatted {WithValue}", 12345))
26+
using (_logger.BeginScope(new Dictionary<string, object> { ["ViaDictionary"] = 100 }))
27+
{
28+
_logger.LogInformation("Hello from the Index!");
29+
_logger.LogDebug("Hello is done");
30+
}
31+
32+
_logger.LogInformation("After");
33+
34+
return new string[] { "value1", "value2" };
35+
}
36+
}
37+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
using System.Collections.Generic;
2+
using Microsoft.AspNetCore.Mvc;
3+
using Serilog;
4+
5+
namespace SimpleWebSample.Controllers
6+
{
7+
[Route("api/[controller]")]
8+
public class ValuesController : Controller
9+
{
10+
// GET api/values
11+
[HttpGet]
12+
public IEnumerable<string> Get()
13+
{
14+
// Directly through Serilog
15+
Log.Information("This is a handler for {Path}", Request.Path);
16+
return new string[] { "value1", "value2" };
17+
}
18+
}
19+
}

samples/SimpleWebSample/Program.cs

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
using System;
2+
using System.IO;
3+
using Microsoft.AspNetCore.Hosting;
4+
using Microsoft.Extensions.Configuration;
5+
using Serilog;
6+
7+
namespace SimpleWebSample
8+
{
9+
public class Program
10+
{
11+
public static int Main(string[] args)
12+
{
13+
var configuration = new ConfigurationBuilder()
14+
.SetBasePath(Directory.GetCurrentDirectory())
15+
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
16+
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true)
17+
.Build();
18+
19+
Log.Logger = new LoggerConfiguration()
20+
.ReadFrom.Configuration(configuration)
21+
.Enrich.FromLogContext()
22+
.WriteTo.Console()
23+
.CreateLogger();
24+
25+
try
26+
{
27+
Log.Information("Getting the motors running...");
28+
29+
var host = new WebHostBuilder()
30+
.UseKestrel()
31+
.UseContentRoot(Directory.GetCurrentDirectory())
32+
.UseIISIntegration()
33+
.UseStartup<Startup>()
34+
.UseConfiguration(configuration)
35+
.UseSerilog()
36+
.Build();
37+
38+
host.Run();
39+
40+
return 0;
41+
}
42+
catch (Exception ex)
43+
{
44+
Log.Fatal(ex, "Host terminated unexpectedly");
45+
return 1;
46+
}
47+
finally
48+
{
49+
Log.CloseAndFlush();
50+
}
51+
}
52+
}
53+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
<PropertyGroup>
3+
<TargetFramework>netcoreapp2.0</TargetFramework>
4+
</PropertyGroup>
5+
6+
<ItemGroup>
7+
<ProjectReference Include="..\..\src\Serilog.AspNetCore\Serilog.AspNetCore.csproj" />
8+
</ItemGroup>
9+
10+
<ItemGroup>
11+
<Folder Include="wwwroot\" />
12+
</ItemGroup>
13+
14+
<ItemGroup>
15+
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
16+
<PackageReference Include="Serilog.Sinks.Console" Version="3.0.1" />
17+
<PackageReference Include="Serilog.Settings.Configuration" Version="2.4.0" />
18+
</ItemGroup>
19+
20+
</Project>

samples/SimpleWebSample/Startup.cs

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
using Microsoft.AspNetCore.Builder;
2+
using Microsoft.AspNetCore.Hosting;
3+
using Microsoft.AspNetCore.Http;
4+
using Microsoft.Extensions.Configuration;
5+
using Microsoft.Extensions.DependencyInjection;
6+
7+
namespace SimpleWebSample
8+
{
9+
public class Startup
10+
{
11+
public Startup(IConfiguration configuration)
12+
{
13+
Configuration = configuration;
14+
}
15+
16+
public IConfiguration Configuration { get; }
17+
18+
// This method gets called by the runtime. Use this method to add services to the container.
19+
public void ConfigureServices(IServiceCollection services)
20+
{
21+
services.AddMvc();
22+
}
23+
24+
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
25+
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
26+
{
27+
if (env.IsDevelopment())
28+
{
29+
app.UseDeveloperExceptionPage();
30+
}
31+
32+
app.UseMvc();
33+
34+
app.Run(async (context) =>
35+
{
36+
await context.Response.WriteAsync("Hello World!");
37+
});
38+
}
39+
}
40+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"Serilog": {
3+
"MinimumLevel": {
4+
"Default": "Debug"
5+
}
6+
}
7+
}
+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"Serilog": {
3+
"MinimumLevel": {
4+
"Default": "Debug",
5+
"Override": {
6+
"Microsoft": "Warning",
7+
"System": "Warning"
8+
}
9+
}
10+
}
11+
}

0 commit comments

Comments
 (0)