• Stars
    star
    124
  • Rank 279,321 (Top 6 %)
  • Language
    C#
  • License
    Apache License 2.0
  • Created about 6 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Serilog logging for Microsoft.Extensions.Hosting

Serilog.Extensions.Hosting Build status NuGet Version

Serilog logging for Microsoft.Extensions.Hosting. This package routes framework log messages through Serilog, so you can get information about the framework's internal operations written to the same Serilog sinks as your application events.

ASP.NET Core applications should consider using Serilog.AspNetCore instead, which bundles this package and includes other ASP.NET Core-specific features.

Instructions

First, install the Serilog.Extensions.Hosting NuGet package into your app. You will need a way to view the log messages - Serilog.Sinks.Console writes these to the console; there are many more sinks available on NuGet.

dotnet add package Serilog.Extensions.Hosting
dotnet add package Serilog.Sinks.Console

Next, in your application's Program.cs file, configure Serilog first. A try/catch block will ensure any configuration issues are appropriately logged:

public class Program
{
    public static int Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .Enrich.FromLogContext()
            .WriteTo.Console()
            .CreateLogger();

        try
        {
            Log.Information("Starting host");
            BuildHost(args).Run();
            return 0;
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly");
            return 1;
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

Then, add UseSerilog() to the host builder in BuildHost().

    public static IHost BuildHost(string[] args) =>
        new HostBuilder()
            .ConfigureServices(services => services.AddSingleton<IHostedService, PrintTimeService>())
            .UseSerilog() // <- Add this line
            .Build();
}

Finally, clean up by removing the remaining "Logging" section from appsettings.json files (this can be replaced with Serilog configuration as shown in this example, if required)

That's it! You will see log output like:

[22:10:39 INF] Getting the motors running...
[22:10:39 INF] The current time is: 12/05/2018 10:10:39 +00:00

A more complete example, showing appsettings.json configuration, can be found in the sample project here.

Using the package

With Serilog.Extensions.Hosting installed and configured, you can write log messages directly through Serilog or any ILogger interface injected by .NET. All loggers will use the same underlying implementation, levels, and destinations.

Tip: change the minimum level for Microsoft to Warning

Inline initialization

You can alternatively configure Serilog using a delegate as shown below:

    // dotnet add package Serilog.Settings.Configuration
    .UseSerilog((hostingContext, services, loggerConfiguration) => loggerConfiguration
        .ReadFrom.Configuration(hostingContext.Configuration)
        .Enrich.FromLogContext()
        .WriteTo.Console())

This has the advantage of making the hostingContext's Configuration object available for configuration of the logger, but at the expense of ignoring Exceptions raised earlier in program startup.

If this method is used, Log.Logger is assigned implicitly, and closed when the app is shut down.

Versioning

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

More Repositories

1

serilog

Simple .NET logging with fully-structured events
C#
6,857
star
2

serilog-aspnetcore

Serilog integration for ASP.NET Core
C#
1,250
star
3

serilog-settings-configuration

A Serilog configuration provider that reads from Microsoft.Extensions.Configuration
C#
418
star
4

serilog-sinks-file

Write Serilog events to files in text and JSON formats, optionally rolling on time or size
C#
314
star
5

serilog-extensions-logging

Serilog provider for Microsoft.Extensions.Logging
C#
301
star
6

serilog-sinks-console

Write log events to System.Console as text or JSON, with ANSI theme support
C#
223
star
7

serilog-sinks-async

An asynchronous wrapper for Serilog sinks that logs on a background thread
C#
216
star
8

serilog-expressions

An embeddable mini-language for filtering, enriching, and formatting Serilog events, ideal for use with JSON or XML configuration.
C#
170
star
9

serilog-sinks-mssqlserver

A Serilog sink that writes events to Microsoft SQL Server
C#
169
star
10

serilog-extensions-logging-file

Add file logging to ASP.NET Core apps in one line of code.
C#
148
star
11

serilog-formatting-compact

Compact JSON event format for Serilog
C#
139
star
12

serilog-sinks-opentelemetry

Serilog to OpenTelemetry Logs sink
C#
87
star
13

serilog-filters-expressions

Expression-based event filtering for Serilog
C#
80
star
14

serilog-enrichers-environment

Enrich Serilog log events with properties from System.Environment.
C#
71
star
15

serilog-sinks-email

A Serilog sink that writes events to SMTP email
C#
68
star
16

serilog-sinks-periodicbatching

Infrastructure for Serilog sinks that process events in batches.
C#
65
star
17

serilog-sinks-browserconsole

A console sink for the Blazor/Wasm environment
C#
60
star
18

serilog-sinks-rollingfile

Deprecated: new applications should use https://github.com/serilog/serilog-sinks-file instead
C#
59
star
19

serilog-sinks-xamarin

A Serilog sink that writes events to Xamarin mobile targets
C#
53
star
20

serilog-settings-appsettings

An <appSettings> configuration reader for Serilog
C#
50
star
21

serilog-sinks-eventlog

A Serilog sink that writes events to the Windows Event Log
C#
44
star
22

serilog-enrichers-thread

Enrich Serilog events with properties from the current thread.
C#
40
star
23

serilog-sinks-map

A Serilog sink wrapper that dispatches events based on a property value
C#
39
star
24

serilog-sinks-debug

Writes Serilog events to the debug output window
C#
31
star
25

serilog-sinks-loggly

A Serilog event sink that writes to Loggly
C#
27
star
26

serilog-formatting-compact-reader

A reader for Serilog's compact JSON format
C#
25
star
27

serilog-enrichers-process

The process enricher for Serilog.
C#
24
star
28

serilog-sinks-observable

Write Serilog events to observers (Rx) through an IObservable
C#
18
star
29

serilog-sinks-azuredocumentdb

A Serilog sink that writes to Azure DocumentDB
C#
17
star
30

serilog-sinks-amazonkinesis

A Serilog sink that logs to Amazon Kinesis
C#
14
star
31

serilog-sinks-signalr

A Serilog sink that writes events to SignalR
C#
14
star
32

serilog-sinks-log4net

A Serilog sink that writes events to log4net
C#
13
star
33

serilog-sinks-coloredconsole

Deprecated: now a part of https://github.com/serilog/serilog-sinks-console
C#
10
star
34

serilog-sinks-trace

The diagnostic trace sink for Serilog.
C#
10
star
35

serilog-sinks-datadog

A Serilog sink that writes events to DataDog
C#
9
star
36

serilog-sinks-logentries

A Serilog sink that writes events to Logentries
C#
8
star
37

serilog-sinks-nlog

A Serilog sink that writes events to NLog
C#
8
star
38

serilog-sinks-textwriter

The System.IO.TextWriter sink for Serilog
C#
8
star
39

serilog-generator

A simulation that generates simple log data through Serilog, ideal for testing sinks or log servers
C#
6
star
40

serilog-sinks-rethinkdb

A Serilog sink that writes to RethinkDB
C#
5
star
41

serilog-sinks-xsockets

A Serilog sink that writes events to XSockets
C#
4
star
42

serilog-sinks-reflectinsight

Writes events from Serilog to the ReflectInsight logging framework
C#
3
star
43

serilog-dnx-prerelease

Pre-release support for the DNX (.NET 5) runtime environment for Serilog
C#
3
star
44

serilog-sinks-dynamodb

A Serilog sink that writes events to Amazon Web Services DynamoDB
C#
1
star