Estoy trabajando en una configuración de Log4Net que registrará todas las excepciones no controladas. Necesito ciertas propiedades, basadas en el usuario, para agregar a cada entrada de registro. Lo configuré con éxito de la siguiente manera en mi evento Application_Error. Aquí está mi global.asax completoLog4Net, ThreadContext y Global.asax
Imports log4net
Imports log4net.Config
Public Class Global_asax
Inherits System.Web.HttpApplication
'Define a static logger variable
Private Shared log As ILog = LogManager.GetLogger(GetType(Global_asax))
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the application is started
ConfigureLogging()
End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
Dim ex As Exception = Server.GetLastError()
ThreadContext.Properties("user") = User.Identity.Name
ThreadContext.Properties("appbrowser") = String.Concat(Request.Browser.Browser, " ", Request.Browser.Version)
If TypeOf ex Is HttpUnhandledException AndAlso ex.InnerException IsNot Nothing Then
ex = ex.InnerException
End If
log.Error(ex)
ThreadContext.Properties.Clear()
End Sub
Private Sub ConfigureLogging()
Dim logFile As String = Server.MapPath("~/Log4Net.config")
log4net.Config.XmlConfigurator.ConfigureAndWatch(New System.IO.FileInfo(logFile))
log4net.GlobalContext.Properties("appname") = System.Reflection.Assembly.GetExecutingAssembly.GetName.Name
End Sub
End Class
Esto parece estar funcionando bien. Sin embargo, tengo algunas preguntas que no puedo responder.
¿La forma en que estoy agregando las propiedades específicas del usuario, a través del threadcontext, es correcta? ¿Esto siempre registrará la información correcta, incluso bajo carga? ¿Cuándo usarías threadlogicalcontext? ¿Hay una mejor manera de hacer esto?
Gracias
Solo tenga cuidado si usa codificación paralela ya que HttpContext.Current puede necesitar copiarse en cualquier subproceso de trabajo si se agregan al registro. –
¿En qué parte de global.asax.cs pondría la llamada a HttpContextUserProvider? – Rory
ASP.Net tiene un almacenamiento específico de contexto. Vea aquí: http://msdn.microsoft.com/en-us/library/system.web.httpcontext.items.aspx – MatteoSp