Serilog.Settings.Configuration 8.0.0-dev-00555

Serilog.Settings.Configuration Build status NuGet Version

A Serilog settings provider that reads from Microsoft.Extensions.Configuration sources, including .NET Core's appsettings.json file.

By default, configuration is read from the Serilog section.

{
  "Serilog": {
    "Using":  [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      { "Name": "Console" },
      { "Name": "File", "Args": { "path": "Logs/log.txt" } }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
    "Destructure": [
      { "Name": "With", "Args": { "policy": "Sample.CustomPolicy, Sample" } },
      { "Name": "ToMaximumDepth", "Args": { "maximumDestructuringDepth": 4 } },
      { "Name": "ToMaximumStringLength", "Args": { "maximumStringLength": 100 } },
      { "Name": "ToMaximumCollectionCount", "Args": { "maximumCollectionCount": 10 } }
    ],
    "Properties": {
        "Application": "Sample"
    }
  }
}

After installing this package, use ReadFrom.Configuration() and pass an IConfiguration object.

static void Main(string[] args)
{
    var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", true)
        .Build();

    var logger = new LoggerConfiguration()
        .ReadFrom.Configuration(configuration)
        .CreateLogger();

    logger.Information("Hello, world!");
}

This example relies on the Microsoft.Extensions.Configuration.Json, Serilog.Sinks.Console, Serilog.Sinks.File, Serilog.Enrichers.Environment and Serilog.Enrichers.Thread packages also being installed.

For a more sophisticated example go to the sample folder.

Syntax description

Root section name

Root section name can be changed:

{
  "CustomSection": {
    ...
  }
}
var options = new ConfigurationReaderOptions { SectionName = "CustomSection" };
var logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration, options)
    .CreateLogger();

Using section and auto-discovery of configuration assemblies

Using section contains list of assemblies in which configuration methods (WriteTo.File(), Enrich.WithThreadId()) reside.

"Serilog": {
    "Using":  [ "Serilog.Sinks.Console", "Serilog.Enrichers.Thread", /* ... */ ],
    // ...
}

For .NET Core projects build tools produce .deps.json files and this package implements a convention using Microsoft.Extensions.DependencyModel to find any package among dependencies with Serilog anywhere in the name and pulls configuration methods from it, so the Using section in example above can be omitted:

{
  "Serilog": {
    "MinimumLevel": "Debug",
    "WriteTo": [ "Console" ],
    ...
  }
}

In order to utilize this convention for .NET Framework projects which are built with .NET Core CLI tools specify PreserveCompilationContext to true in the csproj properties:

<PropertyGroup Condition=" '$(TargetFramework)' == 'net46' ">
  <PreserveCompilationContext>true</PreserveCompilationContext>
</PropertyGroup>

In case of non-standard dependency management you can pass a custom DependencyContext object:

var functionDependencyContext = DependencyContext.Load(typeof(Startup).Assembly);

var options = new ConfigurationReaderOptions(functionDependencyContext) { SectionName = "AzureFunctionsJobHost:Serilog" };
var logger = new LoggerConfiguration()
    .ReadFrom.Configuration(hostConfig, options)
    .CreateLogger();

Alternatively, you can also pass an array of configuration assemblies:

var configurationAssemblies = new[]
{
    typeof(ConsoleLoggerConfigurationExtensions).Assembly,
    typeof(FileLoggerConfigurationExtensions).Assembly,
};
var options = new ConfigurationReaderOptions(configurationAssemblies);
var logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration, options)
    .CreateLogger();

For legacy .NET Framework projects it also scans default probing path(s).

For all other cases, as well as in the case of non-conventional configuration assembly names DO use Using section.

.NET 5.0 onwards Single File Applications

Currently, auto-discovery of configuration assemblies is not supported in bundled mode. DO use Using section or explicitly pass a collection of configuration assemblies for workaround.

MinimumLevel, LevelSwitches, overrides and dynamic reload

The MinimumLevel configuration property can be set to a single value as in the sample above, or, levels can be overridden per logging source.

