• Stars
    star
    503
  • Rank 87,705 (Top 2 %)
  • Language
    C#
  • License
    MIT License
  • Created about 9 years ago
  • Updated 4 months ago

Reviews

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

Repository Details

Log exception details and custom properties that are not output in Exception.ToString().

Serilog.Exceptions Banner

Serilog.Exceptions NuGet Package Serilog.Exceptions package in serilog-exceptions feed in Azure Artifacts Serilog.Exceptions NuGet Package Downloads Twitter URL Twitter Follow

Serilog.Exceptions is an add-on to Serilog to log exception details and custom properties that are not output in Exception.ToString().

What Does It Do?

Your JSON logs will now be supplemented with detailed exception information and even custom exception properties. Here is an example of what happens when you log a DbEntityValidationException from EntityFramework (This exception is notorious for having deeply nested custom properties which are not included in the .ToString()).

try
{
    ...
}
catch (DbEntityValidationException exception)
{
    logger.Error(exception, "Hello World");
}

The code above logs the following:

{
  "Timestamp": "2015-12-07T12:26:24.0557671+00:00",
  "Level": "Error",
  "MessageTemplate": "Hello World",
  "RenderedMessage": "Hello World",
  "Exception": "System.Data.Entity.Validation.DbEntityValidationException: Message",
  "Properties": {
    "ExceptionDetail": {
      "EntityValidationErrors": [
        {
          "Entry": null,
          "ValidationErrors": [
            {
              "PropertyName": "PropertyName",
              "ErrorMessage": "PropertyName is Required.",
              "Type": "System.Data.Entity.Validation.DbValidationError"
            }
          ],
          "IsValid": false,
          "Type": "System.Data.Entity.Validation.DbEntityValidationResult"
        }
      ],
      "Message": "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.",
      "Data": {},
      "InnerException": null,
      "TargetSite": null,
      "StackTrace": null,
      "HelpLink": null,
      "Source": null,
      "HResult": -2146232032,
      "Type": "System.Data.Entity.Validation.DbEntityValidationException"
    },
    "Source": "418169ff-e65f-456e-8b0d-42a0973c3577"
  }
}

Getting Started

Warning Entity Framework Core Users: If you are using Entity Framework with Serilog.Exceptions you should read the following instructions.

Add the Serilog.Exceptions NuGet package to your project using the NuGet Package Manager or run the following command in the Package Console Window:

dotnet add package Serilog.Exceptions

When setting up your logger, add the WithExceptionDetails() line like so:

using Serilog;
using Serilog.Exceptions;

ILogger logger = new LoggerConfiguration()
    .Enrich.WithExceptionDetails()
    .WriteTo.RollingFile(
        new JsonFormatter(renderMessage: true), 
        @"C:\logs\log-{Date}.txt")    
    .CreateLogger();

Make sure that the sink's formatter outputs enriched properties. Serilog.Sinks.Console and many more do not do that by default. You may need to add {Properties:j} to your sink's format template. For example, configuration for console sink may look like that:

.WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception} {Properties:j}")

JSON appSettings.json configuration

Alternatively to fluent configuration setting can be stored in application configuration using Serilog.Settings.Configuration:

{
  "Serilog": {
    "Using": [ "Serilog.Exceptions" ],
    "Enrich": [ "WithExceptionDetails" ],
    "WriteTo": [
      { "Name": "Console" }
    ]
  }
}

Performance

This library has custom code to deal with extra properties on most common exception types and only falls back to using reflection to get the extra information if the exception is not supported by Serilog.Exceptions internally. Reflection overhead is present but minimal, because all the expensive relection-based operations are done only once per exception-type.

Additional Destructurers

Serilog.Exceptions.SqlServer

Serilog.Exceptions.SqlServer NuGet Package Serilog.Exceptions.SqlServer package in serilog-exceptions feed in Azure Artifacts Serilog.Exceptions.SqlServer NuGet Package Downloads

Add the Serilog.Exceptions.SqlServer NuGet package to your project to avoid the reflection based destructurer for SqlException when using System.Data.SqlClient:

dotnet add package Serilog.Exceptions.SqlServer

Add the SqlExceptionDestructurer during setup:

.Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
    .WithDefaultDestructurers()
    .WithDestructurers(new[] { new SqlExceptionDestructurer() }))

Serilog.Exceptions.MsSqlServer

Serilog.Exceptions.MsSqlServer NuGet Package Serilog.Exceptions.MsSqlServer package in serilog-exceptions feed in Azure Artifacts Serilog.Exceptions.MsSqlServer NuGet Package Downloads

