Skip to content

Commit d91658e

Browse files
committed
Add an overload to UseSerilog() - Useful for configuring Serilog during the construction of IWebHost.
1 parent b8a3708 commit d91658e

File tree

9 files changed

+224
-1
lines changed

9 files changed

+224
-1
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Copyright 2017 Serilog Contributors
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
using System.Collections.Generic;
16+
using Microsoft.AspNetCore.Mvc;
17+
using Microsoft.Extensions.Configuration;
18+
using Microsoft.Extensions.Logging;
19+
20+
namespace SimpleWebSampleV2.Controllers
21+
{
22+
// This controller lists configuration settings and their value.
23+
// Please, do try to update the appsettings.json while the application is running. 😉
24+
25+
[Route("api/[controller]")]
26+
public class ConfigurationController : Controller
27+
{
28+
public ConfigurationController(IConfiguration configuration, ILogger<ConfigurationController> logger)
29+
{
30+
Configuration = configuration;
31+
Logger = logger;
32+
}
33+
34+
public IConfiguration Configuration { get; }
35+
public ILogger Logger { get; }
36+
37+
[HttpGet]
38+
public IEnumerable<KeyValuePair<string, string>> Get()
39+
{
40+
Logger.LogInformation("Listing all configuration settings…");
41+
42+
return Configuration.AsEnumerable();
43+
}
44+
45+
[HttpGet("{key}")]
46+
public string Get(string key)
47+
{
48+
Logger.LogInformation("The configuration key {ConfigurationKey} was requested.", key);
49+
string value = Configuration[key];
50+
Logger.LogInformation("The configuration key {ConfigurationKey} has value {ConfigurationValue}.", key, value);
51+
52+
return value;
53+
}
54+
}
55+
}

samples/SimpleWebSampleV2/Program.cs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
using System;
2+
using System.IO;
3+
using Microsoft.AspNetCore.Hosting;
4+
using Microsoft.Extensions.Configuration;
5+
using Serilog;
6+
7+
namespace SimpleWebSampleV2
8+
{
9+
public class Program
10+
{
11+
public static void Main(string[] args)
12+
{
13+
var host = new WebHostBuilder()
14+
.UseKestrel()
15+
.UseContentRoot(Directory.GetCurrentDirectory())
16+
.ConfigureAppConfiguration
17+
(
18+
// Load the application configuration over the web host configuration.
19+
(hostingContext, configurationBuilder) =>
20+
{
21+
configurationBuilder
22+
.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
23+
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
24+
.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true)
25+
.AddEnvironmentVariables();
26+
}
27+
)
28+
.UseSerilog
29+
(
30+
// Configure Serilog to be used as the logger for the whole application.
31+
(hostingContext, loggerConfiguration) => loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration)
32+
.Enrich.FromLogContext()
33+
.WriteTo.Console()
34+
)
35+
.UseIISIntegration()
36+
.UseStartup<Startup>()
37+
.Build();
38+
39+
host.Run();
40+
}
41+
}
42+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
{
2+
"iisSettings": {
3+
"windowsAuthentication": false,
4+
"anonymousAuthentication": true,
5+
"iisExpress": {
6+
"applicationUrl": "http://localhost:52009/",
7+
"sslPort": 0
8+
}
9+
},
10+
"profiles": {
11+
"IIS Express": {
12+
"commandName": "IISExpress",
13+
"launchBrowser": true,
14+
"launchUrl": "api/configuration/Greeting",
15+
"environmentVariables": {
16+
"ASPNETCORE_ENVIRONMENT": "Development"
17+
}
18+
},
19+
"SimpleWebSample": {
20+
"commandName": "Project",
21+
"launchBrowser": true,
22+
"launchUrl": "api/configuration/Greeting",
23+
"environmentVariables": {
24+
"ASPNETCORE_ENVIRONMENT": "Development"
25+
},
26+
"applicationUrl": "http://localhost:52010/"
27+
}
28+
}
29+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
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+
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
12+
<PackageReference Include="Serilog.Sinks.Console" Version="3.0.1" />
13+
<PackageReference Include="Serilog.Settings.Configuration" Version="2.4.0" />
14+
</ItemGroup>
15+
16+
</Project>

samples/SimpleWebSampleV2/Startup.cs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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 SimpleWebSampleV2
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+
}
35+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"Serilog": {
3+
"MinimumLevel": {
4+
"Default": "Debug"
5+
}
6+
}
7+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"Serilog": {
3+
"MinimumLevel": {
4+
"Default": "Debug",
5+
"Override": {
6+
"Microsoft": "Warning",
7+
"System": "Warning"
8+
}
9+
}
10+
},
11+
"Greeting": "Hello World !"
12+
}

