Skip to content

Commit be6b75c

Browse files
committed
Update the example projects to .NET Core 3.0 conventions
2 parents 4871096 + 16d1ca9 commit be6b75c

File tree

7 files changed

+54
-83
lines changed

7 files changed

+54
-83
lines changed

README.md

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,10 @@ With _Serilog.AspNetCore_ installed and configured, you can write log messages d
66

77
### Instructions
88

9-
**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; there are [many more sinks available](https://www.nuget.org/packages?q=Tags%3A%22serilog%22) on NuGet.
9+
**First**, install the _Serilog.AspNetCore_ [NuGet package](https://www.nuget.org/packages/Serilog.AspNetCore) into your app.
1010

1111
```shell
1212
dotnet add package Serilog.AspNetCore
13-
dotnet add package Serilog.Sinks.Console
1413
```
1514

1615
**Next**, in your application's _Program.cs_ file, configure Serilog first. A `try`/`catch` block will ensure any configuration issues are appropriately logged:
@@ -79,9 +78,9 @@ That's it! With the level bumped up a little you will see log output resembling:
7978
[22:14:45.741 DBG] Handled. Status code: 304 File: /css/site.css
8079
```
8180

82-
Tip: to see Serilog output in the Visual Studio output window when running under IIS, select _ASP.NET Core Web Server_ from the _Show output from_ drop-down list.
81+
**Tip:** to see Serilog output in the Visual Studio output window when running under IIS, either select _ASP.NET Core Web Server_ from the _Show output from_ drop-down list, or replace `WriteTo.Console()` in the logger configuration with `WriteTo.Debug()`.
8382

84-
A more complete example, showing _appsettings.json_ configuration, can be found in [the sample project here](https://github.com/serilog/serilog-aspnetcore/tree/dev/samples/EarlyInitializationSample).
83+
A more complete example, showing `appsettings.json` configuration, can be found in [the sample project here](https://github.com/serilog/serilog-aspnetcore/tree/dev/samples/EarlyInitializationSample).
8584

8685
### Request logging <sup>`3.0.0-*`</sup>
8786

@@ -162,17 +161,16 @@ This pattern has the advantage of reducing the number of log events that need to
162161

163162
### Inline initialization
164163

165-
You can alternatively configure Serilog inline, in `BulidWebHost()`, using a delegate as shown below:
164+
You can alternatively configure Serilog inline, in `BuildWebHost()`, using a delegate as shown below:
166165

167166
```csharp
168-
// dotnet add package Serilog.Settings.Configuration
169167
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
170168
.ReadFrom.Configuration(hostingContext.Configuration)
171169
.Enrich.FromLogContext()
172170
.WriteTo.Console())
173171
```
174172

175-
This has the advantage of making the `hostingContext`'s `Configuration` object available for configuration of the logger, but at the expense of recording `Exception`s raised earlier in program startup.
173+
This has the advantage of making the `hostingContext`'s `Configuration` object available for [configuration of the logger](https://github.com/serilog/serilog-settings-configuration), but at the expense of losing `Exception`s raised earlier in program startup.
176174

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

@@ -217,15 +215,19 @@ If [inline initialization](#inline-initialization) is used, providers can be ena
217215
writeToProviders: true)
218216
```
219217

220-
### Writing to the Azure Diagnostics Log Stream
218+
### JSON output
219+
220+
The `Console()`, `Debug()`, and `File()` sinks all support JSON-formatted output natively, via the included _Serilog.Formatting.Compact_ package.
221221

222-
The Azure Diagnostic Log Stream ships events from any files in the `D:\home\LogFiles\` folder. To enable this for your app, first install the _Serilog.Sinks.File_ package:
222+
To write newline-delimited JSON, pass a `CompactJsonFormatter` or `RenderedCompactJsonFormatter` to the sink configuration method:
223223

224-
```powershell
225-
Install-Package Serilog.Sinks.File
224+
```csharp
225+
.WriteTo.Console(new RenderedCompactJsonFormatter())
226226
```
227227

228-
Then add a file sink to your `LoggerConfiguration`, taking care to set the `shared` and `flushToDiskInterval` parameters:
228+
### Writing to the Azure Diagnostics Log Stream
229+
230+
The Azure Diagnostic Log Stream ships events from any files in the `D:\home\LogFiles\` folder. To enable this for your app, add a file sink to your `LoggerConfiguration`, taking care to set the `shared` and `flushToDiskInterval` parameters:
229231

230232
```csharp
231233
public static int Main(string[] args)

samples/EarlyInitializationSample/Program.cs

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
using System;
22
using System.IO;
3-
using Microsoft.AspNetCore;
43
using Microsoft.AspNetCore.Hosting;
54
using Microsoft.Extensions.Configuration;
65
using Microsoft.Extensions.Hosting;
@@ -22,10 +21,9 @@ public static int Main(string[] args)
2221
Log.Logger = new LoggerConfiguration()
2322
.ReadFrom.Configuration(Configuration)
2423
.Enrich.FromLogContext()
24+
.WriteTo.Debug()
2525
.WriteTo.Console(
26-
// {Properties:j} added:
27-
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} " +
28-
"{Properties:j}{NewLine}{Exception}")
26+
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}")
2927
.CreateLogger();
3028

