using Longbow; using Longbow.Configuration; using Longbow.Web.Mvc; using PetaPoco; using System; using System.Collections.Generic; using System.Collections.Specialized; 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分钟内为刚刚 /// public string Period { get; set; } private static void ClearExceptions() => System.Threading.Tasks.Task.Run(() => { DbManager.Db.Execute("delete from Exceptions where LogTime < @0", DateTime.Now.AddMonths(0 - LgbConvert.ReadValue(ConfigurationManager.AppSettings["KeepExceptionsPeriod"], 1))); }); /// /// /// /// /// /// public virtual bool Log(Exception ex, NameValueCollection additionalInfo) { if (ex == null) throw new ArgumentNullException(nameof(ex)); var errorPage = additionalInfo?["ErrorPage"] ?? (ex.GetType().Name.Length > 50 ? ex.GetType().Name.Substring(0, 50) : ex.GetType().Name); DbManager.Db.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 }); ClearExceptions(); return true; } /// /// 查询一周内所有异常 /// /// public virtual IEnumerable Retrieves() => DbManager.Db.Fetch("select * from Exceptions where LogTime > @0 order by LogTime desc", DateTime.Now.AddDays(-7)); /// /// /// /// /// /// /// /// 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); if (startTime == null && endTime == null) sql.Append("where LogTime > @0", DateTime.Today.AddDays(-7)); sql.Append("order by @0", $"{po.Sort} {po.Order}"); return DbManager.Db.Page(po.PageIndex, po.Limit, sql); } } }