Troubleshoot your ASP.NET Core web app using logging
You’ve created your new ASP.NET Core web app and are happily building your features.
Then something breaks and you’ve no idea what.
How can you find out what’s causing the problem?
If you’ve created your ASP.NET Core web app from scratch (not using any templates or magic but bare-bones style using dotnet new
) then you’ll find you have absolutely no error handling/logging set up. This makes diagnosing errors pretty difficult.
Shine a light on the problem#
ASP.NET Core uses middleware to configure your application. You’ll use middleware to configure things like authentication, error handling and logging.
Add logging middleware to see what (if any) errors are being reported by your application.Don’t forget to select the .NET Core SDK version you’re using before you follow along.
Let’s start with logging to the console.
Add a couple of dependencies to your app
Make sure to restore them.
Update Startup.cs
to add the Console logger (via loggerFactory).
Now the console will show you what’s going on “under the hood”.
In this example .NET Core can’t find a specific view.
Microsoft Logging Extensions?#
Microsoft.Extensions.Logging is a new common logging subsystem that makes it possible to use the same logging code but target different log providers.
Microsoft provide some basic loggers in Microsoft.Extensions. For example you can write to the Event Log.
As you can see, there is one for Slack. This is not provided by Microsoft (note the different icon).
You can bring in third party loggers as dependencies (or write your own). Here are some popular ones.
NLog#
Link: NLog.Extensions.Logging
dotnet add package NLog.Extensions.Logging
Startup.cs#
Log4Net#
Link: AspNet.log4net
dotnet add package Microsoft.Extensions.Logging.Log4Net.AspNetCore
Startup.cs#
Serilog#
Link: Serilog.Extensions.Logging
dotnet add package Serilog.Extensions.Logging
Startup.cs#
In Summary#
This is just the tip of the iceberg when it comes to logging in ASP.NET Core.
Next we’ll take a look at logging your own messages and how to log different levels (e.g. info/debug) depending on your environment.
photo credit: person-question via freeimages (license)All posts in ASP.NET Core from scratch using the command line
- Your first .NET Core web application using just the command line (in ten minutes or less)
- Add Web API to your .NET Core application
- How to add MVC to your ASP.NET Core web application
- Compile your changes on the fly with .NET Core Watch
- The basics of publishing your .NET Core web app
- How to serve static files for your Single Page Application from .NET Core
- Troubleshoot your ASP.NET Core web app using logging
- How to log different levels of information in your ASP.NET Core app
- Start using Dependency Injection with ASP.NET Core