Skip to content

Commit fb0d872

Browse files
committed
README, new samples based on the default netcoreapp2.2 template
1 parent 945289f commit fb0d872

File tree

108 files changed

+79289
-129
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

108 files changed

+79289
-129
lines changed

README.md

+48-9
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ public class Program
4949
```csharp
5050
public static IWebHost BuildWebHost(string[] args) =>
5151
WebHost.CreateDefaultBuilder(args)
52-
.UseStartup<Startup>()
52+
.UseStartup<Startup>()
5353
.UseSerilog() // <-- Add this line
5454
.Build();
5555
}
@@ -58,11 +58,11 @@ public class Program
5858
**Finally**, clean up by removing the remaining configuration for the default logger:
5959

6060
* Remove calls to `AddLogging()`
61-
* 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](https://github.com/serilog/serilog-aspnetcore/blob/dev/samples/SimpleWebSample/Program.cs), if required)
61+
* 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 [the _EarlyInitializationSample_ project](https://github.com/serilog/serilog-aspnetcore/blob/dev/samples/EarlyInitializationSample/Program.cs), if required)
6262
* Remove `ILoggerFactory` parameters and any `Add*()` calls on the logger factory in _Startup.cs_
6363
* Remove `UseApplicationInsights()` (this can be replaced with the [Serilog AI sink](https://github.com/serilog/serilog-sinks-applicationinsights), if required)
6464

65-
That's it! With the level bumped up a little you will see log output like:
65+
That's it! With the level bumped up a little you will see log output resembling:
6666

6767
```
6868
[22:14:44.646 DBG] RouteCollection.RouteAsync
@@ -79,7 +79,7 @@ That's it! With the level bumped up a little you will see log output like:
7979

8080
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.
8181

82-
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/SimpleWebSample).
82+
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).
8383

8484
### Using the package
8585

@@ -89,21 +89,60 @@ With _Serilog.AspNetCore_ installed and configured, you can write log messages d
8989

9090
### Inline initialization
9191

92-
You can alternatively configure Serilog using a delegate as shown below:
92+
You can alternatively configure Serilog inline, in `BulidWebHost()`, using a delegate as shown below:
9393

9494
```csharp
9595
// dotnet add package Serilog.Settings.Configuration
9696
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
97-
.ReadFrom.Configuration(hostingContext.Configuration)
98-
.Enrich.FromLogContext()
99-
.WriteTo.Console())
97+
.ReadFrom.Configuration(hostingContext.Configuration)
98+
.Enrich.FromLogContext()
99+
.WriteTo.Console())
100100
```
101101

102102
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.
103103

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

