Introduction
Syslog has become the standard logging solution on Unix and Linux systems. There are many applications which can send and receive syslog messages on windows computers. I have this wireless router (WRT type) and after a firmware upgrade, there was a syslog option. Working on a Windows XP machine, I wrote a Syslog daemon of my own entirely in C#.
Background
For logging on Windows we have Eventlog. To make use of Eventlog we have to make a service which translates syslog messages and sends them to Eventlog. Syslog messages are transported as UDP packets on port number 514, and have a very simple structure. For more on Syslog packets, please read http://www.ietf.org/rfc/rfc3164.txt
Using the demo project
The demo project contains the Syslogd.exe service. If you want to use it, you have to install the service by using the .NET tool installutil.exe which is located in the framework directory (watch version numbering).
In my src project I use two post-build steps, one for uninstall, and one for installing.
Note: If you build the project for the first time, the first step will break. So remove it, and add it later.
c:\windows\microsoft.net\framework\v2.0.50727\installutil.exe
/u "$(TargetPath)"
c:\windows\microsoft.net\framework\v2.0.50727\installutil.exe
"$(TargetPath)"
Note: The demo project contains a simple install.cmd that does install your service.
Because services are not nice to debug(!), the project contains a simple Form which can Start and Stop the Syslogd process. You can set breakpoints, and do single steps from here.
When using installutil.exe for registering .NET services, the tool looks for any [RunInstaller(true)] attribute on a class, and executes that piece of code.
[RunInstaller(true)]
public class SyslogdInstaller : Installer
{
.......
}
SyslogdInstaller.cs
This installer code is located in SyslogdInstaller.cs which does two things. It installs the syslogd service and opens up the internal firewall of Windows XP, for more on this, see 'Points of Interest'.
.......
this.serviceProcessInstaller1.Account = ServiceAccount.LocalSystem;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
.......
this.serviceInstaller1.ServiceName = settings.ServiceName;
this.serviceInstaller1.Description = settings.Description;
this.serviceInstaller1.DisplayName = settings.DisplayName;
this.serviceInstaller1.StartType = ServiceStartMode.Automatic;
Properties.Settings
Most of the properties in this project are configurable by its Properties.Settings class.
In Visual Studio you can use the nice properties editor:

