Posted on 1/4/2007 3:23:02 AM
in #.NET
Here I would like to share some of the tools I've developed.
www.bodurov.com/soft/TracerLog.zip
This is a class for viewing the stack trace. You can use it as: TracerLog.ToFile(path); if you want to have the stcktrace as file, or TracerLog.ToString(path); if you want to have it as string.
The class:
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
///
/// Sample call:
/// TracerLog.ToFile(HttpContext.Current.Server.MapPath("~/")+"TracerLog.txt");
///
/// or just:
/// TracerLog.ToFile();
///
public class TracerLog
{
private static int Count = 1;
private TracerLog(){}
private string Path
{
get
{
string path = null;
if(System.Web.HttpContext.Current == null)
{
path = this.GetType().Assembly.CodeBase+".TracerLog-";
}
else
{
path = System.Web.HttpContext.Current.Server.MapPath("~/")+"TracerLog-";
}
path += DateTime.Now.Year + "." + DateTime.Now.Month + "." + DateTime.Now.Day + "." + DateTime.Now.Hour + "." +
DateTime.Now.Minute + "." + DateTime.Now.Second+"."+(Count++)+".log";
return path;
}
}
public static void ToFile()
{
TracerLog log = new TracerLog();
ToFile(log.Path, false);
}
public static void ToFile(string path)
{
ToFile(path, true);
}
public static void ToFile(string path, bool append)
{
TracerLog log = new TracerLog();
log.CreateLogFile(path, append);
}
public static void ToFile(string path, bool append, string more, params object[] data)
{
TracerLog log = new TracerLog();
log.More = String.Format(more, data);
log.CreateLogFile(path, append);
}
public new static string ToString() {
return TracerLog.ToString(String.Empty);
}
public static string ToString(string more)
{
StackTrace trace = new StackTrace();
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Date: {0}, {1} {2}", DateTime.Now, (Count++), more);
sb.AppendLine();
foreach(StackFrame frame in trace.GetFrames()) {
MethodBase method = frame.GetMethod();
if(method.ReflectedType.FullName == "TracerLog") {
continue;
}
sb.AppendFormat("{0,-80}\t\tReturns:{1} ->> Module:{2}", GetFullName(method), GetReturnType(method), method.Module.Name);
sb.AppendLine();
}
return sb.ToString();
}
private static string GetName(MethodBase method)
{
return method.ToString().Split(" ".ToCharArray(), 2)[1];
}
private static string GetReturnType(MethodBase method)
{
return method.ToString().Split(' ')[0];
}
private static string GetFullName(MethodBase method)
{
return method.ReflectedType.FullName + "." + GetName(method);
}
private string _more;
protected string More
{
get
{
return this._more;
}
set
{
this._more = value;
}
}
private void CreateLogFile(string path, bool append)
{
if(!File.Exists(path))
{
StreamWriter sw1 = File.CreateText(path);
sw1.Close();
}
StreamWriter sw2 = new StreamWriter( path, append );
sw2.WriteLine( TracerLog.ToString(this.More) );
sw2.Close();
}
}
Share this post:
digg
Stumble Upon
del.icio.us
E-mail
|