我正在尝试在数据库中存储自定义日志记录错误,所以我有
public enum Events
{
Error,
Info,
Debug
}
public class Logging
{
public int LoggingID { get; set; }
public Events EventName { get; set; }
public string Message { get; set; }
public virtual Customer Customer { get; set; }
}
并且我为每个事件制作了一个类似于此示例的消息
LogHelper.Infos(" Running application ");
ConfigureAuth(app);
如何将这些事件存储在数据库中?
答案 0 :(得分:0)
您可以像这样定义您的Log实体:
public class LogAction
{
public DateTime PerformedAt { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
public string Description { get; set; }
public string UserName { get; set; }
public string Ip { get; set; }
}
然后你可以创建一个这样的自定义属性:
public class LogAttribute : ActionFilterAttribute
{
public string Description { get; set; }
public IUnitOfWork Uow { get; set; }
public ILogActionService LogActionService { get; set; }
public IApplicationUserManager ApplicationUserManager { get; set; }
public LogAttribute(string desciption)
{
Description = desciption;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
string currentUserId = null;
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
currentUserId = filterContext.HttpContext.User.Identity.GetUserId();
}
var model = new LogAction
{
UserName = currentUserId ?? "Anonymouse user",
Action = filterContext.ActionDescriptor.ActionName,
Controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
Description = Description,
PerformedAt = DateTime.Now,
Ip = Helper.Helper.GetUser_IP_Message()
};
LogActionService.AddLog(model);
Uow.SaveAllChanges();
base.OnActionExecuted(filterContext);
}
}
如您所见,在OnActionExecuted
方法中,您可以填充实体并将其保存到数据库中,因此您可以这样使用该属性:
[Log("Home Page")]
public ActionResult Index()
{
return View();
}