平安校园
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

49 lines
2.3 KiB

  1. using UAParser;
  2. namespace SafeCampus.Web.Core;
  3. /// <summary>
  4. /// LoggingMonitor操作日志写入数据库插件
  5. /// </summary>
  6. public sealed class LoggingMonitorComponent : IServiceComponent
  7. {
  8. public void Load(IServiceCollection services, ComponentContext componentContext)
  9. {
  10. //Monitor日志配置
  11. services.AddMonitorLogging(options =>
  12. {
  13. options.JsonIndented = true;// 是否美化 JSON
  14. options.GlobalEnabled = true;//全局启用
  15. options.ConfigureLogger((logger, logContext, context) =>
  16. {
  17. var httpContext = context.HttpContext;//获取httpContext
  18. //获取头
  19. var userAgent = httpContext.Request.Headers["User-Agent"];
  20. if (string.IsNullOrEmpty(userAgent)) userAgent = "Other";//如果没有这个头就指定一个
  21. //获取客户端信息
  22. var client = Parser.GetDefault().Parse(userAgent);
  23. // 获取控制器/操作描述器
  24. // var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
  25. //操作名称默认是控制器名加方法名,自定义操作名称要在action上加Description特性
  26. //var option = $"{controllerActionDescriptor.ControllerName}/{controllerActionDescriptor.ActionName}";
  27. ////获取特性
  28. //var monitor = controllerActionDescriptor.MethodInfo.GetCustomAttribute<DescriptionAttribute>();
  29. //if (monitor != null)//如果有LoggingMonitor特性
  30. // option = monitor.Description;//则将操作名称赋值为控制器上写的title
  31. //logContext.Set(LoggingConst.Operation, option);//传操作名称
  32. logContext.Set(LoggingConst.CLIENT, client);//客户端信息
  33. logContext.Set(LoggingConst.PATH, httpContext.Request.Path.Value);//请求地址
  34. logContext.Set(LoggingConst.METHOD, httpContext.Request.Method);//请求方法
  35. });
  36. });
  37. //日志写入数据库配置
  38. services.AddDatabaseLogging<DatabaseLoggingWriter>(options =>
  39. {
  40. options.WriteFilter = logMsg =>
  41. {
  42. return logMsg.LogName == "System.Logging.LoggingMonitor";//只写入LoggingMonitor日志
  43. };
  44. });
  45. }
  46. }