This is useful in ASP.NET Core applications, which will often specify minimum level as:

"MinimumLevel": {
    "Default": "Information",
    "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
    }
}

MinimumLevel section also respects dynamic reload if the underlying provider supports it.

var configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile(path: "appsettings.json", reloadOnChange: true)
    .Build();

Any changes for Default, Microsoft, System sources will be applied at runtime.

(Note: only existing sources are respected for a dynamic update. Inserting new records in Override section is not supported.)

You can also declare LoggingLevelSwitch-es in custom section and reference them for sink parameters:

{
    "Serilog": {
        "LevelSwitches": { "controlSwitch": "Verbose" },
        "WriteTo": [
            {
                "Name": "Seq",
                "Args": {
                    "serverUrl": "http://localhost:5341",
                    "apiKey": "yeEZyL3SMcxEKUijBjN",
                    "controlLevelSwitch": "$controlSwitch"
                }
            }
        ]
    }
}

Level updates to switches are also respected for a dynamic update.

Since version 7.0.0, both declared switches (i.e. Serilog:LevelSwitches section) and minimum level override switches (i.e. Serilog:MinimumLevel:Override section) are exposed through a callback on the reader options so that a reference can be kept:

var allSwitches = new Dictionary<string, LoggingLevelSwitch>();
var options = new ConfigurationReaderOptions
{
    OnLevelSwitchCreated = (switchName, levelSwitch) => allSwitches[switchName] = levelSwitch
};

var logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration, options)
    .CreateLogger();

LoggingLevelSwitch controlSwitch = allSwitches["$controlSwitch"];

WriteTo, Enrich, AuditTo, Destructure sections

These sections support simplified syntax, for example the following is valid if no arguments are needed by the sinks:

"WriteTo": [ "Console", "DiagnosticTrace" ]

Or alternatively, the long-form ("Name": ...) syntax from the example above can be used when arguments need to be supplied.

By Microsoft.Extensions.Configuration.Json convention, array syntax implicitly defines index for each element in order to make unique paths for configuration keys. So the example above is equivalent to:

"WriteTo": {
    "0": "Console",
    "1": "DiagnosticTrace"
}

And

"WriteTo:0": "Console",
"WriteTo:1": "DiagnosticTrace"

(The result paths for the keys will be the same, i.e. Serilog:WriteTo:0 and Serilog:WriteTo:1)

When overriding settings with environment variables it becomes less convenient and fragile, so you can specify custom names:

"WriteTo": {
    "ConsoleSink": "Console",
    "DiagnosticTraceSink": { "Name": "DiagnosticTrace" }
}

Properties section

This section defines a static list of key-value pairs that will enrich log events.

Filter section

This section defines filters that will be applied to log events. It is especially useful in combination with Serilog.Expressions (or legacy Serilog.Filters.Expressions) package so you can write expression in text form:

"Filter": [{
  "Name": "ByIncludingOnly",
  "Args": {
      "expression": "Application = 'Sample'"
  }
}]

Using this package you can also declare LoggingFilterSwitch-es in custom section and reference them for filter parameters:

{
    "Serilog": {
        "FilterSwitches": { "filterSwitch": "Application = 'Sample'" },
        "Filter": [
            {
                "Name": "ControlledBy",
                "Args": {
                    "switch": "$filterSwitch"
                }
            }
        ]
}

Level updates to switches are also respected for a dynamic update.

Since version 7.0.0, filter switches are exposed through a callback on the reader options so that a reference can be kept:

var filterSwitches = new Dictionary<string, ILoggingFilterSwitch>();
var options = new ConfigurationReaderOptions
{
    OnFilterSwitchCreated = (switchName, filterSwitch) => filterSwitches[switchName] = filterSwitch
};

var logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration, options)
    .CreateLogger();

ILoggingFilterSwitch filterSwitch = filterSwitches["filterSwitch"];

Nested configuration sections

Some Serilog packages require a reference to a logger configuration object. The sample program in this project illustrates this with the following entry configuring the Serilog.Sinks.Async package to wrap the Serilog.Sinks.File package. The configure parameter references the File sink configuration:

