DEV Community

Andrés Baamonde Lozano
Andrés Baamonde Lozano

Posted on

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

Top comments (0)