A simple trace writer for Newtonsoft.Json serialization / deserialization debugging
and logging to Serilog.
Link: https://gist.github.com/SeppPenner/1968bbd4a47055471a135bdfbc58ac2b
Code:
// <copyright file="SerilogTraceWriter.cs" company="Hämmer Electronics"> |
// Copyright (c) 2020 All rights reserved. |
// A custom trace writer to write serialization information for Newtonsoft.Json to Serilog. |
// -------------------------------------------------------------------------------------------------------------------- |
namespace Data.Serialization |
using System.Diagnostics; |
using System.Diagnostics.CodeAnalysis; |
using Newtonsoft.Json.Serialization; |
/// A custom trace writer to write serialization information for Newtonsoft.Json to Serilog. |
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")] |
public class SerilogTraceWriter : ITraceWriter |
private static readonly ILogger Logger = Log.ForContext<SerilogTraceWriter>(); |
/// <inheritdoc cref="ITraceWriter"/> |
/// Gets the <see cref="TraceLevel"/> that will be used to filter the trace messages passed to the writer. |
/// For example a filter level of <see cref="TraceLevel.Info"/> will exclude <see cref="TraceLevel.Verbose"/> messages and include <see cref="TraceLevel.Info"/>, |
/// <see cref="TraceLevel.Warning"/> and <see cref="TraceLevel.Error"/> messages. |
/// <value>The <see cref="TraceLevel"/> that will be used to filter the trace messages passed to the writer.</value> |
/// <seealso cref="ITraceWriter"/> |
public TraceLevel LevelFilter => TraceLevel.Verbose; |
/// <inheritdoc cref="ITraceWriter"/> |
/// Writes the specified trace level, message and optional exception. |
/// <param name="level">The <see cref="TraceLevel"/> at which to write this trace.</param> |
/// <param name="message">The trace message.</param> |
/// <param name="ex">The trace exception. This parameter is optional.</param> |
/// <seealso cref="ITraceWriter"/> |
public void Trace(TraceLevel level, string message, Exception ex) |
// ReSharper disable once SwitchStatementHandlesSomeKnownEnumValuesWithDefault |
case TraceLevel.Info: Logger.Information("Message: {message}, Exception: {exception}.", message, ex); |
case TraceLevel.Warning: Logger.Warning("Message: {message}, Exception: {exception}.", message, ex); |
case TraceLevel.Verbose: Logger.Verbose("Message: {message}, Exception: {exception}.", message, ex); |
case TraceLevel.Error: Logger.Error("Message: {message}, Exception: {exception}.", message, ex); |
case TraceLevel.Off: break; |
}
// -------------------------------------------------------------------------------------------------------------------- |
Keine Kommentare:
Kommentar veröffentlichen