Coder Social home page Coder Social logo

yydashixiong / serilog-settings-configuration Goto Github PK

View Code? Open in Web Editor NEW

This project forked from serilog/serilog-settings-configuration

0.0 1.0 0.0 496 KB

A Serilog configuration provider that reads from Microsoft.Extensions.Configuration

License: Apache License 2.0

PowerShell 0.96% Shell 0.25% C# 98.78%

serilog-settings-configuration's Introduction

Serilog.Settings.Configuration Build status NuGet Version

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

Configuration is read from the Serilog section.

{
  "Serilog": {
    "Using":  ["Serilog.Sinks.Console"],
    "MinimumLevel": "Debug",
    "WriteTo": [
      { "Name": "Console" },
      { "Name": "File", "Args": { "path": "%TEMP%\\Logs\\serilog-configuration-sample.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"
    }
  }
}

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

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

public class Program
{
    public static void Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();

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

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

The WriteTo and Enrich sections support the same 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 first example can be used when arguments need to be supplied.

(This package implements a convention using DependencyContext to find any package with Serilog anywhere in the name and pulls configuration methods from it, so the Using example above is redundant.)

.NET 4.x

To use this package in .NET 4.x applications, add preserveCompilationContext to buildOptions in project.json.

"net4.6": {
   "buildOptions": {
     "preserveCompilationContext": true
   }
},

Level overrides

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"
        }
    }

Environment variables

If your application enables the environment variable configuration source (AddEnvironmentVariables()) you can add or override Serilog configuration through the environment.

For example, to set the minimum log level using the Windows command prompt:

set Serilog:MinimumLevel=Debug
dotnet run

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}"
        }
      }
    ]
  }
},

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.

Complex parameter value 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 and TimeSpan objects and enum elements.

If the parameter value is not a discrete value, 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.

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.

serilog-settings-configuration's People

Contributors

nblumhardt avatar tsimbalar avatar mv10 avatar mrmon3y avatar merbla avatar nbaztec avatar khellang avatar adamchester avatar alastairs avatar elogicjp avatar fantasticfiasco avatar maximrouiller avatar sphiecoh avatar dougmoney avatar jayanthakgjls avatar

Watchers

Bryan avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.