3129
try
@@ -47,18 +45,12 @@ public static int Main(string[] args)
4745
}
4846
}
4947

50-
public static IWebHost BuildWebHost(string[] args) =>
51-
WebHost.CreateDefaultBuilder(args)
52-
.UseStartup<Startup>()
53-
.Build();
54-
5548
public static IHostBuilder CreateHostBuilder(string[] args) =>
5649
Host.CreateDefaultBuilder(args)
5750
.ConfigureWebHostDefaults(webBuilder =>
5851
{
5952
webBuilder.UseStartup<Startup>();
6053
})
61-
.UseConfiguration(Configuration)
6254
.UseSerilog();
6355
}
6456
}
Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
using Microsoft.AspNetCore.Builder;
22
using Microsoft.AspNetCore.Hosting;
3-
using Microsoft.Extensions.Configuration;
43
using Microsoft.Extensions.DependencyInjection;
54
using Microsoft.Extensions.Hosting;
65
using Serilog;
@@ -9,15 +8,9 @@ namespace EarlyInitializationSample
98
{
109
public class Startup
1110
{
12-
public Startup(IConfiguration configuration)
13-
{
14-
Configuration = configuration;
15-
}
16-
17-
public IConfiguration Configuration { get; }
18-
1911
public void ConfigureServices(IServiceCollection services)
2012
{
13+
services.AddControllersWithViews();
2114
}
2215

2316
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
@@ -29,18 +22,24 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
2922
else
3023
{
3124
app.UseExceptionHandler("/Home/Error");
25+
app.UseHsts();
3226
}
3327

28+
app.UseStaticFiles();
29+
3430
// Write streamlined request completion events, instead of the more verbose ones from the framework.
3531
// To use the default framework request logging instead, remove this line and set the "Microsoft"
3632
// level in appsettings.json to "Information".
3733
app.UseSerilogRequestLogging();
3834

39-
app.UseStaticFiles();
40-
4135
app.UseRouting();
4236

43-
app.UseEndpoints(endpoints => endpoints.MapControllers());
37+
app.UseEndpoints(endpoints =>
38+
{
39+
endpoints.MapControllerRoute(
40+
name: "default",
41+
pattern: "{controller=Home}/{action=Index}/{id?}");
42+
});
4443
}
4544
}
4645
}
Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,11 @@
11
<Project Sdk="Microsoft.NET.Sdk.Web">
22

33
<PropertyGroup>
4-
<TargetFramework>netcoreapp2.2</TargetFramework>
5-
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
4+
<TargetFramework>netcoreapp3.0</TargetFramework>
65
</PropertyGroup>
76

87
<ItemGroup>
98
<ProjectReference Include="..\..\src\Serilog.AspNetCore\Serilog.AspNetCore.csproj" />
109
</ItemGroup>
1110

12-
<ItemGroup>
13-
<PackageReference Include="Microsoft.AspNetCore.App" />
14-
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
15-
<PackageReference Include="Serilog.Sinks.Console" Version="3.0.1" />
16-
<PackageReference Include="Serilog.Settings.Configuration" Version="2.4.0" />
17-
</ItemGroup>
18-
1911
</Project>
Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
using Microsoft.AspNetCore;
2-
using Microsoft.AspNetCore.Hosting;
1+
using Microsoft.AspNetCore.Hosting;
2+
using Microsoft.Extensions.Hosting;
33
using Serilog;
44