Add the Serilog.Exceptions.MsSqlServer NuGet package to your project to avoid the reflection based destructurer for SqlException when using Microsoft.Data.SqlClient:

dotnet add package Serilog.Exceptions.MsSqlServer

Add the SqlExceptionDestructurer during setup:

.Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
    .WithDefaultDestructurers()
    .WithDestructurers(new[] { new SqlExceptionDestructurer() }))

Serilog.Exceptions.EntityFrameworkCore

Serilog.Exceptions.EntityFrameworkCore NuGet Package Serilog.Exceptions.EntityFrameworkCore package in serilog-exceptions feed in Azure Artifacts Serilog.Exceptions.EntityFrameworkCore NuGet Package Downloads

Warning If you are using Entity Framework with Serilog.Exceptions you must follow the instructions below, otherwise in certain cases your entire database will be logged! This is because the exceptions in Entity Framework have properties that link to the entire database schema in them (See #100, aspnet/EntityFrameworkCore#15214). Version 8 or newer of Serilog.Exceptions reduces the problem by preventing the destructure of properties that implement IQueryable but the rest of the DbContext object will still get logged.

Add the Serilog.Exceptions.EntityFrameworkCore NuGet package to your project when using EntityFrameworkCore in your project

dotnet add package Serilog.Exceptions.EntityFrameworkCore

Add the DbUpdateExceptionDestructurer during setup:

.Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
    .WithDefaultDestructurers()
    .WithDestructurers(new[] { new DbUpdateExceptionDestructurer() }))

Serilog.Exceptions.Refit

Serilog.Exceptions.Refit NuGet Package Serilog.Exceptions.Refit package in serilog-exceptions feed in Azure Artifacts Serilog.Exceptions.Refit NuGet Package Downloads

Add the Serilog.Exceptions.Refit NuGet package to your project to provide detailed logging for the ApiException when using Refit:

dotnet add package Serilog.Exceptions.Refit

Add the ApiExceptionDestructurer during setup:

.Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
    .WithDefaultDestructurers()
    .WithDestructurers(new[] { new ApiExceptionDestructurer() }))

Depending on your Serilog setup, common System.Exception properties may already be logged. To omit the logging of these properties, use the overloaded constructor as follows:

.Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
    .WithDefaultDestructurers()
    .WithDestructurers(new[] { new ApiExceptionDestructurer(destructureCommonExceptionProperties: false) }))

The default configuration logs the following properties of an ApiException:

  • Uri
  • StatusCode

In addition, the ApiException.Content property can be logged with the following setup:

.Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
    .WithDefaultDestructurers()
    .WithDestructurers(new[] { new ApiExceptionDestructurer(destructureHttpContent: true) }))

Be careful with this option as the HTTP body could be very large and/or contain sensitive information.

Serilog.Exceptions.Grpc

Serilog.Exceptions.Grpc NuGet Package Serilog.Exceptions.Grpc package in serilog-exceptions feed in Azure Artifacts Serilog.Exceptions.Grpc NuGet Package Downloads

Add the Serilog.Exceptions.Grpc NuGet package to your project to avoid the reflection based destructurer for RpcException when using Grpc.Net.Client:

dotnet add package Serilog.Exceptions.Grpc

Add the RpcExceptionDestructurer during setup:

.Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
    .WithDefaultDestructurers()
    .WithDestructurers(new[] { new RpcExceptionDestructurer() }))

Custom Exception Destructurers

You may want to add support for destructuring your own exceptions without relying on reflection. To do this, create your own destructuring class implementing ExceptionDestructurer (You can take a look at this for ArgumentException), then simply add it like so:

.Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
    .WithDefaultDestructurers()
    .WithDestructurers(new[] { new MyCustomExceptionDestructurer() }))

If you write a destructurer that is not included in this project (even for a third party library), please contribute it.

Additional configuration

You can configure some additional properties of destructuring process, by passing custom destructuring options during setup:

.Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
    .WithDefaultDestructurers()
    .WithRootName("Exception"))

Currently following options are supported:

  • RootName: The property name which will hold destructured exception, ExceptionDetail by default.
  • Filter: The object implementing IExceptionPropertyFilter that will have a chance to filter properties just before they are put in destructured exception object. Go to "Filtering properties" section for details.
  • DestructuringDepth: The maximum depth of reflection based recursive destructuring process.
  • ReflectionBasedDestructurer: Reflection based destructurer is enabled by default, but can be disabled in case you want to have complete control over destructuring process. You will have to register destructurers for all exceptions explicitly.

Filtering properties

You may want to skip some properties of all or part your exception classes without directly creating or modifying custom destructurers. Serilog.Exceptions supports this functionality using a filter.

Most typical use case is the need to skip StackTrace and TargetSite. Serilog is already reporting them so you may want Serilog.Exceptions to skip them to save space and processing time. To do that you just need to modify a line in configuration:

.Enrich.WithExceptionDetails(new DestructuringOptionsBuilder().WithFilter(someFilter));

Filtering for other scenarios is also supported:

  • Use WithIgnoreStackTraceAndTargetSiteExceptionFilter if you need to filter some other set of named properties
  • Implement custom IExceptionPropertyFilter if you need some different filtering logic
  • Use CompositeExceptionPropertyFilter to combine multiple filters

Continuous Integration

Name Operating System Status History
Azure Pipelines Ubuntu Azure Pipelines Ubuntu Build Status
Azure Pipelines Mac Azure Pipelines Mac Build Status
Azure Pipelines Windows Azure Pipelines Windows Build Status
Azure Pipelines Overall Azure Pipelines Overall Build Status Azure DevOps Build History
GitHub Actions Ubuntu, Mac & Windows GitHub Actions Status GitHub Actions Build History
AppVeyor Ubuntu, Mac & Windows AppVeyor Build Status AppVeyor Build History

Contributions and Thanks

Please view the contributing guide for more information.

  • 304NotModified - Added Markdown syntax highlighting.
  • joelweiss - Added Entity Framework Core destructurers.
  • krajek & JeroenDragt - For adding filters to help ignore exception properties you don't want logged.
  • krajek - For helping with cyclic dependencies when using the reflection destructurer.
  • mraming - For logging properties that throw exceptions.
  • optical - For a huge VS 2017 upgrade PR.
  • JΓ©rΓ©mie Bertrand - For making Serilog.Exceptions compatible with Mono.
  • krajek - For writing some much needed unit tests.

More Repositories

1

EditorConfig

A very generic .editorconfig file supporting .NET, C#, VB and web technologies.
627
star
2

Schema.NET

Schema.org objects turned into strongly typed C# POCO classes for use in .NET. All classes can be serialized into JSON/JSON-LD and XML, typically used to represent structured data in the head section of html page.
C#
586
star
3

.NET-Big-O-Algorithm-Complexity-Cheat-Sheet

Big-O complexities of common algorithms used in .NET and Computer Science.
HTML
383
star
4

Bash-Cheat-Sheet

A cheat sheet for bash commands.
369
star
5

Kubernetes-Cheat-Sheet

A cheat sheet for Kubernetes commands.
157
star
6

Serilog.Enrichers.Span

Enrich Serilog log events with properties from Open Telemetry spans.
C#
79
star
7

Helm-Cheat-Sheet

A cheat sheet for Helm commands.
73
star
8

Elysium-Extra

Elysium Extra is a library that implements Metro style for Windows Presentation Foundation (WPF) applications. This Project is a very large add-on project built on top of the Elysium SDK.
C#
67
star
9

Git-Cheat-Sheet

A cheat sheet for uncommon Git commands.
PowerShell
41
star
10

rehansaeed.github.io

Muhammad Rehan Saeed's Blog
Vue
28
star
11

Windows

Get a new Windows machine started quickly by installing everthing a developer needs.
PowerShell
17
star
12

MVVM-Design-Patterns

Showcasing the design patterns you can use alongside Model-View-ViewModel (MVVM).
C#
15
star
13

ReadOnlyDockerTest

Repro for using --read-only flag in Docker with ASP.NET Core
C#
10
star
14

OrleansAdventure

Demo project using Microsoft Orleans.
C#
9
star
15

MakeCertificate

Makes certificate files by answering a few simple questions.
PowerShell
9
star
16

NotificationsExtensions.Portable

Used to Create Windows 8.1/10 or Windows Phone 8.1/10 Tile, Toast and Badge Notification XML.
C#
7
star
17

Inversion-of-Control

Samples showing how Inversion of Control (IoC) containers work and some of their more advanced features.
C#
5
star
18

PulumiSample

C#
4
star
19

SnowflakeId

C#
4
star
20

PowerShell-Cheat-Sheet

A cheat sheet for PowerShell and Windows commands.
3
star
21

UpdateSocialMedia

Creates posts on social media for a new YouTube video or blog post.
C#
3
star
22

RehanSaeed

About Muhammad Rehan Saeed
2
star
23

Shooter

A J2ME game I made in 2006.
Java
2
star
24

SpaceInvaders

A flash game I made for an interview in 2006.
AngelScript
1
star
25

FastestApi

C#
1
star
26

FastestNuGet

C#
1
star