エラーログを保存するテーブルをdbに作成します。私は、EFとLogsというテーブルを使用しています。
クラスを作成します。
public class MyAppExceptionFilter : IExceptionFilter
{
private MyApp.Models.ApplicationDbContext db = new Models.ApplicationDbContext();
public void OnException(ExceptionContext context)
{
Exception ex = context.Exception;
Log log = new Log();
log.DateTime = DateTime.Now;
log.LogText = "Exception happened, text:" + ex.Message;
try
{
log.LogText +="User details:"+context.HttpContext.User.Identity.Name;
}
catch
{
log.LogText += "User details:none";
}
db.Logs.Add(log);
db.SaveChanges();
}
}
App_StartフォルダーのFilterConfig.csに次を追加します。
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
*filters.Add(new MyAppExceptionFilter());*
}