I'm using SyslogNet.Client to syslog (UDP) messages to a server. I loop through a collection of errors from a database and send them. Only ~40% of messages arrive. I understand that with UDP, there is no guarantee of message arrival, but this is a very high percentage. However, if I call Thread.Sleep(1)
between each iteration of the loop, 100% of the messages arrive. I'm having trouble understanding why this is happening.
Here's the loop:
private static void SyslogErrors(Dictionary<int, string> errorCol)
{
foreach (var error in errorCol)
{
SyslogMessage("AppName", error.Value);
Thread.Sleep(1);
}
}
And here's SyslogMessage
:
private static void SyslogMessage(string appName, string message)
{
using (_syslogSender = new SyslogUdpSender(Server, Port))
{
var msg = new SyslogMessage(DateTime.Now,
Facility.SecurityOrAuthorizationMessages1,
Severity.Informational,
Environment.MachineName,
appName,
message);
_syslogSender.Send(msg, new SyslogRfc3164MessageSerializer());
}
}
First of all, why is this happening? Secondly, what's the "best practices" way to slow the loop down? Thread.Sleep(1) doesn't seem like a very clean solution.
Thanks!
It looks like the OS rejects some logs when spammed too much, and the sleep will most likely do just fine. But there are indeed some more reliable solutions. You can setup a Timer object and call your logger using the Elapsed event.
Something like:
//likely much longer than needed, I figure you dont need this to breeze anyway
aTimer = new System.Timers.Timer(50);
aTimer.Elapsed += timeToLog;
aTimer.Enabled = true;
Then you log in time:
private static void timeToLog(Object source, ElapsedEventArgs e)
{
var error = getNextError(); //Keep an iterator somewhere
SyslogMessage("AppName", error.Value);
}
I can add the code you'll need in order to create and manage the iterator (getNextError), although we're getting outside the scope of your question.