Introduction
With each test application, we would like to print some output. It's pretty useful to have information about time of action and what thread it happened at. Moreover, prompt with waiting for user to press ENTER is common.
Using the Code
Here is the Log
class text:
public class Log
{
private Log()
{
}
public static void Print(string text, params object[] args)
{
DoLog("", text, args);
}
public static void Info(string text, params object[] args)
{
DoLog("INFO ", text, args);
}
public static void Warning(string text, params object[] args)
{
DoLog("WARNING ", text, args);
}
public static void Error(string text, params object[] args)
{
DoLog("!!!ERROR!!! ", text, args);
}
public static void WaitForEnter()
{
WaitForEnter("Press ENTER to continue...");
}
public static void WaitForEnter(string prompt)
{
DoLog("", prompt);
Console.ReadLine();
}
private static void DoLog(string prefix, string text, params object[] args)
{
int threadId = AppDomain.GetCurrentThreadId();
Console.Write("[{0:D4}] [{1}] ",
threadId,
DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff"));
Console.Write(prefix);
Console.WriteLine(text, args);
}
}
For such a program:
class Program
{
public Program()
{
Log.Print("Program()");
}
~Program()
{
Log.Print("~Program()");
}
static void Main(string[] args)
{
Program program = new Program();
Log.Print("Test");
Log.Error("MyError");
Log.Print("Test #{0}{1}", 1, ":o)");
Log.Error("MyError #{0}{1}", 1, ":o)");
Log.WaitForEnter();
}
}
It gives you this output:
[3276] [2008/09/27 08:52:05.431] Program()
[3276] [2008/09/27 08:52:05.434] Test
[3276] [2008/09/27 08:52:05.434] !!!ERROR!!! MyError
[3276] [2008/09/27 08:52:05.435] Test #1
[3276] [2008/09/27 08:52:05.435] !!!ERROR!!! MyError #1
[3276] [2008/09/27 08:52:05.435] Test #1:o)
[3276] [2008/09/27 08:52:05.435] !!!ERROR!!! MyError #1:o)
[3276] [2008/09/27 08:52:05.435] Press ENTER to continue...
[4500] [2008/09/27 08:52:07.682] ~Program()
As we can see, our Program
object was destroyed from some other thread (e.g. by GC thread).
History
- 27th September, 2008: Initial post
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.