Achraf Ben Alaya
No Result
View All Result
  • Home
  • News
  • Blog
    • blazor
    • c#
    • Cloud
      • Azure
    • docker
    • sql
    • xamarin
    • Dapr
    • Tricks, Tips and Fixes
    • General Tips & Fix
  • AI
  • Cloud
  • Motivation
  • Courses
  • About
    • Resume
    • Privacy Policy
SUBSCRIBE
  • Home
  • News
  • Blog
    • blazor
    • c#
    • Cloud
      • Azure
    • docker
    • sql
    • xamarin
    • Dapr
    • Tricks, Tips and Fixes
    • General Tips & Fix
  • AI
  • Cloud
  • Motivation
  • Courses
  • About
    • Resume
    • Privacy Policy
No Result
View All Result
Achraf Ben Alaya
No Result
View All Result
ADVERTISEMENT
Home Blog

Setting up Serilog in ASP.NET Core

achraf by achraf
September 15, 2020
in Blog, c#
4 min read
0
Setting up Serilog in ASP.NET Core
0
SHARES
3k
VIEWS
Share on FacebookShare on Twitter

WHAT TO LOG

It is not enough to log errors in order to use them for troubleshooting purposes. It is also useful to log successful requests so we can have a clear idea of how users work with the application .

Logs are also useful to detect  mistakes that users make, as well as for security purposes. Writing good logs about a user’s activity can alert us about malicious activity or any other kind of problems that we didn’t detect .

Why use Serilog ?

Serilog provides basic diagnostic logging not only to the console, files, Amazon, Azure, but more ,it’s easy to integrate and to use in a few steps .

This article will demonstrate the console and file sinks. It is easy as 1, 2, 3 to set up with appsettings configurations.

Steps : 

 

First thing that we are going to do is to create a new empty solution (Web Api )

serielog
serielog
serielog
serielog

Now we need to use the package manager to install some extensions as in pictures below or you can use the command :

Serilog.AspNetCore package

 

serielog
serielog
serielog
serielog
serielog
serielog
serielog
serielog
serielog
serielog
serielog
serielog
serielog
serielog

Logger initialization in Program.cs :

To start working with Serielog we need to initilize it first in the program.cs  .
You can copy replace your code with the below code :

public static void Main(string[] args)
       {
           var configuration = new ConfigurationBuilder()
           .AddJsonFile("appsettings.json")
           .Build();

           Log.Logger = new LoggerConfiguration()
               .ReadFrom.Configuration(configuration).WriteTo.Console().CreateLogger();

           try
           {
               Log.Information("Application startinng up");
               CreateHostBuilder(args).Build().Run();
           }
           catch (Exception ex)
           {

               Log.Fatal(ex, "The application failed to start correctly");
           }
           finally
           {
               Log.CloseAndFlush();

           }



       }

Also , we need to add : .UseSerilog() inside the CreateHostBuilder :

public static IHostBuilder CreateHostBuilder(string[] args) =>
           Host.CreateDefaultBuilder(args)
           .UseSerilog()
               .ConfigureWebHostDefaults(webBuilder =>
               {
                   webBuilder.UseStartup<Startup>();
               });

 

Next , inside the Startup.cs we need to add : app.UseSerilogRequestLogging();

serielog
serielog

 

Now if we run our solution , we should see inside the console a message saying : Application startinng up ,

if you remember we added a line of code that will fire when the application start :

Log.Information("Application startinng up");

 

serielog
serielog

 

Cleaning up The default logger :

There are a few more changes that we are going to do and now inside the appsettings.json .

Serilog completely replaces the logging implementation on .NET Core,it will not work together  but it will replace the default implementation . The benefit of this is that you’re not running two different logging frameworks with tricky edge cases where they overlap in functionality.

{
  "AllowedHosts": "*",
  "Serilog": {
    "Using": [],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/log.txt",
          "rollingInterval": "Day",
          "outputTemplate": "{Timestamp:G} {Message}{NewLine:1}{Exception:1}"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/log.json",
          "rollingInterval": "Day",
          "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
        }
      }
   
    ]
  }
}

The “Name” key here specifies the sink desired. To write to multiple sinks, add another object to the “WriteTo” array , in our case we want to create files inside a logs folder and each day we want to create a new different file that contain the date time .

The MinimumLevel configuration object provides for one of the log event levels to be specified as the minimum.

If you see ,we have “path“: “Logs/log.txt”, where we define where we want our file to be written to and stored .

rollingInterval here mean that we want to create a new file per day .

as you can see inside write to , we defined to object , one that will write to a text file and another one that’s going to write inside a json file .

Now let’s run our solution :

 

serielog
serielog
serielog
serielog

As you can see there is a new Folder created : Logs , that contain a json file and a txt file .
let explore those 2 files :

