Click here to Skip to main content
13,406,177 members (51,634 online)
Click here to Skip to main content
Add your own
alternative version


18 bookmarked
Posted 16 Aug 2012

Multithreaded, Customizable SysLog Server - C#

, 27 Mar 2013
Rate this:
Please Sign up or sign in to vote.
Multithreaded, customizable SysLog server in C#.


For those of us managing multiple devices, keeping aware of issues and events can be a challenge. Many Linux, Unix, and Windows devices support the ability to send SysLog (System Log) events to a central server for notifications and/or logging. I decided to make this application using C# (Visual Studio Express 2010) to receive those messages, store them in CSV format and send me email notifications based on custom criteria I define. I chose CSV because it's light weight and can natively be opened by any spreadsheet software or brought in to another app as a DataTable with a simple OLEDB connection. For my purposes, multithreading this app was essential due to the volume of devices configured to send SysLogs to the server. I let this app run for a bit and looked through the output CSV file to determine which events I should be made aware of via email, and set those as email triggers. This is a relatively light weight console app that is very versatile for a number of uses. Check out the code and leave a comment with any questions or suggestions! You can also check out my blog at

Using the code

Configure your "devices" to aim their SysLog events to the IP of your computer (you'll probably want a static or reserved IP for this to work well). Create a Console application in Visual Studio, and use the following code:

using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace syslog
    class Program
        static void Main(string[] args)
            IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
            UdpClient udpListener = new UdpClient(514);
            byte[] bReceive; string sReceive; string sourceIP;

            /* Main Loop */
            /* Listen for incoming data on udp port 514 (default for SysLog events) */
            while (true)
                    bReceive = udpListener.Receive(ref anyIP);
                    /* Convert incoming data from bytes to ASCII */
                    sReceive = Encoding.ASCII.GetString(bReceive);
                    /* Get the IP of the device sending the syslog */
                    sourceIP = anyIP.Address.ToString();
                    new Thread(new logHandler(sourceIP, sReceive).handleLog).Start();
                    /* Start a new thread to handle received syslog event */
                catch (Exception ex) { Console.WriteLine(ex.ToString()); }

    class logHandler
        /* Phrases within the syslog that will trigger an email notification */
        private string[] emailTriggers = new string[] { "link loss", "help please" };
        private string outputPath = @"C:\Users\metastruct\Desktop\syslog.csv"; /* Location to store events */
        private string source; private string log;
        public logHandler(string sourceIP, string logData) /* Initialize object and clean up the raw data */
            source = sourceIP.Trim(); /* Client IP */
            log = logData.Replace(Environment.NewLine, "").Trim(); /* Syslog data */

        public void handleLog() /* Store the syslog and determine whether to trigger an email notification */
            /* Store the syslog using a new thread */
            new Thread(new outputCsvRow(outputPath, new string[] { source, log }).addRow).Start();
            for (int i = 0; i < emailTriggers.Count(); i++) { if (log.Contains(emailTriggers[i])) { emailEvent(); } }
            /* Search for trigger strings and send email if found */


        private void emailEvent() /* Send email notification */
                MailMessage notificationEmail = new MailMessage();
                notificationEmail.Subject = "SysLog Event";
                notificationEmail.IsBodyHtml = true;
                notificationEmail.Body = "<b>SysLog Event Triggered:<br/><br/>Time: </b><br/>" + 
                    DateTime.Now.ToString() + "<br/><b>Source IP: </b><br/>" + 
                    source + "<br/><b>Event: </b><br/>" + log; /* Throw in some basic HTML for readability */
                notificationEmail.From = new MailAddress("", "SysLog Server"); /* From Address */
                notificationEmail.To.Add(new MailAddress("", "metastruct")); /* To Address */
                SmtpClient emailClient = new SmtpClient(""); /* Address of your SMTP server of choice */
                //emailClient.UseDefaultCredentials = false; /* If your SMTP server requires credentials to send email */
                //emailClient.Credentials = new NetworkCredential("username", "password"); /* Supply User Name and Password */
                emailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                emailClient.Send(notificationEmail); /* Send the email */
            catch (Exception ex) { Console.WriteLine(ex.ToString()); }

    class outputCsvRow
        private string formattedRow = null;
        private string outputPath = null;

        public outputCsvRow(string filePath, string[] columns) /* Initialize object */
            outputPath = filePath;
            formattedRow = (char)34 + DateTime.Now.ToString() + (char)34; /* Construct csv row starting with the timestamp */
            for (int i = 0; i < columns.Count(); i++) { formattedRow += "," + (char)34 + columns[i] + (char)34; }

        public void addRow()
            int attempts = 0;
            bool canAccess = false;
            StreamWriter logWriter = null;
            if (!File.Exists(outputPath)) /* If the file doesn't exist, give it some column headers */
                logWriter = new StreamWriter(outputPath, true);
                logWriter.WriteLine((char)34 + "Event_Time" + (char)34 + "," + 
                  (char)34 + "Device_IP" + (char)34 + "," + (char)34 + "SysLog" + (char)34);
            /* Thread safety first! This is a poor man's SpinLock */
            while (true)
                    logWriter = new StreamWriter(outputPath, true); /* Try to open the file for writing */
                    canAccess = true; /* Success! */
                catch (IOException ex)
                    if (attempts < 15) { attempts++; Thread.Sleep(50); }
                    else { Console.WriteLine(ex.ToString()); break; } /* Give up after 15 attempts */
            if (canAccess) /* Write the line if the file is accessible */

Points of Interest

An additional feature that may prove useful would be a function to cross reference IP addresses with a more "user friendly" device name. This would be most useful if the emails or logs are being used by multiple users, or if there are a large amount of devices and remembering the IP addresses of all of them isn't probable. For my "live" application, I also use that feature and separate log files for each device. Word of warning, some devices send tons of these events and your light weight CSV file can become enormous if you let it. I also added some code in the Main block to archive the logs on a rolling seven day basis. For that you'll probably have to halt receiving logs briefly to avoid an IOException.


  • This is version 1, help me improve!


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer (Senior)
United States United States
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralMy vote of 5 Pin
Jeff Block12-Jun-15 15:34
memberJeff Block12-Jun-15 15:34 
GeneralMy vote of 2 Pin
Michael D Bray18-Aug-14 13:36
memberMichael D Bray18-Aug-14 13:36 
QuestionThis is not a good way to do multi-threaded code Pin
Michael D Bray18-Aug-14 13:24
memberMichael D Bray18-Aug-14 13:24 
QuestionReturn this in a Console window Pin
NattyMan000714-Jul-14 20:33
memberNattyMan000714-Jul-14 20:33 
General! Pin
cavalin xucro16-Aug-13 10:33
membercavalin xucro16-Aug-13 10:33 
GeneralMy vote of 5 Pin
metastruct20-Aug-12 9:52
membermetastruct20-Aug-12 9:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.180221.1 | Last Updated 27 Mar 2013
Article Copyright 2012 by metastruct
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid