Created
November 7, 2018 11:52
-
-
Save dlidstrom/d7770f8e4b774a6d9a897de1e83e57bb to your computer and use it in GitHub Desktop.
This file contains 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
public class MessageChecksumConverter : PatternLayoutConverter | |
{ | |
private static readonly TraceSource Source = new TraceSource(nameof(MessageChecksumConverter)); | |
private static readonly MD5 ChecksumGenerator = MD5.Create(); | |
protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) | |
{ | |
var output = TryGetHash(loggingEvent); | |
writer.Write(output); | |
} | |
private string TryGetHash(LoggingEvent loggingEvent) | |
{ | |
string output = string.Empty; | |
try | |
{ | |
byte[] hash; | |
var fmt = loggingEvent.MessageObject as SystemStringFormat; | |
if (fmt != null) | |
{ | |
// read fmt.m_format and use that as input for hash | |
var systemStringFormatType = typeof(SystemStringFormat); | |
var fieldInfo = | |
systemStringFormatType.GetField("m_format", BindingFlags.NonPublic | BindingFlags.Instance); | |
var formatString = fieldInfo?.GetValue(fmt) as string; | |
hash = ChecksumGenerator.ComputeHash(Encoding.ASCII.GetBytes(formatString ?? string.Empty)); | |
} | |
else | |
{ | |
var str = (loggingEvent.ExceptionObject ?? loggingEvent.MessageObject).ToString(); | |
hash = ChecksumGenerator.ComputeHash(Encoding.ASCII.GetBytes(str)); | |
} | |
var builder = new StringBuilder(); | |
foreach (var b in hash.Take(2)) | |
{ | |
builder.Append(b.ToString("x2")); | |
} | |
output = builder.ToString(); | |
} | |
catch (Exception ex) | |
{ | |
// can be found if log4net debugging is enabled | |
Source.TraceError(ex.ToString()); | |
} | |
return output; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment