Skip to content

Commit

Permalink
Merge pull request #112 from serilog/dev
Browse files Browse the repository at this point in the history
3.0 Release
  • Loading branch information
nblumhardt authored Oct 7, 2018
2 parents d503eec + 9f28bbc commit 51a4fca
Show file tree
Hide file tree
Showing 31 changed files with 1,433 additions and 221 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ bld/
# Visual Studo 2015 cache/options directory
.vs/

# JetBrains project files
.idea/

# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
Expand Down Expand Up @@ -196,3 +199,6 @@ FakesAssemblies/
*.opt

project.lock.json

#Test files
*.txt
11 changes: 11 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
language: csharp

matrix:
include:
- os: linux
dist: trusty
sudo: required
dotnet: 2.1.4
group: edge
script:
- ./build.sh
50 changes: 46 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,27 @@ Configuration is read from the `Serilog` section.
```json
{
"Serilog": {
"Using": ["Serilog.Sinks.Literate"],
"Using": ["Serilog.Sinks.Console"],
"MinimumLevel": "Debug",
"WriteTo": [
{ "Name": "LiterateConsole" },
{ "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.Literate_, _Serilog.Sinks.File_, _Serilog.Enrichers.Environment_, _Serilog.Settings.Configuration_ and _Serilog.Enrichers.Thread_ packages also being installed.
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.

Expand All @@ -46,7 +52,7 @@ public class Program
The `WriteTo` and `Enrich` sections support the same syntax, for example the following is valid if no arguments are needed by the sinks:

```json
"WriteTo": ["LiterateConsole", "DiagnosticTrace"]
"WriteTo": ["Console", "DiagnosticTrace"]
```

Or alternatively, the long-form (`"Name":` ...) syntax from the first example can be used when arguments need to be supplied.
Expand Down Expand Up @@ -91,3 +97,39 @@ 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:

```json
"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.

10 changes: 2 additions & 8 deletions appveyor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,6 @@ version: '{build}'
skip_tags: true
image: Visual Studio 2017
configuration: Release
install:
- ps: mkdir -Force ".\build\" | Out-Null
- ps: Invoke-WebRequest "https://raw.githubusercontent.com/dotnet/cli/rel/1.0.0/scripts/obtain/dotnet-install.ps1" -OutFile ".\build\installcli.ps1"
- ps: $env:DOTNET_INSTALL_DIR = "$pwd\.dotnetcli"
- ps: '& .\build\installcli.ps1 -InstallDir "$env:DOTNET_INSTALL_DIR" -NoPath -Version 1.0.1'
- ps: $env:Path = "$env:DOTNET_INSTALL_DIR;$env:Path"
build_script:
- ps: ./Build.ps1
test: off
Expand All @@ -16,7 +10,7 @@ artifacts:
deploy:
- provider: NuGet
api_key:
secure: nvZ/z+pMS91b3kG4DgfES5AcmwwGoBYQxr9kp4XiJHj25SAlgdIxFx++1N0lFH2x
secure: bd9z4P73oltOXudAjPehwp9iDKsPtC+HbgshOrSgoyQKr5xVK+bxJQngrDJkHdY8
skip_symbols: true
on:
branch: /^(master|dev)$/
Expand All @@ -26,4 +20,4 @@ deploy:
artifact: /Serilog.*\.nupkg/
tag: v$(appveyor_build_version)
on:
branch: master
branch: master
17 changes: 17 additions & 0 deletions build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/bin/bash

set -e
dotnet --info
dotnet restore

for path in src/**/*.csproj; do
dotnet build -f netstandard2.0 -c Release ${path}
done

for path in test/*.Tests/*.csproj; do
dotnet test -f netcoreapp2.0 -c Release ${path}
done

cd sample/Sample/
dotnet build -f netcoreapp2.0 -c Release
dotnet bin/Release/netcoreapp2.0/Sample.dll --run-once
48 changes: 45 additions & 3 deletions sample/Sample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
using Microsoft.Extensions.Configuration;
using Serilog;
using System.IO;

using System.Linq;
using Serilog.Core;
using Serilog.Events;
using System.Collections.Generic;

namespace Sample
{
Expand All @@ -22,6 +23,8 @@ public static void Main(string[] args)
.ReadFrom.Configuration(configuration)
.CreateLogger();

logger.Information("Args: {a}", args);

do
{
logger.ForContext<Program>().Information("Hello, world!");
Expand All @@ -30,17 +33,56 @@ public static void Main(string[] args)
logger.ForContext(Constants.SourceContextPropertyName, "Microsoft").Error("Hello, world!");
logger.ForContext(Constants.SourceContextPropertyName, "MyApp.Something.Tricky").Verbose("Hello, world!");

Console.WriteLine();
logger.Information("Destructure with max object nesting depth:\n{@NestedObject}",
new { FiveDeep = new { Two = new { Three = new { Four = new { Five = "the end" } } } } });

logger.Information("Destructure with max string length:\n{@LongString}",
new { TwentyChars = "0123456789abcdefghij" });

logger.Information("Destructure with max collection count:\n{@BigData}",
new { TenItems = new[] { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" } });

logger.Information("Destructure with policy to strip password:\n{@LoginData}",
new LoginData { Username = "BGates", Password = "isityearoflinuxyet" });

Console.WriteLine("\nPress \"q\" to quit, or any other key to run again.\n");
}
while (Console.ReadKey().KeyChar != 'q');
while(!args.Contains("--run-once") && (Console.ReadKey().KeyChar != 'q'));
}
}

// The filter syntax in the sample configuration file is
// processed by the Serilog.Filters.Expressions package.
public class CustomFilter : ILogEventFilter
{
public bool IsEnabled(LogEvent logEvent)
{
return true;
}
}

public class LoginData
{
public string Username;
public string Password;
}

public class CustomPolicy : IDestructuringPolicy
{
public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue result)
{
result = null;

if(value is LoginData)
{
result = new StructureValue(
new List<LogEventProperty>
{
new LogEventProperty("Username", new ScalarValue(((LoginData)value).Username))
});
}

return (result != null);
}
}
}
11 changes: 9 additions & 2 deletions sample/Sample/Sample.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net46;netcoreapp1.0</TargetFrameworks>
<TargetFrameworks>net46;netcoreapp2.0</TargetFrameworks>
<OutputType>Exe</OutputType>
</PropertyGroup>

Expand All @@ -13,8 +13,15 @@
<ProjectReference Include="..\..\src\Serilog.Settings.Configuration\Serilog.Settings.Configuration.csproj" />
</ItemGroup>

<ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net46'">
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp2.0'">
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.0.1" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Serilog.Sinks.Async" Version="1.0.1" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.0.0" />
Expand Down
18 changes: 18 additions & 0 deletions sample/Sample/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,24 @@
"Properties": {
"Application": "Sample"
},
"Destructure": [
{
"Name": "With",
"Args": { "policy": "Sample.CustomPolicy, Sample" }
},
{
"Name": "ToMaximumDepth",
"Args": { "maximumDestructuringDepth": 3 }
},
{
"Name": "ToMaximumStringLength",
"Args": { "maximumStringLength": 10 }
},
{
"Name": "ToMaximumCollectionCount",
"Args": { "maximumCollectionCount": 5 }
}
],
"Filter": [
{
"Name": "ByIncludingOnly",
Expand Down
Loading

0 comments on commit 51a4fca

Please sign in to comment.