When working on our game with a friend, we needed a way to track debug data (and general log info). Here’s what I came up with.
Note, there’s no way to set the logging verbosity (level) as yet, but this will come later.

#if WINDOWS
public enum syslogType
{
ERROR = 0,
WARNING = 1,
INFO = 2,
DEBUG = 3
}
public static class Syslog
{
static bool _enabled;
static string _filename;

static String theTimestamp(this DateTime value)
{
return value.ToString(“yyyy-MM-dd-HH:mm:ss”);
}
static public void initialize()
{
_enabled = true;
_filename = “syslog-” + System.DateTime.Now.ToString(“yyyyMMddHHmmss”) + “.txt”;
StreamWriter outputLog = new StreamWriter(new FileStream(_filename, FileMode.Create, FileAccess.Write));
outputLog.WriteLine(theTimestamp(System.DateTime.Now) + ” [INFO] Log Created”);
outputLog.Close();
}

static public bool Enabled
{
get { return _enabled; }
set { _enabled = value; }
}

// this is the public log interface – Improvement for later: Add optional parameter for module/class to show where entry originated
static public void log(syslogType logType, string logText)
{
if (!_enabled) return;
string logStart = “”;
switch (logType)
{
case syslogType.DEBUG: logStart = “[DEBUG]”; break;
case syslogType.ERROR: logStart = “[ERROR]”; break;
case syslogType.INFO: logStart = “[INFO]”; break;
case syslogType.WARNING: logStart = “[WARNING]”; break;
}
logText = theTimestamp(System.DateTime.Now) + ” ” + logStart + ” ” + logText;
writeLog(logText);
}

static private void writeLog(string logText)
{
try
{
StreamWriter outputLog = new StreamWriter(new FileStream(_filename, FileMode.Append, FileAccess.Write));
outputLog.WriteLine(logText);
outputLog.Close();
}
catch (System.Exception e)
{
string errException = e.Message;
}
}
}
#endif

Call the class with using the public methods and with the following syntax/example:

  Syslog.initialize();

Syslog.log(syslogType.INFO,(“Hello there, I am a log entry: ” + variableifyouneedit));

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s