Exemple #1
0
        /// <summary>
        /// 实现接口方法
        /// </summary>
        /// <param name="invocation"></param>
        public void Intercept(IInvocation invocation)
        {
            // 事前处理: 在服务方法执行之前,做相应的逻辑处理
            var dataIntercept = $"【当前执行方法】:{ invocation.Method.Name} \r\n 【携带的参数有】: {string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray())} \r\n";

            try
            {
                // 执行当前访问的服务方法,(注意:如果下边还有其他的AOP拦截器的话,会跳转到其他的AOP里)
                invocation.Proceed();
                //异步方法
                if (IsAsyncMethod(invocation.Method))
                {
                    if (invocation.Method.ReturnType == typeof(Task))
                    {
                        invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithPostActionAndFinally(
                            (Task)invocation.ReturnValue,
                            async() => await SuccessAction(invocation, dataIntercept), /*成功时执行*/
                            ex =>
                        {
                            LoggerError(ex, dataIntercept);
                        });
                    }
                    //Task<TResult>
                    else
                    {
                        invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithPostActionAndFinallyAndGetResult(
                            invocation.Method.ReturnType.GenericTypeArguments[0],
                            invocation.ReturnValue,

                            async(o) => await SuccessAction(invocation, dataIntercept, o),/*成功时执行*/
                            ex =>
                        {
                            LoggerError(ex, dataIntercept);
                        });
                    }
                }
                else
                {
                    //同步
                    dataIntercept += ($"【执行完成结果】:{invocation.ReturnValue}");
                    Parallel.For(0, 1, e =>
                    {
                        LoggerLock.OutPutLogger("AOPLog", new string[] { dataIntercept });
                    });
                }
            }
            catch
            {
            }

            // 事后处理: 在service被执行了以后,做相应的处理,这里是输出到日志文件
            dataIntercept += ($"【执行完成结果】:{invocation.ReturnValue}");

            // 输出到日志文件
            Parallel.For(0, 1, e =>
            {
                LoggerLock.OutPutLogger("AOPLog", new string[] { dataIntercept });
            });
        }
Exemple #2
0
        private void LoggerError(Exception ex, string dataIntercept)
        {
            if (ex != null)
            {
                //执行的 service 中,收录异常
                //MiniProfiler.Current.CustomTiming("Errors:", ex.Message);
                //执行的 service 中,捕获异常
                dataIntercept += ($"【执行完成结果】:方法中出现异常:{ex.Message + ex.InnerException}\r\n");


                //并行处理  异常日志里有详细的堆栈信息
                Parallel.For(0, 1, e =>
                {
                    LoggerLock.OutPutLogger("AOPLog", new string[] { dataIntercept });
                });
            }
        }
Exemple #3
0
        private async Task SuccessAction(IInvocation invocation, string dataIntercept, object o = null)
        {
            invocation.ReturnValue = o;
            var type = invocation.Method.ReturnType;

            if (typeof(Task).IsAssignableFrom(type))
            {
                var resultProperty = type.GetProperty("Result");
                //类型错误 都可以不要invocation参数,直接将o系列化保存到日志中
                dataIntercept += ($"【执行完成结果】:{JsonConvert.SerializeObject(invocation.ReturnValue)}");
            }
            else
            {
                dataIntercept += ($"【执行完成结果】:{invocation.ReturnValue}");
            }

            await Task.Run(() =>
            {
                Parallel.For(0, 1, e =>
                {
                    LoggerLock.OutPutLogger("AOPLog", new string[] { dataIntercept });
                });
            });
        }
        /// <summary>
        /// 链接数据库
        /// </summary>
        /// <param name="IsAutoCloseConnection">是否主动关闭数据库连接:设置为true无需使用using或者Close操作,默认false</param>
        /// <param name="OperationDBType">数据库的读写操作选择</param>
        private DataBaseConfig(bool IsAutoCloseConnection)
        {
            _connectionWriteStr = Appsettings.GetSettingNode(new string[] { "AppSettings", "MySql", "Write", "ConnectionString" });
            var connStr = Appsettings.GetSettingNode(new string[] { "AppSettings", "MySql", "Read", "ConnectionString" });

            if (!string.IsNullOrEmpty(connStr))
            {
                if (connStr.Contains('|'))
                {
                    _connectionReadStr.AddRange(connStr.Split('|'));
                }
                else
                {
                    _connectionReadStr.Add(connStr);
                }
            }

            if (string.IsNullOrEmpty(_connectionWriteStr))
            {
                throw new ArgumentNullException("数据库连接字符串为空");
            }

            List <SlaveConnectionConfig> connectionConfigs = null;

            if (_connectionReadStr != null && _connectionReadStr.Any())
            {
                connectionConfigs = new List <SlaveConnectionConfig>();
                foreach (var item in _connectionReadStr)
                {
                    connectionConfigs.Add(new SlaveConnectionConfig
                    {
                        ConnectionString = item,
                        HitRate          = 10
                    });
                }
            }

            bool reval    = false;
            var  isSqlAop = Appsettings.GetSettingNode(new string[] { "AppSettings", "SqlAOP", "Enabled" });

            reval = !string.IsNullOrEmpty(isSqlAop) ? bool.Parse(isSqlAop) : false;
            //数据库读写分离(自动将写的操作连接到主库,读的操作连接到次库)
            _db = new SqlSugarClient(new ConnectionConfig()
            {
                //主连接
                ConnectionString      = _connectionWriteStr,
                DbType                = DbType.MySql,
                IsAutoCloseConnection = IsAutoCloseConnection,
                IsShardSameThread     = false,
                //从连接
                SlaveConnectionConfigs = connectionConfigs,
                //如果是非正常的数据类型ORM不支持可以自已添加扩展,其他功能详见官网设置
                ConfigureExternalServices = new ConfigureExternalServices()
                {
                },
                //用于一些全局设置
                MoreSettings = new ConnMoreSettings()
                {
                    IsAutoRemoveDataCache = false  //为true表示可以自动删除二级缓存
                },
                AopEvents = new AopEvents
                {
                    OnLogExecuting = (sql, p) =>
                    {
                        if (reval)
                        {
                            Parallel.For(0, 1, e =>
                            {
                                //MiniProfiler.Current.CustomTiming("SQL:", GetParas(p) + "【SQL语句】:" + sql);
                                LoggerLock.OutPutLogger("SqlLog", new string[] { GetParas(p), "【SQL语句】:" + sql });
                            });
                        }
                    }
                }
            });
        }