"WriteTo:Async": {
  "Name": "Async",
  "Args": {
    "configure": [
      {
        "Name": "File",
        "Args": {
          "path": "%TEMP%/Logs/serilog-configuration-sample.txt",
          "outputTemplate":
              "{Timestamp:o} [{Level:u3}] ({Application}/{MachineName}/{ThreadId}) {Message}{NewLine}{Exception}"
        }
      }
    ]
  }
},

Destructuring

Destructuring means extracting pieces of information from an object and create properties with values; Serilog offers the @ structure-capturing operator. In case there is a need to customize the way log events are serialized (e.g., hide property values or replace them with something else), one can define several destructuring policies, like this:

"Destructure": [
  {
    "Name": "With",
    "Args": {
      "policy": "MyFirstNamespace.FirstDestructuringPolicy, MyFirstAssembly"
    }
  },
  {
    "Name": "With",
    "Args": {
      "policy": "policy": "MySecondNamespace.SecondDestructuringPolicy, MySecondAssembly"
    }
  },
   {
    "Name": "With",
    "Args": {
      "policy": "policy": "MyThirdNamespace.ThirdDestructuringPolicy, MyThirdAssembly"
    }
  },
],

This is how the first destructuring policy would look like:

namespace MyFirstNamespace;

public record MyDto(int Id, int Name);

public class FirstDestructuringPolicy : IDestructuringPolicy
{
    public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, 
        [NotNullWhen(true)] out LogEventPropertyValue? result)
    {
        if (value is not MyDto dto)
        {
            result = null;
            return false;
        }

        result = new StructureValue(new List<LogEventProperty>
        {
            new LogEventProperty("Identifier", new ScalarValue(deleteTodoItemInfo.Id)),
            new LogEventProperty("NormalizedName", new ScalarValue(dto.Name.ToUpperInvariant()))
        });

        return true;
    }
}

Assuming Serilog needs to destructure an argument of type MyDto when handling a log event:

logger.Information("About to process input: {@MyDto} ...", myDto);

it will apply FirstDestructuringPolicy which will convert MyDto instance to a StructureValue instance; a Serilog console sink would write the following entry:

About to process input: {"Identifier": 191, "NormalizedName": "SOME_UPPER_CASE_NAME"} ...

Arguments binding

When the configuration specifies a discrete value for a parameter (such as a string literal), the package will attempt to convert that value to the target method's declared CLR type of the parameter. Additional explicit handling is provided for parsing strings to Uri, TimeSpan, enum, arrays and custom collections.

Since version 7.0.0, conversion will use the invariant culture (CultureInfo.InvariantCulture) as long as the ReadFrom.Configuration(IConfiguration configuration, ConfigurationReaderOptions options) method is used. Obsolete methods use the current culture to preserve backward compatibility.

Static member support

Static member access can be used for passing to the configuration argument via special syntax:

{
  "Args": {
     "encoding": "System.Text.Encoding::UTF8",
     "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console"
  }
}

Complex parameter value binding

If the parameter value is not a discrete value, it will try to find a best matching public constructor for the argument:

{
  "Name": "Console",
  "Args": {
    "formatter": {
      // `type` (or $type) is optional, must be specified for abstract declared parameter types
      "type": "Serilog.Templates.ExpressionTemplate, Serilog.Expressions",
      "template": "[{@t:HH:mm:ss} {@l:u3} {Coalesce(SourceContext, '<none>')}] {@m}\n{@x}"
      }
  }
}

For other cases the package will use the configuration binding system provided by Microsoft.Extensions.Options.ConfigurationExtensions to attempt to populate the parameter. Almost anything that can be bound by IConfiguration.Get<T> should work with this package. An example of this is the optional List<Column> parameter used to configure the .NET Standard version of the Serilog.Sinks.MSSqlServer package.

Abstract parameter types

If parameter type is an interface or an abstract class you need to specify the full type name that implements abstract type. The implementation type should have parameterless constructor.

"Destructure": [
    { "Name": "With", "Args": { "policy": "Sample.CustomPolicy, Sample" } },
    ...
],

