Christian Schou
  • Forside
  • Blog
    • Programmering
      • C#
      • PowerShell
      • Python
      • SQL
    • WordPress
      • Guides
    • Cloud
    • Boligautomatisering
      • Home Assistant
        • Node-Red
    • Career
  • Services
  • Ordbog
  • About
No Result
View All Result
Christian Schou
  • Forside
  • Blog
    • Programmering
      • C#
      • PowerShell
      • Python
      • SQL
    • WordPress
      • Guides
    • Cloud
    • Boligautomatisering
      • Home Assistant
        • Node-Red
    • Career
  • Services
  • Ordbog
  • About
No Result
View All Result
Christian Schou
No Result
View All Result
Home Programmering C# ASP.NET Core
watchdog

The #1 guide to show real-time .NET 6 logs for Web Apps and APIs in a modern way using WatchDog for Free

by Christian
13. august 2022
in ASP.NET Core
0

A reader recently asked me for a more modern way to view log files for requests and exceptions in a web application. The only requirement from him was that the solution had to be open-source and running with the Web API. Fortunately, I know a tool to log Realtime Messages, Events, and HTTP (Requests & Responses), with a built-in Exception logger and viewer for ASP.NET Core Web Apps and APIs named WatchDog.

I often use the Elastic tools to store logs from my applications, but in this case, it had to be running as a built-in service. When helping out others with their solutions I see them logging to .json, .txt, .csv, and databases at runtime. Every time the application encounters an error, they have to open up either the files or the database and search for the error id. This can be done in a much easier and more modern way using the open-source tool named WatchDog by iZyPro.

The final result you will end up with will look like this when running:

watchdog
WatchDog web interface
Indholdsfortegnelse
  1. Video tutorial
  2. What is WatchDog?
  3. Why should you use WatchDog?
  4. Add WatchDog to your .NET Web API
    • Install Dependency
    • Configure for .NET 6 Web Applications
  5. Get the most from WatchDog
    • Automatic clearing of logs by schedule
    • Blacklisting of endpoints in your Web App
    • Forward your logs to an external database
  6. Summary

Video tutorial

What is WatchDog?

From GitHub by the author:

WatchDog is a Realtime Message, Event, HTTP (Request & Response) and Exception logger and viewer for ASP.Net Core Web Apps and APIs. It allows developers log and view messages, events, http requests made to their web application and also exception caught during runtime in their web applications, all in Realtime. It leverages SignalR for real-time monitoring and LiteDb a Serverless MongoDB-like database with no configuration with the option of using your external MSSQL, MySQl or Postgres databases.

https://github.com/IzyPro/WatchDog#introduction

Why should you use WatchDog?

WatchDog allows us to do searching, filtering, pagination, automatic clearing of logs, or even forward the logs to an external database running either MS SQL, MySQL, Postgresql, or LiteDB if you would prefer a lightweight solution, and add authentication, etc… If you ask me WatchDog is in my top 5 list of open-source logging tools when making web apps using .NET.

Some of the features in WatchDog include:

  1. RealTime HTTP Request and Response Logger
  2. RealTime Exception Logger
  3. In-code message and event logging
  4. User-Friendly Logger Views
  5. Search Option for HTTP and Exception Logs
  6. Filtering Option for HTTP Logs using HTTP Methods and StatusCode
  7. Logger View Authentication
  8. Auto Clear Logs Option

Add WatchDog to your .NET Web API

Let’s move on to the part where it gets fun. We will now add WatchDog to a sample Web API I have made out of the default ASP.NET Core Web API template in Visual Studio.

Install Dependency

The first thing we have to do is install WatchDog.NET from the NuGet store. You can do this using the Package Console or by opening the GUI in Visual Studio and searching for “WatchDog.NET”. Below is the command I used to add the package to my demo project for this tutorial.

dotnet add package WatchDog.NET

You can read these official guides from Microsoft about how to install packages via Visual Studio or CLI.

Configure for .NET 6 Web Applications

To make this new library/dependency work, we have to register it in our program.cs file. Go ahead and open up program.cs and add the following code inside the file:

using WatchDog;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddWatchDogServices(); // Register services for logging service

var app = builder.Build();

app.UseWatchDogExceptionLogger(); // Add Exception logging

// Add middleware and setup username + password. You should change credentials.
app.UseWatchDog(opt =>
{
    opt.WatchPageUsername = "admin";
    opt.WatchPagePassword = "admin";
});

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

What happens in the code above?

  • We have added using WatchDog; to the block of using statements.
  • We have added middleware to register requests and responses + the exception logging service.