When saving these settings, an XML file is saved (Syslogd.exe.config) which can be changed according to one's own wishes afterwards.
="1.0" ="utf-8"
<configuration>
.....
<userSettings>
<Syslogd.Properties.Settings>
<setting name="Address" serializeAs="String">
<value>*</value>
</setting>
<setting name="Port" serializeAs="String">
<value>514</value>
</setting>
<setting name="ServiceName" serializeAs="String">
<value>Syslogd</value>
</setting>
<setting name="Description" serializeAs="String">
<value>Syslogd service logs syslog messages to
windows eventlog</value>
</setting>
<setting name="DisplayName" serializeAs="String">
<value>Syslogd service</value>
</setting>
<setting name="EventLog" serializeAs="String">
<value>Syslog</value>
</setting>
</Syslogd.Properties.Settings>
</userSettings>
</configuration>
SyslogdService.cs
The syslogd service code itself is located in SyslogdService.cs. This is more or less a standard service code and inherits from ServiceBase. There is only a Start and a Stop service method.
...
private Syslogd syslogd;
...
public SyslogdService()
{
...
syslogd = new Syslogd();
}
protected override void OnStart(string[] args)
{
syslogd.Start();
}
...
protected override void OnStop()
{
syslogd.Stop();
}
...
Syslogd.cs
When syslogd service is started, a new class syslogd is instantiated, and contains a worker thread for receiving syslog messages. This worker class is located in Syslogd.cs
private void Worker()
{
Properties.Settings settings = new Properties.Settings();
m_EventLog = settings.EventLog;
IPAddress ipAddress = IPAddress.Any;
if(settings.Address!="*")
ipAddress = IPAddress.Parse(settings.Address);
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, settings.Port);
m_socket = new Socket(
AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
m_socket.Bind(ipEndPoint);
EndPoint endPoint = ipEndPoint;
byte[] buffer = new byte[1024];
while (m_running)
{
try
{
int intReceived = m_socket.ReceiveFrom(buffer, 0,
buffer.Length, SocketFlags.None, ref endPoint);
string strReceived = Encoding.ASCII.GetString(buffer,
0, intReceived);
Log(endPoint, strReceived);
}
catch (Exception exception)
{
EventLog myLog = new EventLog();
myLog.Source = settings.ServiceName;
if (!m_running)
myLog.WriteEntry("Stopping...",
EventLogEntryType.Information);
else
myLog.WriteEntry(exception.Message,
EventLogEntryType.Error);
myLog.Close();
myLog.Dispose();
}
}
}
Decoding Syslog PRI
Every syslog packet contains a PRI. This PRI is simply decoded and translated by making use of the appropriate regular expression.
...
m_regex = new Regex("<([0-9]{1,3})>", RegexOptions.Compiled);
...
After decoding the decimal part of the PRI, I use a struct to translate it to Facility and Severity.
private enum FacilityEnum : int
{
kernel = 0, user = 1, mail = 2, system = 3, security = 4, internally = 5, printer = 6, news = 7, uucp = 8, cron = 9, security2 = 10, ftp = 11, ntp = 12, audit = 13, alert = 14, clock2 = 15, local0 = 16, local1 = 17, local2 = 18, local3 = 19, local4 = 20, local5 = 21, local6 = 22, local7 = 23, }
private enum SeverityEnum : int
{
emergency = 0, alert = 1, critical = 2, error = 3, warning = 4, notice = 5, info = 6, debug = 7, }
private struct Pri
{
public FacilityEnum Facility;
public SeverityEnum Severity;
public Pri(string strPri)
{
int intPri = Convert.ToInt32(strPri);
int intFacility = intPri >> 3;
int intSeverity = intPri & 0x7;
this.Facility = (FacilityEnum)Enum.Parse(typeof(FacilityEnum),
intFacility.ToString());
this.Severity = (SeverityEnum)Enum.Parse(typeof(SeverityEnum),
intSeverity.ToString());
}
public override string ToString()
{
return string.Format("{0}.{1}", this.Facility, this.Severity);
}
}
The first PRI match in the received message gets special attention.
See 'The logging in Eventlog' part for this.
...
Pri pri = new Pri(m_regex.Match(strReceived).Groups[1].Value);
...
Because syslog messages can be relayed, and a relay can add more PRI parts, every message can have more than one PRI. Every PRI is replaced by its human readable Facility.Severity pair.
private string evaluator(Match match)
{
Pri pri = new Pri(match.Groups[1].Value);
return pri.ToString()+" ";
}
private void Log(EndPoint endPoint, string strReceived)
{
...
string strMessage = string.Format("{0} : {1}",
endPoint, m_regex.Replace(strReceived, evaluator));
...
}
Translating Syslog Severity to EventLogEntryType
Windows Eventlog supports only a few useful EventLogEntryTypes: Error, Warning and Information. Every syslog Severity is mapped on one of these. This is only done to have a good discriminable part for any Sysadmin, or analyzer program which watches the Eventlog. Every syslog Severity is logged in full in the body of every Eventlog entry.
private EventLogEntryType Severity2EventLogEntryType(SeverityEnum Severity)
{
EventLogEntryType eventLogEntryType;
switch (Severity)
{
case SeverityEnum.emergency:
eventLogEntryType = EventLogEntryType.Error;
break;
case SeverityEnum.alert:
eventLogEntryType = EventLogEntryType.Error;
break;
case SeverityEnum.critical:
eventLogEntryType = EventLogEntryType.Error;
break;
case SeverityEnum.error:
eventLogEntryType = EventLogEntryType.Error;
break;
case SeverityEnum.warning:
eventLogEntryType = EventLogEntryType.Warning;
break;
case SeverityEnum.notice:
eventLogEntryType = EventLogEntryType.Information;
break;
case SeverityEnum.info:
eventLogEntryType = EventLogEntryType.Information;
break;
case SeverityEnum.debug:
eventLogEntryType = EventLogEntryType.Information;
break;
default: eventLogEntryType = EventLogEntryType.Error;
break;
}
return eventLogEntryType;
}
The logging in Eventlog
Binding this all together, logging IP-address, Port-number, PRI translated message, logging in Windows Eventlog. Nice feature to use the first PRI as a eventlog Source, because new Eventlogs can (auto) register Source types, which you can filter etc.
private void Log(EndPoint endPoint, string strReceived)
{
Pri pri = new Pri(m_regex.Match(strReceived).Groups[1].Value);
EventLogEntryType eventLogEntryType =
Severity2EventLogEntryType(pri.Severity);
string strMessage = string.Format("{0} : {1}",
endPoint, m_regex.Replace(strReceived, evaluator));
EventLog myLog = new EventLog(m_EventLog);
myLog.Source = pri.ToString();
myLog.WriteEntry(strMessage, eventLogEntryType);
myLog.Close();
myLog.Dispose();
}
Points of Interest
When building services which use the network on a Windows XP machine, you have to deal with the built-in Firewall. For opening up the internal firewall for the service, this piece of code is needed:
private void FireWall()
{
...
Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);
INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType);
Type NetFwAuthorizedApplicationType =
Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication", false);
INetFwAuthorizedApplication app =
(INetFwAuthorizedApplication)
Activator.CreateInstance(NetFwAuthorizedApplicationType);
app.Name = settings.ServiceName;
app.Enabled = true;
app.ProcessImageFileName = Assembly.GetExecutingAssembly().Location;
app.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
mgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(app);
...
}
Don't forget that you have to make a reference to c:\windows\system32\hnetcfg.dll - it makes an Interop.NetFwTypeLib.dll
Syslogd In action
I'm running a Dutch version of Windows XP, nice for all other programmers to see Services and Eventlog in Dutch!!
A sample Syslog entry of my router:
History
- As of writing, it is Version 1.0