Created
December 2, 2021 05:25
-
-
Save sergey-miryanov/544b8413da70a0be455ac3903c1a781c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Serilog; | |
using Serilog.Core; | |
using Serilog.Events; | |
Log.Logger = new LoggerConfiguration() | |
.WriteTo.Console(formatProvider:new GuidFormatter()) | |
.Destructure.With<GuidDestructuringPolicy>() | |
.Destructure.ByTransforming<CustomClass>(Helper.ToString) | |
.Destructure.ByTransforming<CustomStruct>(Helper.ToString) | |
.CreateLogger(); | |
Log.Information("Hello, {@Guid}!", Guid.NewGuid()); | |
Log.Information("Hello, {@CustomClass}!", new CustomClass { I = 1 }); | |
Log.Information("Hello, {@CustomStruct}!", new CustomStruct()); | |
static class Helper | |
{ | |
public static object ToString(Guid guid) | |
{ | |
return guid.ToString().Substring(0,5); | |
} | |
public static object ToString(CustomClass zxc) | |
{ | |
return $"zxc: {zxc.I}"; | |
} | |
public static object ToString(CustomStruct asd) | |
{ | |
return $"asd: {asd.J}"; | |
} | |
} | |
readonly struct CustomStruct | |
{ | |
public int J { get; } | |
} | |
class CustomClass | |
{ | |
public int I { get; set; } | |
} | |
// doesn't work because Guid considered as scalar type | |
public class GuidDestructuringPolicy : IDestructuringPolicy | |
{ | |
public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue result) | |
{ | |
if (value is Guid guid) | |
{ | |
result = propertyValueFactory.CreatePropertyValue(Helper.ToString(guid)); | |
return true; | |
} | |
result = default; | |
return false; | |
} | |
} | |
// Dummy custom formatter to illustrate idea | |
class GuidFormatter : IFormatProvider, ICustomFormatter | |
{ | |
public GuidFormatter() | |
{ | |
} | |
public string Format(string? format, object? arg, IFormatProvider? formatProvider) | |
{ | |
if (arg is Guid guid) | |
{ | |
return Helper.ToString(guid).ToString(); | |
} | |
return arg.ToString(); | |
} | |
public object GetFormat(Type formatType) | |
{ | |
if (formatType == typeof(ICustomFormatter)) | |
return this; | |
else | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment