using System.Diagnostics; using AspectInjector.Broker; using Serilog; namespace DispenserCommon.Aop; [Aspect(Scope.Global)] [Injection(typeof(ConsumeTime))] public class ConsumeTime(string title) : Attribute { public ConsumeTime() : this("") { Title = ""; } public string Title { get; set; } = title; /// /// 通过AOP实现方法执行前后的时间消耗 /// /// /// /// /// /// /// [Advice(Kind.Around)] public object Around([Argument(Source.Name)] string name, [Argument(Source.Arguments)] object[] args, [Argument(Source.Type)] Type hostType, [Argument(Source.Target)] Func target, [Argument(Source.Triggers)] Attribute[] triggers) { var sw = Stopwatch.StartNew(); try { var result = target(args); return result; } finally { sw.Stop(); Log.Information( $"方法 {(Title != "" ? Title : name)} 执行时间:{sw.Elapsed.TotalMilliseconds}ms"); } } }