I have made a request for the weather forecast endpoint https://localhost:7063/WeatherForecast and this is the result of the logging service now available at https://localhost:7063/watchdog:

watchlog
WatchLog for Weather Forecast GET Request

That’s is actually all you have to do in order to get this cool logging service up and running. Below is a list of how to get the most from WatchDog.

Get the most from WatchDog

This library got some great built-in features you can use to get even more functionality without having to add more than a few lines of code, all of them are optional.

Automatic clearing of logs by schedule

If you don’t want to store your logs for too long as it easily can clutter things up, you can set up a frequency/time interval for how often the logs should automatically be cleared. You can use the following intervals:

  • Daily
  • Weekly
  • Monthly
  • Quarterly

If you would like to prevent any automatic log clearance you can use isAutoClear = false in the configuration of the service. Below is the implementation of this functionality:

services.AddWatchDogServices(settings => 
{ 
   settings.IsAutoClear = true;
   settings.ClearTimeSchedule = WatchDogAutoClearScheduleEnum.Weekly;
});

If you don’t specify any schedule the default clearance of your logs will happen on a daily basis.

Blacklisting of endpoints in your Web App

If you got any form of authentication happening in your application, I would blacklist these endpoints for security reasons. This would prevent any trail logs of your user’s credentials when they interact with your application. By design this logging service will log all your requests and responses, please use it with caution.

To avoid specific endpoints to be included in the logging service, you should pass a list of routes or even words separated by commas in the blacklist parameter in the configuration of the middleware, as shown below:

app.UseWatchDog(settings => 
{ 
   settings.WatchPageUsername = "admin"; 
   settings.WatchPagePassword = "password"; 
   settings.Blacklist = "Test/testPost, weatherforecast";
 });

Forward your logs to an external database

If you need to store the logs from your application inside another database, this can easily be done by passing a connection string along with a SQL driver. The supported databases at the time of writing are:

  • MS SQL
  • MySQL
  • PostgreSQL

To send your logs to another database, you can use this implementation:

services.AddWatchDogServices(settings => 
{
   settings.SqlDriverOption = WatchDogSqlDriverEnum.PostgreSql;
   settings.SetExternalDbConnString = "Server=localhost;Database=testLoggingDb;User Id=sa;Password=password;"; 
});
services.AddWatchDogServices(settings => 
{
   settings.SqlDriverOption = WatchDogSqlDriverEnum.MSSQL;
   settings.SetExternalDbConnString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
});
services.AddWatchDogServices(settings => 
{
   settings.SqlDriverOption = WatchDogSqlDriverEnum.MySQL;
   settings.SetExternalDbConnString = "Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;";
});

If you need a reference to templates for connection strings, you can visit https://www.connectionstrings.com/.

Summary

In this quick guide, you have learned how to set up and configure WatchDog for your .NET 6 Web Application. As you might have noticed it is very easy to implement this library/service inside your Web Application. I use it a lot when I need to show logs in a simple, easy and modern way when developing applications or running them in production.

Remember to always use authentication, as it will harden the security of your application. If you got any questions or suggestions about this topic, please let me know in the comments below. Until next time – happy coding!

Tags: .NET 6.Net CoreAPIASP.NET CoreC#DevelopmentLogLoggingWeb
Previous Post

5 tips to help you get hired for a tech job

Next Post

Top 6 things to add on your personal website to get hired for a tech job

Christian

Christian

Hello 👋 My name is Christian and I am 26 years old. I'm an educated Software Developer with a primary focus on C#, .NET Core, Python, and PowerShell. Currently, I'm expanding my skills in Software Robots and Cloud Architecture. In some of my spare time, I share my knowledge about tech stuff on my blog.

Related Posts

restful web api
ASP.NET Core

How to build a RESTful Web API using ASP.NET Core and Entity Framework Core (.NET 6)

by Christian
25. juli 2022
0

I have noticed many people searching for REST (Representational State Transfer) on my blog, but I haven't made any tutorials...

Read more
Dockerize ASP.NET Core

How to Compose an ASP.NET Core Web API (.NET 6) with an MS SQL Server 2022 on Linux in Docker

19. juli 2022
cqrs, mediatr, cqrs design pattern, design pattern

How to implement CQRS using MediatR in an ASP.NET Core Web API (.NET 6)

19. juli 2022
rate limiting, rate limit

How to implement Rate Limiting in an ASP.NET Core Web API

29. maj 2022
Next Post
personal website

Top 6 things to add on your personal website to get hired for a tech job