55
namespace InlineInitializationSample
@@ -8,18 +8,20 @@ public class Program
88
{
99
public static void Main(string[] args)
1010
{
11-
CreateWebHostBuilder(args).Build().Run();
11+
CreateHostBuilder(args).Build().Run();
1212
}
1313

14-
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
15-
WebHost.CreateDefaultBuilder(args)
16-
.UseStartup<Startup>()
14+
public static IHostBuilder CreateHostBuilder(string[] args) =>
15+
Host.CreateDefaultBuilder(args)
16+
.ConfigureWebHostDefaults(webBuilder =>
17+
{
18+
webBuilder.UseStartup<Startup>();
19+
})
1720
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
1821
.ReadFrom.Configuration(hostingContext.Configuration)
1922
.Enrich.FromLogContext()
23+
.WriteTo.Debug()
2024
.WriteTo.Console(
21-
// {Properties:j} added:
22-
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} " +
23-
"{Properties:j}{NewLine}{Exception}"));
25+
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}"));
2426
}
2527
}

samples/InlineInitializationSample/Startup.cs

Lines changed: 11 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,19 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.Linq;
4-
using System.Threading.Tasks;
5-
using Microsoft.AspNetCore.Builder;
1+
using Microsoft.AspNetCore.Builder;
62
using Microsoft.AspNetCore.Hosting;
7-
using Microsoft.AspNetCore.Http;
8-
using Microsoft.AspNetCore.Mvc;
9-
using Microsoft.Extensions.Configuration;
103
using Microsoft.Extensions.DependencyInjection;
4+
using Microsoft.Extensions.Hosting;
115
using Serilog;
126

137
namespace InlineInitializationSample
148
{
159
public class Startup
1610
{
17-
public Startup(IConfiguration configuration)
18-
{
19-
Configuration = configuration;
20-
}
21-
22-
public IConfiguration Configuration { get; }
23-
24-
// This method gets called by the runtime. Use this method to add services to the container.
2511
public void ConfigureServices(IServiceCollection services)
2612
{
27-
services.Configure<CookiePolicyOptions>(options =>
28-
{
29-
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
30-
options.CheckConsentNeeded = context => true;
31-
options.MinimumSameSitePolicy = SameSiteMode.None;
32-
});
33-
34-
35-
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
13+
services.AddControllersWithViews();
3614
}
3715

38-
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
39-
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
16+
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
4017
{
4118
if (env.IsDevelopment())
4219
{
@@ -45,21 +22,23 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
4522
else
4623
{
4724
app.UseExceptionHandler("/Home/Error");
25+
app.UseHsts();
4826
}
4927

28+
app.UseStaticFiles();
29+
5030
// Write streamlined request completion events, instead of the more verbose ones from the framework.
5131
// To use the default framework request logging instead, remove this line and set the "Microsoft"
5232
// level in appsettings.json to "Information".
5333
app.UseSerilogRequestLogging();
5434

55-
app.UseStaticFiles();
56-
app.UseCookiePolicy();
35+
app.UseRouting();
5736

58-
app.UseMvc(routes =>
37+
app.UseEndpoints(endpoints =>
5938
{
60-
routes.MapRoute(
39+
endpoints.MapControllerRoute(
6140
name: "default",
62-
template: "{controller=Home}/{action=Index}/{id?}");
41+
pattern: "{controller=Home}/{action=Index}/{id?}");
6342
});
6443
}
6544
}

src/Serilog.AspNetCore/Serilog.AspNetCore.csproj

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@
2626
<PackageReference Include="Serilog" Version="2.8.0" />
2727
<PackageReference Include="Serilog.Extensions.Hosting" Version="3.0.0-dev-00019" />
2828
<PackageReference Include="Serilog.Extensions.Logging" Version="3.0.0-*" />
29+
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
30+
<PackageReference Include="Serilog.Sinks.File" Version="4.0.0" />
31+
<PackageReference Include="Serilog.Sinks.Debug" Version="1.0.1" />
32+
<PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />
33+
<PackageReference Include="Serilog.Formatting.Compact" Version="1.0.0" />
2934
<PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="2.0.0" />
3035
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.0.0" />
3136
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.0.0" />

0 commit comments

Comments
 (0)