- Notifications
You must be signed in to change notification settings - Fork0
A Serilog configuration provider that reads from Microsoft.Extensions.Configuration
License
Numpsy/serilog-settings-configuration
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
A Serilog settings provider that reads fromMicrosoft.Extensions.Configuration sources, including .NET Core'sappsettings.json file.
By default, configuration is read from theSerilog section that should be at thetop level of the configuration file.
{"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, useReadFrom.Configuration() and pass anIConfiguration object.
staticvoidMain(string[]args){varconfiguration=newConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")??"Production"}.json",true).Build();varlogger=newLoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();logger.Information("Hello, world!");}
This example relies on theMicrosoft.Extensions.Configuration.Json,Serilog.Sinks.Console,Serilog.Sinks.File,Serilog.Enrichers.Environment andSerilog.Enrichers.Thread packages also being installed.
For a more sophisticated example go to thesample folder.
Root section name can be changed:
{"CustomSection":{...}}
varoptions=newConfigurationReaderOptions{SectionName="CustomSection"};varlogger=newLoggerConfiguration().ReadFrom.Configuration(configuration,options).CreateLogger();
Using section contains list ofassemblies 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 usingMicrosoft.Extensions.DependencyModel to find any package among dependencies withSerilog anywhere in the name and pulls configuration methods from it, so theUsing 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 specifyPreserveCompilationContext totrue in the csproj properties:
<PropertyGroupCondition=" '$(TargetFramework)' == 'net46'"> <PreserveCompilationContext>true</PreserveCompilationContext></PropertyGroup>
In case ofnon-standard dependency management you can pass a customDependencyContext object:
varfunctionDependencyContext=DependencyContext.Load(typeof(Startup).Assembly);varoptions=newConfigurationReaderOptions(functionDependencyContext){SectionName="AzureFunctionsJobHost:Serilog"};varlogger=newLoggerConfiguration().ReadFrom.Configuration(hostConfig,options).CreateLogger();
Alternatively, you can also pass an array of configuration assemblies:
varconfigurationAssemblies=new[]{typeof(ConsoleLoggerConfigurationExtensions).Assembly,typeof(FileLoggerConfigurationExtensions).Assembly,};varoptions=newConfigurationReaderOptions(configurationAssemblies);varlogger=newLoggerConfiguration().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 namesDO useUsing section.
Currently, auto-discovery of configuration assemblies is not supported in bundled mode.DO useUsing section or explicitly pass a collection of configuration assemblies for workaround.
TheMinimumLevel 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.
varconfiguration=newConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path:"appsettings.json",reloadOnChange:true).Build();
Any changes forDefault,Microsoft,System sources will be applied at runtime.
(Note: only existing sources are respected for a dynamic update. Inserting new records inOverride section isnot supported.)
You can also declareLoggingLevelSwitch-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:
varallSwitches=newDictionary<string,LoggingLevelSwitch>();varoptions=newConfigurationReaderOptions{OnLevelSwitchCreated=(switchName,levelSwitch)=>allSwitches[switchName]=levelSwitch};varlogger=newLoggerConfiguration().ReadFrom.Configuration(configuration,options).CreateLogger();LoggingLevelSwitchcontrolSwitch=allSwitches["$controlSwitch"];
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.
ByMicrosoft.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 andSerilog:WriteTo:1)
When overriding settings withenvironment variables it becomes less convenient and fragile, so you can specify custom names:
"WriteTo":{"ConsoleSink":"Console","DiagnosticTraceSink":{ "Name": "DiagnosticTrace" }}
This section defines a static list of key-value pairs that will enrich log events.
This section defines filters that will be applied to log events. It is especially useful in combination withSerilog.Expressions (or legacySerilog.Filters.Expressions) package so you can write expression in text form:
"Filter":[{"Name":"ByIncludingOnly","Args":{"expression":"Application = 'Sample'"}}]
Using this package you can also declareLoggingFilterSwitch-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:
varfilterSwitches=newDictionary<string,ILoggingFilterSwitch>();varoptions=newConfigurationReaderOptions{OnFilterSwitchCreated=(switchName,filterSwitch)=>filterSwitches[switchName]=filterSwitch};varlogger=newLoggerConfiguration().ReadFrom.Configuration(configuration,options).CreateLogger();ILoggingFilterSwitchfilterSwitch=filterSwitches["filterSwitch"];
Some Serilog packages require a reference to a logger configuration object. The sample program in this project illustrates this with the following entry configuring theSerilog.Sinks.Async package to wrap theSerilog.Sinks.File package. Theconfigure 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 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":"MySecondNamespace.SecondDestructuringPolicy, MySecondAssembly"}},{"Name":"With","Args":{"policy":"MyThirdNamespace.ThirdDestructuringPolicy, MyThirdAssembly"}},],
This is how the first destructuring policy would look like:
namespaceMyFirstNamespace;publicrecordMyDto(intId,intName);publicclassFirstDestructuringPolicy:IDestructuringPolicy{publicboolTryDestructure(objectvalue,ILogEventPropertyValueFactorypropertyValueFactory,[NotNullWhen(true)]outLogEventPropertyValue?result){if(valueis notMyDtodto){result=null;returnfalse;}result=newStructureValue(newList<LogEventProperty>{newLogEventProperty("Identifier",newScalarValue(deleteTodoItemInfo.Id)),newLogEventProperty("NormalizedName",newScalarValue(dto.Name.ToUpperInvariant()))});returntrue;}}
Assuming Serilog needs to destructure an argument of typeMyDto when handling a log event:
logger.Information("About to process input: {@MyDto} ...",myDto);
it will applyFirstDestructuringPolicy which will convertMyDto instance to aStructureValue instance; a Serilog console sink would write the following entry:
About to process input: {"Identifier": 191, "NormalizedName": "SOME_UPPER_CASE_NAME"} ...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 toUri,TimeSpan,enum, arrays and custom collections.
Since version 7.0.0, conversion will use the invariant culture (CultureInfo.InvariantCulture) as long as theReadFrom.Configuration(IConfiguration configuration, ConfigurationReaderOptions options) method is used. Obsolete methods use the current culture to preserve backward compatibility.
Static member access can be used for passing to the configuration argument viaspecial syntax:
{"Args":{"encoding":"System.Text.Encoding::UTF8","theme":"Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console"}}
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 byMicrosoft.Extensions.Options.ConfigurationExtensions to attempt to populate the parameter. Almost anything that can be bound byIConfiguration.Get<T> should work with this package. An example of this is the optionalList<Column> parameter used to configure the .NET Standard version of theSerilog.Sinks.MSSqlServer package.
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" } },...],
If a Serilog package requires additional external configuration information (for example, access to aConnectionStrings section, which would be outside of theSerilog section), the sink should include anIConfiguration 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.
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 entireIConfigurationSection 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.
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" } } ] }}InStartup.cs section name should be prefixed withAzureFunctionsJobHost
publicclassStartup:FunctionsStartup{publicoverridevoidConfigure(IFunctionsHostBuilderbuilder){builder.Services.AddSingleton<ILoggerProvider>(sp=>{varfunctionDependencyContext=DependencyContext.Load(typeof(Startup).Assembly);varhostConfig=sp.GetRequiredService<IConfiguration>();varoptions=newConfigurationReaderOptions(functionDependencyContext){SectionName="AzureFunctionsJobHost:Serilog"};varlogger=newLoggerConfiguration().ReadFrom.Configuration(hostConfig,options).CreateLogger();returnnewSerilogLoggerProvider(logger,dispose:true);});}}
In order to make auto-discovery of configuration assemblies work, modify Function's csproj file
<ProjectSdk="Microsoft.NET.Sdk"><!-- ...--><!-- add this targets--> <TargetName="FunctionsPostBuildDepsCopy"AfterTargets="PostBuildEvent"> <CopySourceFiles="$(OutDir)$(AssemblyName).deps.json"DestinationFiles="$(OutDir)bin\$(AssemblyName).deps.json" /> </Target> <TargetName="FunctionsPublishDepsCopy"AfterTargets="Publish"> <CopySourceFiles="$(OutDir)$(AssemblyName).deps.json"DestinationFiles="$(PublishDir)bin\$(AssemblyName).deps.json" /> </Target></Project>
This package tracks the versioning and target framework support of itsMicrosoft.Extensions.Configuration dependency.
About
A Serilog configuration provider that reads from Microsoft.Extensions.Configuration
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Languages
- C#99.3%
- PowerShell0.7%