Skriv et svar Annuller svar

Din e-mailadresse vil ikke blive publiceret. Krævede felter er markeret med *

Christian Schou

Christian Schou

Software Developer

Hello - my name is Christian and I am 26 years old. I'm an educated Software Developer with a primary focus on C#, .NET Core, Python, and PowerShell. Currently, I'm expanding my skills in Software Robots and Cloud Architecture. In some of my spare time, I share my knowledge about tech stuff on my blog.

Recent articles

personal website
Career

Top 6 things to add on your personal website to get hired for a tech job

by Christian
7. august 2022
0

Back in the days before the internet was a thing like it is today, we used to have business cards...

Read more
watchdog

The #1 guide to show real-time .NET 6 logs for Web Apps and APIs in a modern way using WatchDog for Free

13. august 2022
get hired for a tech job

5 tips to help you get hired for a tech job

31. juli 2022
restful web api

How to build a RESTful Web API using ASP.NET Core and Entity Framework Core (.NET 6)

25. juli 2022
dynamically register entities

How to Dynamically Register Entities in DbContext by Extending ModelBuilder?

23. juli 2022

Christian Schou

Software Developer

Hello - my name is Christian and I am 26 years old. I'm an educated Software Developer with a primary focus on C#, .NET Core, Python, and PowerShell. Currently, I'm expanding my skills in Software Robots and Cloud Architecture. In some of my spare time, I share my knowledge about tech stuff on my blog.

Recent articles

personal website

Top 6 things to add on your personal website to get hired for a tech job

7. august 2022
watchdog

The #1 guide to show real-time .NET 6 logs for Web Apps and APIs in a modern way using WatchDog for Free

13. august 2022
get hired for a tech job

5 tips to help you get hired for a tech job

31. juli 2022
  • da_DKDansk
    • en_USEnglish
    • de_DEDeutsch
    • hi_INहिन्दी
    • pt_BRPortuguês do Brasil
  • Contact
  • Privatlivspolitik
  • Vilkår og betingelser

© 2022 Christian Schou - All rights reserved.

No Result
View All Result
  • Forside
  • Blog
    • Programmering
      • C#
      • PowerShell
      • Python
      • SQL
    • WordPress
      • Guides
    • Cloud
    • Boligautomatisering
      • Home Assistant
    • Career
  • Services
  • Ordbog
  • About

© 2022 Christian Schou - All rights reserved.

Jeg bruger cookies på min hjemmeside for at give dig den mest relevante oplevelse ved at huske dine præferencer og gentage besøg. Ved at klikke på "Accepter“, du giver dit samtykke til brugen af ALLE cookies.
Sælg ikke mine personlige informationer.
Cookie indstillingerACCEPT
Privat & Cookies politik

Overblik over privatliv

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Altid aktiveret
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
CookieVarighedBeskrivelse
__gads1 year 24 daysThe __gads cookie, set by Google, is stored under DoubleClick domain and tracks the number of times users see an advert, measures the success of the campaign and calculates its revenue. This cookie can only be read from the domain they are set on and will not track any data while browsing through other sites.
_ga2 yearsThe _ga cookie, installed by Google Analytics, calculates visitor, session and campaign data and also keeps track of site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognize unique visitors.
_ga_0J2F6JVWSD2 yearsThis cookie is installed by Google Analytics.
_gat_gtag_UA_84232734_11 minuteSet by Google to distinguish users.
_gid1 dayInstalled by Google Analytics, _gid cookie stores information on how visitors use a website, while also creating an analytics report of the website's performance. Some of the data that are collected include the number of visitors, their source, and the pages they visit anonymously.
YouTube2 yearsYouTube sets this cookie via embedded youtube-videos and registers anonymous statistical data. I embed YouTube videos in my articles/tutorials - you won't get the full experience of the articles if this is deactivated.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
CookieVarighedBeskrivelse
IDE1 year 24 daysGoogle DoubleClick IDE cookies are used to store information about how the user uses the website to present them with relevant ads and according to the user profile.
test_cookie15 minutesThe test_cookie is set by doubleclick.net and is used to determine if the user's browser supports cookies.
VISITOR_INFO1_LIVE5 months 27 daysA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.
YSCsessionYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.
yt-remote-connected-devicesneverYouTube sets this cookie to store the video preferences of the user using embedded YouTube video.
yt-remote-device-idneverYouTube sets this cookie to store the video preferences of the user using embedded YouTube video.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
GEM & ACCEPTÈR
Powered by CookieYes Logo