There's nothing magical about logging entries into the log store. You simply call:
WebLogEntry entry = new WebLogEntry()
{
Message = "Application Started",
ErrorLevel = ErrorLevels.Message
};
LogManager.Current.WriteEntry(entry);
You can set any of the properties of the Web Entry object and you're on your way. The ErrorLevel property determines the type of error that is logged which is effectively a way to group errors for the log viewer or your own manual querying of the data.
Here are a couple of common examples of logging that you might do which is request logging and error logging.
Log every ASP.NET Request:
protected void Application_EndRequest(Object sender, EventArgs e)
{
// Request Logging
if (LogManagerConfiguration.Current.LogWebRequests)
{
try
{
WebLogEntry entry = new WebLogEntry()
{
ErrorLevel = ErrorLevels.Log,
Message= this.Context.Request.FilePath,
RequestDuration = (decimal) DateTime.Now.Subtract(Context.Timestamp).TotalMilliseconds
};
entry.UpdateFromRequest(this.Context);
LogManager.Current.WriteEntry(entry);
}
catch { ;}
}
}
Here the UpdateFromWebRequest() helper method is used to populate WebLogEntry properties like IpAddress, PostData and so on from the current executing Web request.
Another common scenario is global error handling in ASP.NET by trapping the Application_Error handler and from within it logging an error.
ASP.NET Error Logging
protected void Application_Error(object sender, EventArgs e)
{
try
{
Exception serverException = Server.GetLastError();
// Try to log the inner Exception since that's what
// contains the 'real' error.
if (serverException.InnerException != null)
serverException = serverException.InnerException;
// Log the error if specified
if (LogManagerConfiguration.Current.LogErrors)
{
WebLogEntry entry = new WebLogEntry(serverException, this.Context);
LogManager.Current.WriteEntry(entry);
}
...
}
Here both an exception and the Http Context are passed to the entry which effective sets up the request as an error and assigns both the exception detail as well as all of the request detail. Of course you can still set any of the properties of the WebLogEntry entry object before writing it to the log.
© West Wind Technologies, 1996-2016 • Updated: 01/06/16
Comment or report problem with topic