DEV Community

Andrés Baamonde Lozano
Andrés Baamonde Lozano

Posted on

3 1

Serilog Configuration in aspnet core

On the previous post we fully configurate a serilog on a console application, one of the advantages of defining configuration on a json file, is that we can migrate configuration only copiying the file.

Create the project

mkdir AspnetcoreSerilog
cd AspnetcoreSerilog
dotnet run webapi
Enter fullscreen mode Exit fullscreen mode

Now, we copy serilog config from our previous appsettings file and add dependencies to our new csproj and restore:

  <PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
  <PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />
  <PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
  <PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
  <PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
  <PackageReference Include="Serilog.Filters.Expressions" Version="2.1.0" />
  <PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
Enter fullscreen mode Exit fullscreen mode

Modify your program.cs file, add to CreateHostbuilder the function use serilog call.

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
                    .ReadFrom.Configuration(hostingContext.Configuration))
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
Enter fullscreen mode Exit fullscreen mode

Now we continue host configuration modifications: Enable request logging modifying Startup.cs

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSerilogRequestLogging();

            app.UseHttpsRedirection();
            /* ** file continues  ** */
        }
Enter fullscreen mode Exit fullscreen mode

On the previous post i described the filter expressions functionality. This time we will use expressions to send log messages to differente files, in particular depending on it http method.

For doing this we need a few things. First i will destructure Http Request and then i will filter with a expression depending on the http method.

{
    "Destructure": [
      {
        "Name": "ByTransformingWhere",
        "Args": {
          "predicate": "t => typeof(HttpRequest).Equals(t)",
          "transformedType": "HttpRequest",
          "transformation": "a => new { RawUrl = a.RawUrl, Method = a.Method }"
        }
      }
    ],
}
Enter fullscreen mode Exit fullscreen mode
{
           "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "Method = 'POST'"
                }
              }
            ]
}
Enter fullscreen mode Exit fullscreen mode

Now we will see on console log all logs, and http post calls in his respective file.

My example includes GET and POST filter with two subloggers, you can check http file on my github repo see references below.

References

AspnetSerilog repository (this example)
desctructure
web classic enrich
filter expressions
destructure transforming

Quadratic AI

Quadratic AI – The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo 📊✨

Top comments (0)

PulumiUP 2025 image

PulumiUP 2025: Cloud Innovation Starts Here

Get inspired by experts at PulumiUP. Discover the latest in platform engineering, IaC, and DevOps. Keynote, demos, panel, and Q&A with Pulumi engineers.

Register Now

👋 Kindness is contagious

Dive into this informative piece, backed by our vibrant DEV Community

Whether you’re a novice or a pro, your perspective enriches our collective insight.

A simple “thank you” can lift someone’s spirits—share your gratitude in the comments!

On DEV, the power of shared knowledge paves a smoother path and tightens our community ties. Found value here? A quick thanks to the author makes a big impact.

Okay