jjchiw / gelf4net

GELF log4net Appender - graylog2
MIT License
63 stars 59 forks source link

GelfUdpAppender.GenerateMessageId() generates collisioning IDs #28

Closed dheygere closed 8 years ago

dheygere commented 8 years ago

Hello, the code below will generate identical message ids when called twice in a hundredth of a millisecond. On our application that happens.

public static string GenerateMessageId()
{
    var md5String = String.Join("", MD5.Create().ComputeHash(Encoding.Default.GetBytes(Environment.MachineName)).Select(it => it.ToString("x2")).ToArray<string>());
    var sb = new StringBuilder();
    var t = DateTime.Now.Ticks % 1000000000;
    var s = String.Format("{0}{1}", md5String.Substring(0, 10), md5String.Substring(20, 10));
    var r = Random.Next(10000000).ToString("00000000");

    sb.Append(t); // <== this is already 10 chars long
    sb.Append(s); // this is trimmed out by substring
    sb.Append(r); // this is also trimmed out by substring

    //Message ID: 8 bytes 
    return sb.ToString().Substring(0, MaxHeaderSize);
}

Of the 3 appended variables (t, s and r) only the first 8 chars of t are kept. I tested with the code below:

void Main()
{
    for (int i=1; i<10; i++) {
        Console.WriteLine(GenerateMessageId());
    }
}

// OUTPUT:
// 84128103
// 84128103
// 84128103
// 84128589
// 84128589
// 84128589
// 84129093
// 84129093
// 84129093