using Longbow.Web.Mvc; using PetaPoco; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Data.Common; namespace Bootstrap.DataAccess { /// /// /// public class Exceptions { /// /// /// public string Id { get; set; } /// /// /// public string AppDomainName { get; set; } /// /// /// public string ErrorPage { get; set; } /// /// /// public string UserId { get; set; } /// /// /// public string UserIp { get; set; } /// /// /// public string ExceptionType { get; set; } /// /// /// public string Message { get; set; } /// /// /// public string StackTrace { get; set; } /// /// /// public DateTime LogTime { get; set; } /// /// 获得/设置 时间描述 2分钟内为刚刚 /// [ResultColumn] public string Period { get; set; } /// /// /// public string Category { get; set; } private static void ClearExceptions() => System.Threading.Tasks.Task.Run(() => { DbManager.Create().Execute("delete from Exceptions where LogTime < @0", DateTime.Now.AddMonths(0 - DictHelper.RetrieveExceptionsLogPeriod())); }); /// /// /// /// /// /// public virtual bool Log(Exception ex, NameValueCollection additionalInfo) { if (ex == null) return true; var errorPage = additionalInfo?["ErrorPage"] ?? (ex.GetType().Name.Length > 50 ? ex.GetType().Name.Substring(0, 50) : ex.GetType().Name); var loopEx = ex; var category = "App"; while (loopEx != null) { if (typeof(DbException).IsAssignableFrom(loopEx.GetType())) { category = "DB"; break; } loopEx = loopEx.InnerException; } try { // 防止数据库写入操作失败后陷入死循环 DbManager.Create().Insert(new Exceptions { AppDomainName = AppDomain.CurrentDomain.FriendlyName, ErrorPage = errorPage, UserId = additionalInfo?["UserId"], UserIp = additionalInfo?["UserIp"], ExceptionType = ex.GetType().FullName, Message = ex.Message, StackTrace = ex.StackTrace, LogTime = DateTime.Now, Category = category }); ClearExceptions(); } catch { } return true; } /// /// 查询一周内所有异常 /// /// public virtual IEnumerable Retrieves() => DbManager.Create().Fetch("select * from Exceptions where LogTime > @0 order by LogTime desc", DateTime.Now.AddMonths(0 - DictHelper.RetrieveExceptionsLogPeriod())); /// /// /// /// /// /// /// public virtual Page RetrievePages(PaginationOption po, DateTime? startTime, DateTime? endTime) { var sql = new Sql("select * from Exceptions"); if (startTime.HasValue) sql.Append("where LogTime > @0", startTime.Value); if (endTime.HasValue) sql.Append("where LogTime < @0", endTime.Value.AddDays(1).AddSeconds(-1)); if (startTime == null && endTime == null) sql.Append("where LogTime > @0", DateTime.Today.AddMonths(0 - DictHelper.RetrieveExceptionsLogPeriod())); sql.Append($"order by {po.Sort} {po.Order}"); return DbManager.Create().Page(po.PageIndex, po.Limit, sql); } } }