{"Timestamp":"2020-09-13T15:04:23.3942682+01:00","Level":"Information","MessageTemplate":"Application startinng up"}
{"Timestamp":"2020-09-13T15:04:25.9319025+01:00","Level":"Information","MessageTemplate":"Getting WeatherForecast details","Properties":{"ActionId":"9612d1c8-4c4e-44b7-b7fd-374fe905687c","ActionName":"SerielogDemoDay.Controllers.WeatherForecastController.Get (SerielogDemoDay)","RequestId":"0HM2NTNM09MCA:00000001","RequestPath":"/weatherforecast","SpanId":"|b35b87a8-42a0adeaed09085c.","TraceId":"b35b87a8-42a0adeaed09085c","ParentId":""}}
{"Timestamp":"2020-09-13T15:04:25.9642904+01:00","Level":"Information","MessageTemplate":"HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms","Properties":{"RequestMethod":"GET","RequestPath":"/weatherforecast","StatusCode":200,"Elapsed":134.7792,"SourceContext":"Serilog.AspNetCore.RequestLoggingMiddleware","RequestId":"0HM2NTNM09MCA:00000001","SpanId":"|b35b87a8-42a0adeaed09085c.","TraceId":"b35b87a8-42a0adeaed09085c","ParentId":""},"Renderings":{"Elapsed":[{"Format":"0.0000","Rendering":"134.7792"}]}}

As You can see the json file is very detailed file that contain all the event that happened .

while the txt file below , contain the actions with date time .

09/13/2020 15:04:23 Application startinng up
09/13/2020 15:04:25 Getting WeatherForecast details
09/13/2020 15:04:25 HTTP "GET" "/weatherforecast" responded 200 in 134.7792 ms

and now you can log anywhere inside your application by just using :

Log.Debug("debug test!");
Log.Information("Informations here.....!");
Log.Error("Error here ....!");

 

Link to demo project .

ShareTweet
Previous Post

What’s new in Microsoft Teams

Next Post

Learn… and get rewarded

Related Posts

AI

Model Context Protocol (MCP): The Future of AI Integration

April 21, 2025
94
Azure

Step-by-Step Guide: Azure Front Door + Storage Account Static Website + Custom Domain with Terraform

March 11, 2025
212
Network Security & Route Tables – Checking NSGs, route tables, and service endpoints for a targeted VNET or Subnet
Azure

Network Security & Route Tables – Checking NSGs, route tables, and service endpoints for a targeted VNET or Subnet

February 3, 2025
132
Understanding Generative AI and RAG Benefits
AI

Understanding Generative AI and RAG Benefits

January 12, 2025
95
Azure Communication Services Email Sending Simplified: From Setup to Execution and Monitoring
Azure

Azure Communication Services Email Sending Simplified: From Setup to Execution and Monitoring

December 8, 2024
1.5k
PowerShell Automation for Azure Networks: Detailed VNET and Subnet Analysis
Azure

PowerShell Automation for Azure Networks: Detailed VNET and Subnet Analysis

November 2, 2024
495
Next Post
Learn… and get rewarded

Learn... and get rewarded

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Terraform

Certifications

Microsoft certified trainer (MCT)

Recommended

15 E-books that focus on learning Microsoft Azure Cloud

15 E-books that focus on learning Microsoft Azure Cloud

April 23, 2023
218
Generating report for SSL Certificates for Websites with PowerShell

Generating report for SSL Certificates for Websites with PowerShell

April 10, 2022
1.1k
Boxing and Unboxing in C#

Boxing and Unboxing in C#

August 29, 2020
1.1k
Migrate and modernize your applications on Azure

Migrate and modernize your applications on Azure – Part 2.0 (Azure Functions)

April 3, 2021
541

How To host a Next.js app on Azure

October 5, 2020
1.5k
How to make the most of each day

How to make the most of each day

February 2, 2021
315
Facebook Twitter LinkedIn Youtube

Model Context Protocol (MCP): The Future of AI Integration

April 21, 2025

Step-by-Step Guide: Azure Front Door + Storage Account Static Website + Custom Domain with Terraform

March 11, 2025
Network Security & Route Tables – Checking NSGs, route tables, and service endpoints for a targeted VNET or Subnet

Network Security & Route Tables – Checking NSGs, route tables, and service endpoints for a targeted VNET or Subnet

February 3, 2025

Categories

  • AI (2)
  • Apps (1)
  • Azure (63)
  • blazor (2)
  • Blog (91)
  • c# (7)
  • Cloud (65)
  • Courses (3)
  • Dapr (4)
  • docker (4)
  • Games (1)
  • General Tips & Fix (1)
  • Home (1)
  • Kubernetes Service (AKS) (1)
  • motivation (2)
  • Motivation (3)
  • News (9)
  • Resume (1)
  • sql (4)
  • Terrafrom (1)
  • Tricks, Tips and Fixes (4)
  • xamarin (5)
No Result
View All Result
  • Home
  • News
  • Blog
    • blazor
    • c#
    • Cloud
      • Azure
    • docker
    • sql
    • xamarin
    • Dapr
    • Tricks, Tips and Fixes
    • General Tips & Fix
  • AI
  • Cloud
  • Motivation
  • Courses
  • About
    • Resume
    • Privacy Policy