how to add some properties to log entry

2.4k Views Asked by At

I use Microsoft Enterprise Library 5.0 (Logging Application Block). I want to save IP address and username into database. How can I add these two columns to Logging Application Block?

HttpContext _Context = HttpContext.Current;
Exception _ex = _Context.Server.GetLastError();
LogEntry _LogEntery = new LogEntry();
if (_ex.InnerException != null)
{
    _LogEntery.Message = _ex.InnerException.ToString();
}
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
    _ex.Data.Add("UserName", HttpContext.Current.User.Identity.Name);

}
_ex.Data.Add("IPaddress", Request.UserHostAddress);
_LogEntery.Title = _ex.Message.ToString();
_LogEntery.ExtendedProperties.Add("Ip", _ex.Data["IPaddress"]);
_LogEntery.Categories.Add("Database");
Logger.Write(_LogEntery);
_Context.Server.ClearError();
2

There are 2 best solutions below

0
On

You can write directly as a string Logger.Write("") or you can create your own LogEntry class and inherit from LogEntry and then change the Formatters in the config to include your new properties.

Rereading your question just use extended properties and then change the Formatters in the config.

0
On

This Code Has Not been tested

IDictionary *contextInfo* = new Hashtable();

   contextInfo.Add("Additional Info", "Some information I wanted logged");

   DebugInformationProvider provider = new DebugInformationProvider();
   provider.PopulateDictionary(contextInfo);

   LogEntry logEntry           = new LogEntry();
   logEntry.Message            = "Logged with context specific information";
   logEntry.ExtendedProperties = *contextInfo*;

   Logger.Write(logEntry);