Skip to content

Instantly share code, notes, and snippets.

@dlidstrom
Created November 7, 2018 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dlidstrom/d7770f8e4b774a6d9a897de1e83e57bb to your computer and use it in GitHub Desktop.
Save dlidstrom/d7770f8e4b774a6d9a897de1e83e57bb to your computer and use it in GitHub Desktop.
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