diff --git a/README.md b/README.md index 720b5e34..796f9c46 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ catch (DbEntityValidationException exception) The code above logs the following: -``` +```json { "Timestamp": "2015-12-07T12:26:24.0557671+00:00", "Level": "Error", @@ -75,7 +75,7 @@ Install-Package Serilog.Exceptions When setting up your logger, add the `WithExceptionDetails()` line like so: -``` +```csharp using Serilog; using Serilog.Exceptions; @@ -97,11 +97,43 @@ Make sure that the sink's formatter outputs enriched properties. `Serilog.Sinks. 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. +## Additional Destructurers + +[![NuGet Package](https://img.shields.io/nuget/v/Serilog.Exceptions.SqlServer.svg)](https://www.nuget.org/packages/Serilog.Exceptions.SqlServer/) + +Add the [Serilog.Exceptions.SqlServer](https://www.nuget.org/packages/Serilog.Exceptions.SqlServer/) NuGet package to your project to avoid the reflection based destuctorer for `SqlException` + +``` +Install-Package Serilog.Exceptions.SqlServer +``` + +Add the `SqlExceptionDestructurer` during setup: +```csharp +.Enrich.WithExceptionDetails(new DestructuringOptionsBuilder().WithDefaultDestructurers().WithDestructurers(new[] { new SqlExceptionDestructurer() })) +``` + +--- + +[![NuGet Package](https://img.shields.io/nuget/v/Serilog.Exceptions.EntityFrameworkCore.svg)](https://www.nuget.org/packages/Serilog.Exceptions.EntityFrameworkCore/) + +> **WARNING**: If you are using EntityFrameworkCore with Serilog.Exceptions you must add this, otherwise in certain cases your entire database will be logged! (See [#100](https://github.com/RehanSaeed/Serilog.Exceptions/issues/100), [aspnet/EntityFrameworkCore#15214](https://github.com/aspnet/EntityFrameworkCore/issues/15214)) + +Add the [Serilog.Exceptions.EntityFrameworkCore](https://www.nuget.org/packages/Serilog.Exceptions.EntityFrameworkCore/) NuGet package to your project when using EntityFrameworkCore in your project + +``` +Install-Package Serilog.Exceptions.EntityFrameworkCore +``` + +Add the `DbUpdateExceptionDestructurer` during setup: +```csharp +.Enrich.WithExceptionDetails(new DestructuringOptionsBuilder().WithDefaultDestructurers().WithDestructurers(new[] { new DbUpdateExceptionDestructurer() })) +``` + ## 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](https://github.com/RehanSaeed/Serilog.Exceptions/blob/master/Source/Serilog.Exceptions/Destructurers/ArgumentExceptionDestructurer.cs) for `ArgumentException`), then simply add it like so: -``` +```csharp using Serilog; using Serilog.Exceptions; using Serilog.Formatting.Json; @@ -124,7 +156,7 @@ If you write a destructurer that is not included in this project (even for a thi You can configure some additional properties of destructuring process, by passing custom destructuring options during setup: -``` +```csharp .Enrich.WithExceptionDetails(new DestructuringOptionsBuilder().WithDefaultDestructurers().WithRootName("Exception")) ``` @@ -140,7 +172,7 @@ You may want to skip some properties of all or part your exception classes witho 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: -``` +```csharp .Enrich.WithExceptionDetails(new DestructuringOptionsBuilder().WithFilter(someFilter)); ``` diff --git a/Serilog.Exceptions.sln b/Serilog.Exceptions.sln index 1d4c9a00..12288421 100644 --- a/Serilog.Exceptions.sln +++ b/Serilog.Exceptions.sln @@ -39,6 +39,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Benchmarks", "Benchmarks", EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.Exceptions.Benchmark", "Benchmarks\Serilog.Exceptions.Benchmark\Serilog.Exceptions.Benchmark.csproj", "{5A82CFFC-EC33-4B7B-A6F6-7FADC0E2DDAA}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.Exceptions.EntityFrameworkCore", "Source\Serilog.Exceptions.EntityFrameworkCore\Serilog.Exceptions.EntityFrameworkCore.csproj", "{69C1004B-627D-4B90-8FAD-4B4069115A56}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -65,6 +67,10 @@ Global {5A82CFFC-EC33-4B7B-A6F6-7FADC0E2DDAA}.Debug|Any CPU.Build.0 = Debug|Any CPU {5A82CFFC-EC33-4B7B-A6F6-7FADC0E2DDAA}.Release|Any CPU.ActiveCfg = Release|Any CPU {5A82CFFC-EC33-4B7B-A6F6-7FADC0E2DDAA}.Release|Any CPU.Build.0 = Release|Any CPU + {69C1004B-627D-4B90-8FAD-4B4069115A56}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {69C1004B-627D-4B90-8FAD-4B4069115A56}.Debug|Any CPU.Build.0 = Debug|Any CPU + {69C1004B-627D-4B90-8FAD-4B4069115A56}.Release|Any CPU.ActiveCfg = Release|Any CPU + {69C1004B-627D-4B90-8FAD-4B4069115A56}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -75,6 +81,7 @@ Global {7C962929-2138-4787-ABA7-94E8D3F9C20C} = {D6E871A8-2DFF-4676-BED8-046B164919B9} {F5BBB5C1-5920-40F3-8C44-01A54CC3D6B7} = {C5508012-7216-4ABE-AB2F-B166ED5FF94F} {5A82CFFC-EC33-4B7B-A6F6-7FADC0E2DDAA} = {5CE72C42-F5C5-405B-BE8A-9AFDA7F43CB2} + {69C1004B-627D-4B90-8FAD-4B4069115A56} = {C5508012-7216-4ABE-AB2F-B166ED5FF94F} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {BE74AFAC-AC6F-4B80-860F-15C22BEE1A38} diff --git a/Source/Serilog.Exceptions.EntityFrameworkCore/Destructurers/DbUpdateExceptionDestructurer.cs b/Source/Serilog.Exceptions.EntityFrameworkCore/Destructurers/DbUpdateExceptionDestructurer.cs new file mode 100644 index 00000000..200f060e --- /dev/null +++ b/Source/Serilog.Exceptions.EntityFrameworkCore/Destructurers/DbUpdateExceptionDestructurer.cs @@ -0,0 +1,45 @@ +namespace Serilog.Exceptions.SqlServer.Destructurers +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Microsoft.EntityFrameworkCore; + using Serilog.Exceptions.Core; + using Serilog.Exceptions.Destructurers; + + /// + /// A destructurer for . + /// + /// + public class DbUpdateExceptionDestructurer : ExceptionDestructurer + { + /// + public override Type[] TargetTypes => new[] { typeof(DbUpdateException), typeof(DbUpdateConcurrencyException) }; + + /// + public override void Destructure( + Exception exception, + IExceptionPropertiesBag propertiesBag, + Func> destructureException) + { + base.Destructure(exception, propertiesBag, destructureException); + +#pragma warning disable CA1062 // Validate arguments of public methods + var dbUpdateException = (DbUpdateException)exception; + var entriesValue = dbUpdateException.Entries?.Select(e => new + { + EntryProperties = e.Properties.Select(p => new + { + PropertyName = p.Metadata.Name, + p.OriginalValue, + p.CurrentValue, + p.IsTemporary, + p.IsModified + }), + e.State + }).ToList(); + propertiesBag.AddProperty(nameof(DbUpdateException.Entries), entriesValue); +#pragma warning restore CA1062 // Validate arguments of public methods + } + } +} \ No newline at end of file diff --git a/Source/Serilog.Exceptions.EntityFrameworkCore/Properties/AssemblyInfo.cs b/Source/Serilog.Exceptions.EntityFrameworkCore/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..fb51532b --- /dev/null +++ b/Source/Serilog.Exceptions.EntityFrameworkCore/Properties/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Serilog.Exceptions.Test, PublicKey=00240000048000009400000006020000002400005253413100040000010001007320f17cde01a37b8b3dff91961943f76893c63352544608de15974586e17739e0b232cdc8cc8762b40d988a21522024abca8116605ed1c8958f350bc6ca4594aa1ca61c1906d85ee76df8d9b404ffd65a5f6efeddd486bddd5b74ff9a7449af0dc9d43da753a3023b20ca616e8313e82a18719b6551f37c45c8d8e4e4cf9bac")] \ No newline at end of file diff --git a/Source/Serilog.Exceptions.EntityFrameworkCore/Serilog.Exceptions.EntityFrameworkCore.csproj b/Source/Serilog.Exceptions.EntityFrameworkCore/Serilog.Exceptions.EntityFrameworkCore.csproj new file mode 100644 index 00000000..5d9f2d4e --- /dev/null +++ b/Source/Serilog.Exceptions.EntityFrameworkCore/Serilog.Exceptions.EntityFrameworkCore.csproj @@ -0,0 +1,54 @@ + + + + netstandard2.0;net461;net472 + ../../MinimumRecommendedRulesWithStyleCop.ruleset + true + latest + true + + + + 5.3.0 + Muhammad Rehan Saeed (RehanSaeed.com) + Serilog Exceptions + Log exception details and custom properties that are not output in Exception.ToString(). + Copyright © Muhammad Rehan Saeed. All rights Reserved + true + MIT + https://github.com/RehanSaeed/Serilog.Exceptions.EntityFrameworkCore + https://raw.githubusercontent.com/RehanSaeed/Serilog.Exceptions/master/Images/Serilog%20Community%20256x256.png + https://github.com/RehanSaeed/Serilog.Exceptions.git + git + Serilog;Exception;Log;Logging;Detail;Details + https://github.com/RehanSaeed/Serilog.Exceptions/releases + + + + true + ../../Key.snk + true + + + + + true + + true + + $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb + + + + + + + + + + + + + + + diff --git a/Source/Serilog.Exceptions/Destructurers/ReflectionBasedDestructurer.cs b/Source/Serilog.Exceptions/Destructurers/ReflectionBasedDestructurer.cs index 6f4d22b3..9e481d34 100644 --- a/Source/Serilog.Exceptions/Destructurers/ReflectionBasedDestructurer.cs +++ b/Source/Serilog.Exceptions/Destructurers/ReflectionBasedDestructurer.cs @@ -177,6 +177,7 @@ private ReflectionInfo GenerateReflectionInfoForType(Type valueType) var propertyInfos = properties.Select(p => new ReflectionPropertyInfo() { Name = p.Name, + DeclaringType = p.DeclaringType, Getter = GenerateFastGetterForProperty(valueType, p), }).ToArray(); var propertiesInfosExceptBaseOnes = propertyInfos @@ -335,7 +336,8 @@ private IDictionary DestructureObject( level + 1, destructuredObjects, ref nextCyclicRefId); - values.Add(property.Name, destructuredValue); + var key = values.ContainsKey(property.Name) ? $"{property.DeclaringType.FullName}.{property.Name}" : property.Name; + values.Add(key, destructuredValue); } catch (TargetInvocationException targetInvocationException) { @@ -431,6 +433,8 @@ private class ReflectionPropertyInfo { public string Name { get; set; } + public Type DeclaringType { get; set; } + public Func Getter { get; set; } } } diff --git a/Tests/Serilog.Exceptions.Test/Destructurers/DbUpdateExceptionDestructurerTest.cs b/Tests/Serilog.Exceptions.Test/Destructurers/DbUpdateExceptionDestructurerTest.cs new file mode 100644 index 00000000..7a10f9fe --- /dev/null +++ b/Tests/Serilog.Exceptions.Test/Destructurers/DbUpdateExceptionDestructurerTest.cs @@ -0,0 +1,115 @@ +namespace Serilog.Exceptions.Test.Destructurers +{ + using System; + using System.Collections.Generic; + using System.IO; + using FluentAssertions; + using Microsoft.EntityFrameworkCore; + using Microsoft.EntityFrameworkCore.ChangeTracking; + using Serilog.Exceptions.Core; + using Serilog.Exceptions.SqlServer.Destructurers; + using Serilog.Formatting.Json; + using Xunit; + using static LogJsonOutputUtils; + + public class DbUpdateExceptionDestructurerTest + { + [Fact] + public void WithoutDbUpdateExceptionDestructurerShouldLogDbValues() + { + // Arrange + var jsonWriter = new StringWriter(); + ILogger logger = new LoggerConfiguration() + .Enrich.WithExceptionDetails(new DestructuringOptionsBuilder().WithDefaultDestructurers()) + .WriteTo.Sink(new TestTextWriterSink(jsonWriter, new JsonFormatter())) + .CreateLogger(); + var ctx = new TestContext(); + ctx.Database.EnsureDeleted(); + ctx.Database.EnsureCreated(); + + var entry = ctx.Add(new User + { + UserId = Guid.NewGuid().ToString() + }); + + // Act + logger.Error(new TestDbUpdateException("DbUpdate Error", entry), "Error"); + + // Assert + var writtenJson = jsonWriter.ToString(); + writtenJson.Should().Contain(TestContext.UserIdIDoNotWantToSee); + } + + [Fact] + public void WithDbUpdateExceptionDestructurerShouldNotLogDbValues() + { + // Arrange + var jsonWriter = new StringWriter(); + ILogger logger = new LoggerConfiguration() + .Enrich.WithExceptionDetails(new DestructuringOptionsBuilder().WithDefaultDestructurers().WithDestructurers(new[] { new TestDbUpdateExceptionDestructurer() })) + .WriteTo.Sink(new TestTextWriterSink(jsonWriter, new JsonFormatter())) + .CreateLogger(); + var ctx = new TestContext(); + ctx.Database.EnsureDeleted(); + ctx.Database.EnsureCreated(); + + var entry = ctx.Add(new User + { + UserId = Guid.NewGuid().ToString() + }); + + // Act + logger.Error(new TestDbUpdateException("DbUpdate Error", entry), "Error"); + + // Assert + var writtenJson = jsonWriter.ToString(); + writtenJson.Should().NotContain(TestContext.UserIdIDoNotWantToSee); + } + + public class User + { + public string UserId { get; set; } + } + + public class TestContext : DbContext + { + public const string UserIdIDoNotWantToSee = "I Don't Want To See You"; + + public DbSet Users { get; set; } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseInMemoryDatabase(databaseName: "TestDebUpdateException"); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + var users = new List + { + new User + { + UserId = "FirstUser" + }, + new User + { + UserId = UserIdIDoNotWantToSee + } + }; + + modelBuilder.Entity().HasData(users); + } + } + + internal class TestDbUpdateException : DbUpdateException + { + private readonly IReadOnlyList entityEntries; + + public TestDbUpdateException(string message, EntityEntry entityEntry) + : base(message, (Exception)null) => this.entityEntries = new List { entityEntry }.AsReadOnly(); + + public override IReadOnlyList Entries => this.entityEntries; + } + + internal class TestDbUpdateExceptionDestructurer : DbUpdateExceptionDestructurer + { + public override Type[] TargetTypes => new[] { typeof(TestDbUpdateException) }; + } + } +} \ No newline at end of file diff --git a/Tests/Serilog.Exceptions.Test/Destructurers/ReflectionBasedDestructurerTest.cs b/Tests/Serilog.Exceptions.Test/Destructurers/ReflectionBasedDestructurerTest.cs index 4e86cb26..4d1e35e4 100644 --- a/Tests/Serilog.Exceptions.Test/Destructurers/ReflectionBasedDestructurerTest.cs +++ b/Tests/Serilog.Exceptions.Test/Destructurers/ReflectionBasedDestructurerTest.cs @@ -350,6 +350,26 @@ public void WhenDestruringArgumentException_ResultShouldBeEquivalentToArgumentEx Test_ResultOfReflectionDestructurerShouldBeEquivalentToCustomOne(exception, new ArgumentExceptionDestructurer()); } + [Fact] + public void CanDestructureObjectWithHiddenProperty() + { + var derived = new DerivedClass + { + HiddenProperty = 123 + }; + var baseClass = (BaseClass)derived; + baseClass.HiddenProperty = 456; + var exception = new HiddenException("test", derived); + + var propertiesBag = new ExceptionPropertiesBag(exception); + CreateReflectionBasedDestructurer().Destructure(exception, propertiesBag, EmptyDestructurer()); + + var properties = propertiesBag.GetResultDictionary(); + var info = properties[nameof(HiddenException.Info)] as IDictionary; + Assert.Equal(derived.HiddenProperty, info[nameof(DerivedClass.HiddenProperty)]); + Assert.Equal(baseClass.HiddenProperty, info[$"{typeof(BaseClass).FullName}.{nameof(BaseClass.HiddenProperty)}"]); + } + private static void Test_ResultOfReflectionDestructurerShouldBeEquivalentToCustomOne( Exception exception, IExceptionDestructurer customDestructurer) @@ -531,5 +551,26 @@ internal class TestClass public string ReferenceType { get; set; } } + + internal class BaseClass + { + public virtual int HiddenProperty { get; set; } + } + + internal class DerivedClass : BaseClass + { + public new T HiddenProperty { get; set; } + } + + internal class HiddenException : Exception + { + public HiddenException(string message, object info) + : base(message) + { + this.Info = info; + } + + public object Info { get; set; } + } } } diff --git a/Tests/Serilog.Exceptions.Test/Serilog.Exceptions.Test.csproj b/Tests/Serilog.Exceptions.Test/Serilog.Exceptions.Test.csproj index fae267dc..dbecee37 100644 --- a/Tests/Serilog.Exceptions.Test/Serilog.Exceptions.Test.csproj +++ b/Tests/Serilog.Exceptions.Test/Serilog.Exceptions.Test.csproj @@ -1,4 +1,4 @@ - + netcoreapp2.2 @@ -14,12 +14,14 @@ + +