I've got a method with some overloads to handle logging, and am noticing some (to me) bizarre behavior. The overloads (which are in a class that my other classes inherit) generate a stacktrace and call the main logging method that then writes out a line which ostensibly includes the calling class and method:
class Global
{
public static void LogLine(string logline, StackTrace st)
{
string cmethod = st.GetFrame(1).GetMethod().Name;
string cclass = st.GetFrame(1).GetMethod().DeclaringType.Name;
string logsuffix = String.Format(" ({0}.{1})", cclass, cmethod);
string curDir = Directory.GetCurrentDirectory();
string logfile = String.Format(@"{0}\logs\Logfile_{1}.log", curDir, DateTime.Today.ToString("yyyyMMdd"));
using (System.IO.StreamWriter log = new System.IO.StreamWriter(logfile, true))
{
string curtime = String.Format("[{0}]: ", DateTime.Now.ToString("yyyyMMdd-HHmm"));
log.WriteLine(curtime + logline + logsuffix);
}
return;
}
public static void WLog(string logline)
{
StackTrace st = new StackTrace();
LogLine(logline, st);
}
public static void WLog(string logline, object obj0)
{
StackTrace st = new StackTrace();
LogLine(string.Format(logline, obj0), st);
}
}
Now the bizarre behavior. This will generate a nullreference exception:
class Program : Global
{
static void Main(string[] args)
{
string text = "rando text";
WLog(text);
}
}
If I wrap the string in string.Format in WLog(string), it works just fine:
public static void WLog(string logline)
{
StackTrace st = new StackTrace();
LogLine(string.Format(logline), st);
}
Can anyone help me understand why this is happening?
The generated exception:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at ...Global.LogLine(String logline, StackTrace st) in ...\Global.cs:line 15
at ...Program.Main(String[] args) in ...\Program.cs:line 24