Using system;
Using system. configuration;
Using system. IO;
Using system. Web;
Namespace singingeels
{
Public class errorlogger
{
Public static void logexception (exception ex)
{
Errorloggersection configinstance = configurationmanager. getsection ("websiteerrorlogger") as errorloggersection;
If (configinstance! = NULL)
{
String mydirectory = httpcontext. current. server. mappath (configinstance. logfilepath + datetime. now. year. tostring () + "/" + datetime. now. month. tostring () + "/");
String mypath = mydirectory + datetime. Now. tow.datestring () + ". txt ";
If (! Directory. exists (mydirectory ))
{
Directory. createdirectory (mydirectory );
}
File. appendalltext (mypath, String. format ("{0: yyyymmdd_hhmmss }::{ 1} {2} {2}", datetime. now, ex, environment. newline ));
}
Else
{
Throw new exception ("cocould not find section 'errorloggersection 'in the application configuration file .");
}
}
}
// Inherit from "configurationsection" simple enough!
Public class errorloggersection: configurationsection
{
// I only want one property logfilepath, And I'm
// Here telling. Net to look for an attribute in
// Config file called 'logfilepath' to get the value from.
[Configurationproperty ("logfilepath", isrequired = true)]
Public String logfilepath
{
Get
{
Return (string) base ["logfilepath"];
}
Set
{
Base ["logfilepath"] = value;
}
}
}
}
Web. config
<? XML version = "1.0"?>
<Configuration>
<Configsections>
<Section name = "websiteerrorlogger" type = "singingeels. errorloggersection"/>
</Configsections>
<Websiteerrorlogger logfilepath = "~ /Log/"/>
<System. Web>
<Compilation DEBUG = "true"/>
</System. Web>
<System. Web>
<Customerrors mode = "remoteonly" defaultredirect = "~ /Error.htm "> </customerrors>
</System. Web>
</Configuration>
Global. asax
<% @ Application language = "C #" %>
<SCRIPT runat = "server">
Void application_start (Object sender, eventargs E)
{
// Code that runs on application startup
}
Void application_end (Object sender, eventargs E)
{
// Code that runs on application shutdown
}
Void application_error (Object sender, eventargs E)
{
// Code that runs when an unhandled error occurs
Exception err = server. getlasterror (). getbaseexception ();
Singingeels. errorlogger. logexception (ERR );
}
Void session_start (Object sender, eventargs E)
{
// Code that runs when a new session is started
}
Void session_end (Object sender, eventargs E)
{
// Code that runs when a session ends.
// Note: The session_end event is raised only when the sessionstate Mode
// Is set to inproc in the web. config file. If session mode is set to StateServer
// Or sqlserver, the event is not raised.
}
</SCRIPT>
Source code