Using ELMAH's SqlErrorLog to manually insert into Sql Server

by sunil ravulapalli /27. March 2013 00:47 /.net-tools /Comments (0)

This is a class I use to manually log into ELMAH tables

using Elmah;

namespace WesternUnionService
{
 public class Logger
 {
  public static bool LogError(Exception exception)
  {
	Error error = new Error()
	{ 
		HostName = System.Environment.MachineName,
		Type = exception.GetType().ToString(),
		Source = exception.Source,
		Message = exception.ToString(),
		StatusCode = 0,
		Time = System.DateTime.UtcNow
	};

	Log(error);

	return true;
  }

  public static bool LogInfo(string info)
  {
	Error error = new Error()
	{ 
		HostName = System.Environment.MachineName,
		Type = "Info",
		Source = ConfigurationManager.AppSettings["applicationName"],
		Message = info.Length <= 500 ? info : info.Substring(0,500),
		StatusCode = 0,
		Time = System.DateTime.UtcNow
	};

	Log(error);

	return true;
  }

  private static void Log(Error error)
  {
	  SqlErrorLog sqlErrorLog = new SqlErrorLog((Hashtable)ConfigurationManager.GetSection("elmah/errorLog"));
	  sqlErrorLog.Log(error);
  }

 }
}

It can be used like below:

try
{
 //do something
}
catch (Exception ex)
{
 Logger.LogError(ex);
}

or

Logger.LogInfo("Peek a boo");
blog comments powered by Disqus