是否可以使用ELMAH进行以下操作?
logger.Log(" something");
我是这样做的:
try
{
// Code that might throw an exception
}
catch(Exception ex)
{
// I need to log error here...
}
ELMAH不会自动记录此异常,因为它已被处理。
是否可以使用ELMAH进行以下操作?
logger.Log(" something");
我是这样做的:
try
{
// Code that might throw an exception
}
catch(Exception ex)
{
// I need to log error here...
}
ELMAH不会自动记录此异常,因为它已被处理。
当前回答
有时CurrentHttpContext可能不可用。
定义
public class ElmahLogger : ILogger
{
public void LogError(Exception ex, string contextualMessage = null, bool withinHttpContext = true)
{
try
{
var exc = contextualMessage == null
? ex
: new ContextualElmahException(contextualMessage, ex);
if (withinHttpContext)
ErrorSignal.FromCurrentContext().Raise(exc);
else
ErrorLog.GetDefault(null).Log(new Error(exc));
}
catch { }
}
}
Use
public class MyClass
{
readonly ILogger _logger;
public MyClass(ILogger logger)
{
_logger = logger;
}
public void MethodOne()
{
try
{
}
catch (Exception ex)
{
_logger.LogError(ex, withinHttpContext: false);
}
}
}
其他回答
直接日志写入方法,自ELMAH 1.0开始工作:
try
{
some code
}
catch(Exception ex)
{
Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(ex));
}
ELMAH 1.2引入了更灵活的API:
try
{
some code
}
catch(Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
这两种解决方案之间存在差异:
Raise方法对异常应用ELMAH过滤规则。日志方法没有。 Raise是基于订阅的,能够将一个异常记录到多个记录器中。
可以使用Elmah.ErrorSignal()方法记录问题而不引发异常。
try
{
// Some code
}
catch(Exception ex)
{
// Log error
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
// Continue
}
我希望在一个线程中做同样的事情,我已经开始从我的MVC4应用程序中排队邮件,因此当异常被引发时,我没有HttpContext可用。为了做到这一点,我最终与以下基于这个问题和另一个答案在这里找到:elmah:异常没有HttpContext?
在配置文件中,我指定了一个应用程序名称:
<elmah>
<security allowRemoteAccess="false" />
<errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="ELMAH" applicationName="myApplication"/>
</elmah>
然后在代码中(就像上面提供的答案,但没有HttpContext)你可以传递null而不是HttpContext:
ThreadPool.QueueUserWorkItem(t => {
try {
...
mySmtpClient.Send(message);
} catch (SomeException e) {
Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(e));
}
});
有时CurrentHttpContext可能不可用。
定义
public class ElmahLogger : ILogger
{
public void LogError(Exception ex, string contextualMessage = null, bool withinHttpContext = true)
{
try
{
var exc = contextualMessage == null
? ex
: new ContextualElmahException(contextualMessage, ex);
if (withinHttpContext)
ErrorSignal.FromCurrentContext().Raise(exc);
else
ErrorLog.GetDefault(null).Log(new Error(exc));
}
catch { }
}
}
Use
public class MyClass
{
readonly ILogger _logger;
public MyClass(ILogger logger)
{
_logger = logger;
}
public void MethodOne()
{
try
{
}
catch (Exception ex)
{
_logger.LogError(ex, withinHttpContext: false);
}
}
}
我在使用ASP。NET core和ElmahCore。
要手动记录HttpContext中的错误(在控制器中),只需写:
using ElmahCore;
...
HttpContext.RiseError(new Exception("Your Exception"));
在没有HttpContext的应用程序的另一部分:
using ElmahCore;
...
ElmahExtensions.RiseError(new Exception("Your Exception"));