106-
Note: Configuring Serilog via the `hostingContext`'s `Configuration` object requires that you've installed the _Serilog.Settings.Configuration_ [NuGet package](https://www.nuget.org/packages/Serilog.Settings.Configuration).
106+
A complete example, showing this approach, can be found in [the _InlineIntializationSample_ project](https://github.com/serilog/serilog-aspnetcore/tree/dev/samples/InlineInitializationSample).
107+
108+
### Enabling `Microsoft.Extensions.Logging.ILoggerProvider`s
109+
110+
Serilog sends events to outputs called _sinks_, that implement Serilog's `ILogEventSink` interface, and are added to the logging pipeline using `WriteTo`. _Microsoft.Extensions.Logging_ has a similar concept called _providers_, and these implement `ILoggerProvider`. Providers are what the default logging configuration creates under the hood through methods like `AddConsole()`.
111+
112+
By default, Serilog ignores providers, since there are usually equivalent Serilog sinks available, and these work more efficiently with Serilog's pipeline. If provider support is needed, it can be optionally enabled.
113+
114+
**Using the recommended configuration:**
115+
116+
In the recommended configuration (in which startup exceptions are caught and logged), first create a `LoggerProviderCollection` in a static field in _Program.cs_:
117+
118+
```csharp
119+
// using Serilog.Extensions.Logging;
120+
static readonly LoggerProviderCollection Providers = new LoggerProviderCollection();
121+
```
122+
123+
Next, add `WriteTo.Providers()` to the logger configuration:
124+
125+
```csharp
126+
.WriteTo.Providers(Providers)
127+
```
128+
129+
Finally, pass the provider collection into `UseSerilog()`:
130+
131+
```csharp
132+
.UseSerilog(providers: Providers)
133+
```
134+
135+
Providers registered in _Startup.cs_ with `AddLogging()` will then receive events from Serilog.
136+
137+
**Using iniline initialization:**
138+
139+
If [inline initialization](#inline-initialization) is used, providers can be enabled by adding `writeToProviders: true` to the `UseSerilog()` method call:
140+
141+
```csharp
142+
.UseSerilog(
143+
(hostingContext, loggerConfiguration) => /* snip! */,
144+
writeToProviders: true)
145+
```
107146

108147
### Writing to the Azure Diagnostics Log Stream
109148

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
using System;
2+
using System.Diagnostics;
3+
using Microsoft.AspNetCore.Mvc;
4+
using EarlyInitializationSample.Models;
5+
using Microsoft.Extensions.Logging;
6+
7+
namespace EarlyInitializationSample.Controllers
8+
{
9+
public class HomeController : Controller
10+
{
11+
readonly ILogger<HomeController> _logger;
12+
13+
public HomeController(ILogger<HomeController> logger)
14+
{
15+
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
16+
}
17+
18+
public IActionResult Index()
19+
{
20+
_logger.LogInformation("Hello, world!");
21+
return View();
22+
}
23+
24+
public IActionResult Privacy()
25+
{
26+
return View();
27+
}
28+
29+
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
30+
public IActionResult Error()
31+
{
32+
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
33+
}
34+
}
35+
}

samples/SimpleWebSample/SimpleWebSample.csproj renamed to samples/EarlyInitializationSample/EarlyInitializationSample.csproj

+5-6
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,17 @@
11
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
23
<PropertyGroup>
3-
<TargetFramework>netcoreapp2.0</TargetFramework>
4+
<TargetFramework>netcoreapp2.2</TargetFramework>
5+
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
46
</PropertyGroup>
57

68
<ItemGroup>
79
<ProjectReference Include="..\..\src\Serilog.AspNetCore\Serilog.AspNetCore.csproj" />
810
</ItemGroup>
911

1012
<ItemGroup>
11-
<Folder Include="wwwroot\" />
12-
</ItemGroup>
13-
14-
<ItemGroup>
15-
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
13+
<PackageReference Include="Microsoft.AspNetCore.App" />
14+
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
1615
<PackageReference Include="Serilog.Sinks.Console" Version="3.0.1" />
1716
<PackageReference Include="Serilog.Settings.Configuration" Version="2.4.0" />
1817
</ItemGroup>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
namespace EarlyInitializationSample.Models
2+
{
3+
public class ErrorViewModel
4+
{
5+
public string RequestId { get; set; }
6+
7+
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
8+
}
9+
}

samples/SimpleWebSample/Program.cs renamed to samples/EarlyInitializationSample/Program.cs

+6-7
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
using System;
1+
using System;
22
using System.IO;
33
using Microsoft.AspNetCore;
44
using Microsoft.AspNetCore.Hosting;
55
using Microsoft.Extensions.Configuration;
66
using Serilog;
77

8-
namespace SimpleWebSample
8+
namespace EarlyInitializationSample
99
{
1010
public class Program
1111
{
@@ -18,7 +18,6 @@ public class Program
1818

1919
public static int Main(string[] args)
2020
{
21-
2221
Log.Logger = new LoggerConfiguration()
2322
.ReadFrom.Configuration(Configuration)
2423
.Enrich.FromLogContext()
@@ -46,9 +45,9 @@ public static int Main(string[] args)
4645

4746
public static IWebHost BuildWebHost(string[] args) =>
4847
WebHost.CreateDefaultBuilder(args)
49-
.UseStartup<Startup>()
50-
.UseConfiguration(Configuration)
51-
.UseSerilog()
52-
.Build();
48+
.UseStartup<Startup>()
49+
.UseConfiguration(Configuration)
50+
.UseSerilog()
51+
.Build();
5352
}
5453
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Threading.Tasks;
5+
using Microsoft.AspNetCore.Builder;
6+
using Microsoft.AspNetCore.Hosting;
7+
using Microsoft.AspNetCore.Http;
8+
using Microsoft.AspNetCore.Mvc;
9+
using Microsoft.Extensions.Configuration;
10+
using Microsoft.Extensions.DependencyInjection;
11+
12+
namespace EarlyInitializationSample
13+
{
14+
public class Startup
15+
{
16+
public Startup(IConfiguration configuration)
17+
{
18+
Configuration = configuration;
19+
}
20+
21+
public IConfiguration Configuration { get; }
22+
23+
// This method gets called by the runtime. Use this method to add services to the container.
24+
public void ConfigureServices(IServiceCollection services)
25+
{
26+
services.Configure<CookiePolicyOptions>(options =>
27+
{
28+
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
29+
options.CheckConsentNeeded = context => true;
30+
options.MinimumSameSitePolicy = SameSiteMode.None;
31+
});
32+
33+
34+
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
35+
}
36+
37+
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
38+
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
39+
{
40+
if (env.IsDevelopment())
41+
{
42+
app.UseDeveloperExceptionPage();
43+
}
44+
else
45+
{
46+
app.UseExceptionHandler("/Home/Error");
47+
}
48+
49+
app.UseStaticFiles();
50+
app.UseCookiePolicy();
51+
52+
app.UseMvc(routes =>
53+
{
54+
routes.MapRoute(
55+
name: "default",
56+
template: "{controller=Home}/{action=Index}/{id?}");
57+
});
58+
}
59+
}
60+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
@{
2+
ViewData["Title"] = "Home Page";
3+
}
4+
5+
<div class="text-center">
6+
<h1 class="display-4">Welcome</h1>
7+
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
8+
</div>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
@{
2+
ViewData["Title"] = "Privacy Policy";
3+
}
4+
<h1>@ViewData["Title"]</h1>
5+
6+
<p>Use this page to detail your site's privacy policy.</p>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
@model ErrorViewModel
2+
@{
3+
ViewData["Title"] = "Error";
4+
}
5+
6+
<h1 class="text-danger">Error.</h1>
7+
<h2 class="text-danger">An error occurred while processing your request.</h2>
8+
9+
@if (Model.ShowRequestId)
10+
{
11+
<p>
12+
<strong>Request ID:</strong> <code>@Model.RequestId</code>
13+
</p>
14+
}
15+
16+
<h3>Development Mode</h3>
17+
<p>
18+
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
19+
</p>
20+
<p>
21+
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
22+
It can result in displaying sensitive information from exceptions to end users.
23+
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
24+
and restarting the app.
25+
</p>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
@using Microsoft.AspNetCore.Http.Features
2+
3+
@{
4+
var consentFeature = Context.Features.Get<ITrackingConsentFeature>();
5+
var showBanner = !consentFeature?.CanTrack ?? false;
6+
var cookieString = consentFeature?.CreateConsentCookie();
7+
}
8+
9+
@if (showBanner)
10+
{
11+
<div id="cookieConsent" class="alert alert-info alert-dismissible fade show" role="alert">
12+
Use this space to summarize your privacy and cookie use policy. <a asp-area="" asp-controller="Home" asp-action="Privacy">Learn More</a>.
13+
<button type="button" class="accept-policy close" data-dismiss="alert" aria-label="Close" data-cookie-string="@cookieString">
14+
<span aria-hidden="true">Accept</span>
15+
</button>
16+
</div>
17+
<script>
18+
(function () {
19+
var button = document.querySelector("#cookieConsent button[data-cookie-string]");
20+
button.addEventListener("click", function (event) {
21+
document.cookie = button.dataset.cookieString;
22+
}, false);
23+
})();
24+
</script>
25+
}

0 commit comments

Comments
 (0)