IConfiguration parameter

If a Serilog package requires additional external configuration information (for example, access to a ConnectionStrings section, which would be outside of the Serilog section), the sink should include an IConfiguration parameter in the configuration extension method. This package will automatically populate that parameter. It should not be declared in the argument list in the configuration source.

IConfigurationSection parameters

Certain Serilog packages may require configuration information that can't be easily represented by discrete values or direct binding-friendly representations. An example might be lists of values to remove from a collection of default values. In this case the method can accept an entire IConfigurationSection as a call parameter and this package will recognize that and populate the parameter. In this way, Serilog packages can support arbitrarily complex configuration scenarios.

Samples

Azure Functions (v2, v3)

hosts.json

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingExcludedTypes": "Request",
      "samplingSettings": {
        "isEnabled": true
      }
    }
  },
  "Serilog": {
    "MinimumLevel": {
        "Default": "Information",
        "Override": {
            "Microsoft": "Warning",
            "System": "Warning"
        }
    },
    "Enrich": [ "FromLogContext" ],
    "WriteTo": [
      { "Name": "Seq", "Args": { "serverUrl": "http://localhost:5341" } }
    ]
  }
}

In Startup.cs section name should be prefixed with AzureFunctionsJobHost

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddSingleton<ILoggerProvider>(sp =>
        {
            var functionDependencyContext = DependencyContext.Load(typeof(Startup).Assembly);

            var hostConfig = sp.GetRequiredService<IConfiguration>();
            var options = new ConfigurationReaderOptions(functionDependencyContext) { SectionName = "AzureFunctionsJobHost:Serilog" };
            var logger = new LoggerConfiguration()
                .ReadFrom.Configuration(hostConfig, options)
                .CreateLogger();

            return new SerilogLoggerProvider(logger, dispose: true);
        });
    }
}

In order to make auto-discovery of configuration assemblies work, modify Function's csproj file

<Project Sdk="Microsoft.NET.Sdk">

  <!-- ... -->

  <!-- add this targets -->
  <Target Name="FunctionsPostBuildDepsCopy" AfterTargets="PostBuildEvent">
    <Copy SourceFiles="$(OutDir)$(AssemblyName).deps.json" DestinationFiles="$(OutDir)bin\$(AssemblyName).deps.json" />
  </Target>

  <Target Name="FunctionsPublishDepsCopy" AfterTargets="Publish">
    <Copy SourceFiles="$(OutDir)$(AssemblyName).deps.json" DestinationFiles="$(PublishDir)bin\$(AssemblyName).deps.json" />
  </Target>

</Project>

Versioning

This package tracks the versioning and target framework support of its Microsoft.Extensions.Configuration dependency.

Showing the top 20 packages that depend on Serilog.Settings.Configuration.

Packages Downloads
Serilog.AspNetCore
Serilog support for ASP.NET Core logging
1,111
Serilog.AspNetCore
Serilog support for ASP.NET Core logging
33
Serilog.AspNetCore
Serilog support for ASP.NET Core logging
22
Serilog.AspNetCore
Serilog support for ASP.NET Core logging
20
Serilog.AspNetCore
Serilog support for ASP.NET Core logging
19
Serilog.AspNetCore
Serilog support for ASP.NET Core logging
18
Serilog.AspNetCore
Serilog support for ASP.NET Core logging
17
Serilog.AspNetCore
Serilog support for ASP.NET Core logging
16

