.NET 6 — Web API Logging

Mohamad Talal Lawand
2 min readSep 10, 2022

In this article we will be discussing logs in .NET 6 WebAPI and how we can utilise the WatchDog package to integrate it within our application.

You can watch the full video on youtube

And you can find the full source code on Github

https://github.com/mohamadlawand087/webapi-log

Why use WatchDog:

  • RealTime HTTP Request and Response Logger
  • RealTime Exception Logger
  • In-code message and event logging
  • User Friendly Logger Views
  • Search Option for HTTP and Exception Logs
  • Filtering Option for HTTP Logs using HTTP Methods and StatusCode
  • Logger View Authentication
  • Auto Clear Logs Option

Code

Create a new WebApi application

dotnet new webpi -n DataLog

Install the nuget package

dotnet add package WatchDog.NET

Now we need to configure our application to work with the DogWatch library inside the program.cs we need to add the following

builder.Services.AddWatchDogServices();

We can take the WatchDog service configuration to the next step by updating the following

builder.Services.AddWatchDogServices(opt =>
{
opt.IsAutoClear = true; // clears the logs after a specific duration
opt.ClearTimeSchedule = WatchDog.src.Enums.WatchDogAutoClearScheduleEnum.Monthly; // specify when it will automatically clear the logs
});

We want to be able to store the logs in a database so we can refer back to them, for that we will be utilising PostgreSQL

First we need to make sure that PostgreSQL is installed on our machine

brew install postgresql

Starting and Stoping Postgres is running

brew services start postgresql
brew services stop postgresql

Connect with Postgres

psql postgres

Create User and Pass so we can utilise them in our .NET app

CREATE ROLE devuser WITH LOGIN PASSWORD '12345678';
ALTER ROLE devuser CREATEDB;
ALTER ROLE devuser WITH Superuser;

Create a Database

create database sampledblogs;

Grand permission to the db

GRANT CONNECT ON DATABASE sampledb TO mohamad;

Update AppSettings with connection string

"ConnectionStrings": {
"SampleDbConnection": "User ID =devuser;Password=12345678;Server=localhost;Port=5432;Database=samplelogs; Integrated Security=true;Pooling=true;"
}

Now we need to enable the db connection to watch dog

builder.Services.AddWatchDogServices(opt => 
{
opt.IsAutoClear = false;
opt.SetExternalDbConnString = builder.Configuration.GetConnectionString("SampleDbConnection");
opt.SqlDriverOption = WatchDog.src.Enums.WatchDogSqlDriverEnum.PostgreSql;
});

Now we need to enable exception logs

app.UseWatchDogExceptionLogger();

Next we need to enable admin portal

app.UseWatchDog(opt => 
{
opt.WatchPageUsername = "admin";
opt.WatchPagePassword = "Mohamad123!";
});

--

--

Mohamad Talal Lawand

A determined and forward-thinking Technical Architect with 14+ years of experience.