.net core的服务日志

namespace SwiftCode.BBS.Extensions.AOP
{
    public class BbLogsAOP : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            //invocation.TargetType.Name是类名 Method.Name方法名 Arguments请求参数
            var dateIntercept =
                $" {invocation.TargetType.Name}.{invocation.Method.Name}({string.Join(",", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray())})";
            try
            {
                invocation.Proceed();
            }
            catch (Exception ex)
            {
                dateIntercept += $" 异常:{ex.Message}";
            }
            //拦截方法执行结果返回
            dateIntercept += $" 返回值:{invocation.ReturnValue}";
            //输出到日志
            var path = Directory.GetCurrentDirectory() + @"\Log";
            if (!Directory.Exists(path)) { 
                Directory.CreateDirectory(path);
            }
            string fileName = path + $@"\log{DateTime.Now.ToString("yyyyMMddHHmmss")}.log";
            StreamWriter sw = File.AppendText(fileName);
            sw.WriteLine(dateIntercept);
            sw.Close();
        }
    }
}

 

 

namespace SwiftCode.BBS.Extensions.ServiceExtensions
{
    public class AutofacModuleRegister:Autofac.Module
    {
        protected override void Load(ContainerBuilder containerBuilder)
        {
            // 1. 首先注册拦截器本身
            containerBuilder.RegisterType<BbLogsAOP>()
                           .AsSelf()
                           .InstancePerLifetimeScope();

            //服务项目程序集
            Assembly service = Assembly.Load("Swift.BBS.Service");
            Assembly repository = Assembly.Load("Swift.BBS.Repository");
            //项目必须以xxx结尾
            containerBuilder.RegisterAssemblyTypes(service).Where(n => n.Name.EndsWith("Service") && !n.IsAbstract)//IsAbstract指的是抽象类
                .EnableInterfaceInterceptors()  // 启用接口拦截
                .InterceptedBy(typeof(BbLogsAOP))  // 指定使用的拦截器(这样是全局使用,可以使用在单独的service或类上用特性这样只针对个别)
                .InstancePerLifetimeScope().AsImplementedInterfaces();
            containerBuilder.RegisterAssemblyTypes(repository).Where(n => n.Name.EndsWith("Repository") && !n.IsAbstract)
                .EnableInterfaceInterceptors()
                .InterceptedBy(typeof(BbLogsAOP))
                .InstancePerLifetimeScope().AsImplementedInterfaces();
        }
    }
}

 

posted @ 2025-09-18 17:55  爱晒太阳的懒猫。。  阅读(6)  评论(0)    收藏  举报