Version Downloads Last updated
10.0.1-dev-02339 6 04/10/2026
10.0.1-dev-02334 5 04/09/2026
10.0.1-dev-02330 23 01/21/2026
10.0.0 18 12/13/2025
10.0.0-dev-02326 11 12/21/2025
10.0.0-dev-02325 11 12/20/2025
10.0.0-dev-02323 14 12/15/2025
10.0.0-dev-02322 13 12/15/2025
9.0.1-dev-02319 12 12/10/2025
9.0.1-dev-02317 11 12/13/2025
9.0.0 9 12/15/2025
9.0.0-dev-02314 12 12/13/2025
9.0.0-dev-02313 9 12/10/2025
9.0.0-dev-02311 9 12/13/2025
9.0.0-dev-02304 10 12/14/2025
8.0.4 10 12/20/2025
8.0.4-dev-00604 15 12/25/2025
8.0.3 7 12/13/2025
8.0.3-dev-00600 10 01/02/2026
8.0.2 10 12/11/2025
8.0.2-dev-00599 9 12/22/2025
8.0.2-dev-00598 6 12/21/2025
8.0.2-dev-00592 13 12/11/2025
8.0.2-dev-00591 9 12/22/2025
8.0.1 11 12/26/2025
8.0.1-dev-00583 6 01/07/2026
8.0.1-dev-00582 10 12/29/2025
8.0.1-dev-00575 12 12/23/2025
8.0.1-dev-00572 11 12/22/2025
8.0.1-dev-00571 11 12/22/2025
8.0.1-dev-00561 11 12/13/2025
8.0.0 1,112 12/10/2025
8.0.0-dev-00556 10 01/02/2026
8.0.0-dev-00555 10 12/16/2025
8.0.0-dev-00550 14 12/11/2025
7.0.2-dev-00546 12 12/10/2025
7.0.1 11 12/14/2025
7.0.1-dev-00540 10 12/29/2025
7.0.0 14 01/02/2026
7.0.0-dev-00538 11 12/13/2025
7.0.0-dev-00535 8 12/28/2025
7.0.0-dev-00529 15 12/13/2025
7.0.0-dev-00527 7 12/22/2025
7.0.0-dev-00525 13 12/13/2025
7.0.0-dev-00521 13 12/11/2025
7.0.0-dev-00519 10 12/11/2025
7.0.0-dev-00513 11 12/11/2025
7.0.0-dev-00508 13 12/11/2025
7.0.0-dev-00504 10 12/22/2025
4.0.0-dev-00499 11 12/22/2025
4.0.0-dev-00486 11 12/16/2025
4.0.0-dev-00484 17 12/10/2025
4.0.0-dev-00482 10 12/20/2025
4.0.0-dev-00473 8 12/13/2025
4.0.0-dev-00456 14 12/13/2025
4.0.0-dev-00452 13 12/28/2025
4.0.0-dev-00448 7 12/22/2025
4.0.0-dev-00443 12 12/13/2025
4.0.0-dev-00440 13 12/13/2025
4.0.0-dev-00417 13 12/13/2025
4.0.0-dev-00413 11 12/13/2025
4.0.0-dev-00411 13 12/13/2025
4.0.0-dev-00408 6 12/13/2025
4.0.0-dev-00401 10 12/22/2025
4.0.0-dev-00395 10 12/28/2025
4.0.0-dev-00389 6 12/14/2025
4.0.0-dev-00385 11 12/13/2025
3.5.0-dev-00383 11 12/22/2025
3.5.0-dev-00370 13 12/12/2025
3.5.0-dev-00367 10 12/28/2025
3.5.0-dev-00359 5 01/10/2026
3.5.0-dev-00357 15 12/31/2025
3.5.0-dev-00355 9 12/22/2025
3.5.0-dev-00353 13 12/13/2025
3.5.0-dev-00352 5 01/06/2026
3.4.0 16 12/13/2025
3.3.1-dev-00337 7 12/30/2025
3.3.1-dev-00335 10 12/28/2025
3.3.1-dev-00327 10 12/09/2025
3.3.1-dev-00323 11 12/21/2025
3.3.1-dev-00313 10 12/13/2025
3.3.1-dev-00296 18 12/18/2025
3.3.0 7 12/15/2025
3.3.0-dev-00291 10 12/16/2025
3.2.1-dev-00288 8 12/31/2025
3.2.0 11 12/13/2025
3.2.0-dev-00283 9 12/13/2025
3.2.0-dev-00281 8 01/01/2026
3.2.0-dev-00272 12 12/13/2025
3.2.0-dev-00269 11 12/28/2025
3.2.0-dev-00266 10 01/06/2026
3.2.0-dev-00264 8 12/13/2025
3.2.0-dev-00261 10 12/12/2025
3.2.0-dev-00257 11 12/13/2025
3.2.0-dev-00249 7 12/23/2025
3.2.0-dev-00244 9 12/14/2025
3.2.0-dev-00239 11 12/13/2025
3.1.1-dev-00237 9 12/30/2025
3.1.1-dev-00234 6 01/02/2026
3.1.1-dev-00232 7 01/04/2026
3.1.1-dev-00228 10 12/13/2025
3.1.1-dev-00224 12 12/13/2025
3.1.1-dev-00216 9 01/01/2026
3.1.1-dev-00209 10 12/13/2025
3.1.0 12 12/11/2025
3.1.0-dev-00206 10 12/22/2025
3.1.0-dev-00204 14 12/28/2025
3.1.0-dev-00202 7 01/05/2026
3.1.0-dev-00200 8 12/13/2025
3.0.2-dev-00198 8 01/07/2026
3.0.2-dev-00195 8 12/28/2025
3.0.2-dev-00187 12 12/13/2025
3.0.2-dev-00186 14 12/16/2025
3.0.2-dev-00185 11 12/28/2025
3.0.2-dev-00183 9 12/25/2025
3.0.2-dev-00171 11 12/28/2025
3.0.1 10 12/13/2025
3.0.1-dev-00163 11 12/13/2025
3.0.1-dev-00160 12 12/28/2025
3.0.0 10 12/13/2025
3.0.0-dev-00149 9 12/13/2025
3.0.0-dev-00147 9 12/13/2025
3.0.0-dev-00142 9 12/13/2025
3.0.0-dev-00139 12 12/19/2025
3.0.0-dev-00133 8 01/03/2026
3.0.0-dev-00128 14 12/13/2025
3.0.0-dev-00125 12 12/24/2025
3.0.0-dev-00119 9 12/20/2025
3.0.0-dev-00116 9 12/16/2025
3.0.0-dev-00113 9 01/03/2026
3.0.0-dev-00112 6 12/22/2025
3.0.0-dev-00111 6 01/03/2026
3.0.0-dev-00108 10 01/02/2026
3.0.0-dev-00103 9 01/09/2026
3.0.0-dev-00097 12 12/17/2025
3.0.0-dev-00093 9 12/17/2025
3.0.0-dev-00083 11 12/13/2025
2.6.1 11 12/29/2025
2.6.0 10 12/10/2025
2.6.0-dev-00081 9 01/04/2026
2.5.1-dev-00078 9 12/13/2025
2.5.0 9 01/05/2026
2.4.1-dev-00072 13 12/28/2025
2.4.1-dev-00070 12 12/13/2025
2.4.1-dev-00063 8 01/10/2026
2.4.1-dev-00061 9 12/21/2025
2.4.0 13 12/15/2025
2.4.0-dev-00057 12 01/04/2026
2.4.0-dev-00055 12 12/13/2025
2.3.2-dev-00054 10 12/13/2025
2.3.1 13 12/10/2025
2.3.1-dev-00049 8 12/23/2025
2.3.0 6 12/15/2025
2.3.0-dev-00044 7 12/23/2025
2.3.0-dev-00042 11 01/04/2026
2.2.1-dev-00041 10 12/28/2025
2.2.0 12 12/12/2025
2.2.0-dev-00035 8 01/07/2026
2.1.0 10 12/30/2025
2.1.0-dev-00028 12 01/06/2026
2.1.0-dev-00026 14 12/13/2025
2.0.0 10 12/13/2025
2.0.0-rc-8 10 12/21/2025
2.0.0-rc-21 8 12/13/2025
2.0.0-rc-19 11 12/20/2025
2.0.0-rc-17 9 12/21/2025
2.0.0-rc-15 10 12/13/2025
2.0.0-rc-13 11 12/13/2025
2.0.0-beta-6 14 12/21/2025
2.0.0-beta-5 14 12/13/2025
2.0.0-beta-4 11 12/21/2025