serilog-aspnetcore.sln

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11

22
Microsoft Visual Studio Solution File, Format Version 12.00
33
# Visual Studio 15
4-
VisualStudioVersion = 15.0.26730.10
4+
VisualStudioVersion = 15.0.26730.12
55
MinimumVisualStudioVersion = 10.0.40219.1
66
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{A1893BD1-333D-4DFE-A0F0-DDBB2FE526E0}"
77
EndProject
@@ -24,6 +24,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.AspNetCore", "src\S
2424
EndProject
2525
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.AspNetCore.Tests", "test\Serilog.AspNetCore.Tests\Serilog.AspNetCore.Tests.csproj", "{AD51759B-CD58-473F-9620-0B0E56A123A1}"
2626
EndProject
27+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimpleWebSampleV2", "samples\SimpleWebSampleV2\SimpleWebSampleV2.csproj", "{2711EC78-7F7D-440B-A8AB-BA3D32227667}"
28+
EndProject
2729
Global
2830
GlobalSection(SolutionConfigurationPlatforms) = preSolution
2931
Debug|Any CPU = Debug|Any CPU
@@ -42,6 +44,10 @@ Global
4244
{AD51759B-CD58-473F-9620-0B0E56A123A1}.Debug|Any CPU.Build.0 = Debug|Any CPU
4345
{AD51759B-CD58-473F-9620-0B0E56A123A1}.Release|Any CPU.ActiveCfg = Release|Any CPU
4446
{AD51759B-CD58-473F-9620-0B0E56A123A1}.Release|Any CPU.Build.0 = Release|Any CPU
47+
{2711EC78-7F7D-440B-A8AB-BA3D32227667}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
48+
{2711EC78-7F7D-440B-A8AB-BA3D32227667}.Debug|Any CPU.Build.0 = Debug|Any CPU
49+
{2711EC78-7F7D-440B-A8AB-BA3D32227667}.Release|Any CPU.ActiveCfg = Release|Any CPU
50+
{2711EC78-7F7D-440B-A8AB-BA3D32227667}.Release|Any CPU.Build.0 = Release|Any CPU
4551
EndGlobalSection
4652
GlobalSection(SolutionProperties) = preSolution
4753
HideSolutionNode = FALSE
@@ -50,6 +56,7 @@ Global
5056
{69F9A0ED-7910-4F33-8919-28BB05376FBC} = {F2407211-6043-439C-8E06-3641634332E7}
5157
{0549D23F-986B-4FB2-BACE-16FD7A7BC9EF} = {A1893BD1-333D-4DFE-A0F0-DDBB2FE526E0}
5258
{AD51759B-CD58-473F-9620-0B0E56A123A1} = {E30F638E-BBBE-4AD1-93CE-48CC69CFEFE1}
59+
{2711EC78-7F7D-440B-A8AB-BA3D32227667} = {F2407211-6043-439C-8E06-3641634332E7}
5360
EndGlobalSection
5461
GlobalSection(ExtensibilityGlobals) = postSolution
5562
SolutionGuid = {811E61C5-3871-4633-AFAE-B35B619C8A10}

src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,5 +41,25 @@ public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, Serilog.I
4141
collection.AddSingleton<ILoggerFactory>(new SerilogLoggerFactory(logger, dispose)));
4242
return builder;
4343
}
44+
45+
/// <summary>Sets Serilog as the logging provider.</summary>
46+
/// <param name="builder">The web host builder to configure.</param>
47+
/// <param name="configureSerilog">The delegate for configuring the <see cref="LoggerConfiguration" /> that will be used to construct a <see cref="Logger" />.</param>
48+
/// <returns>The web host builder.</returns>
49+
public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, Action<WebHostBuilderContext, LoggerConfiguration> configureSerilog)
50+
{
51+
if (builder == null) throw new ArgumentNullException(nameof(builder));
52+
if (configureSerilog == null) throw new ArgumentNullException(nameof(configureSerilog));
53+
builder.ConfigureServices
54+
(
55+
(context, collection) =>
56+
{
57+
var loggerConfiguration = new LoggerConfiguration();
58+
configureSerilog(context, loggerConfiguration);
59+
collection.AddSingleton<ILoggerFactory>(new SerilogLoggerFactory(loggerConfiguration.CreateLogger(), true));
60+
}
61+
);
62+
return builder;
63+
}
4464
}
4565
}

0 commit comments

Comments
 (0)