Skip to content

rtodosic/Serilog01

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Context

  1. .Net Core Serilog – Basic
  2. .Net Core Serilog – Configuration
  3. .Net Core Serilog - Structured JSON output
  4. .Net Core Serilog - Enrichers
  5. .Net Core Serilog - Custom JSON output
  6. .Net Core Serilog - Adding Sinks

This is part 1 of 6.

1. .Net Core Serilog – Basic

Serilog isn't too hard to setup, but the following outlines the simplest steps (that I have found) to add Serilog to a .Net Core Web API project:

  1. Create a new a ASP.NET Core Web Application and select API. (Weather API Sample) Image alt text
  2. Change the Get() method in WeatherForcastController.cs to the following:
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
    var cnt = 10;
    var minTemp = -20;
    var maxTemp = 55;

    _logger.LogInformation("===> Get was called <=== Count: {Count}, MinTemp: {MinTemp}, MaxTemp: {MaxTemp}", cnt, minTemp, maxTemp);

    var rng = new Random();
    return Enumerable.Range(1, cnt).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(minTemp, maxTemp),
        Summary = Summaries[rng.Next(Summaries.Length)]
    })
    .ToArray();
}
  1. Run the app (without Serilog), you should see the default logging implementation at the command line. Image alt text
  2. Now add the “Serilog.AspNetCore” NuGet package to your project. Image alt text
  3. In Program.cs, add “using Serilog;” to the top of the file and change the CreateHostBuilder() method to the following:
public static IHostBuilder CreateHostBuilder(string[] args) =>
  Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
      webBuilder.UseStartup<Startup>();
    })
    .UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
      .WriteTo.Console()
);
  1. In the Startup.cs file, add the following, before app.UseEndpoints() near the bottom of the file.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseSerilogRequestLogging();  // <-- Add this

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}
  1. Run the app again and notice the output. Image alt text
  2. You have a basic implementation of Serilog. Notice the differences in the output. Image alt text Image alt text

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages