Aop.OnExecutingChangeSql 本地调试可以,但是发布linux 就不行了,帮我看下这个配置代码 返回

SqlSugar 沟通中
3 539

    internal static class SqlSugarSetup

    {

        internal static List<string> tablelist = new List<string>()

                {

                    "SysLogOp","SysLogVis","SysLogDiff","mk_jobtriggers","sys_jobtriggers","mk_jobdetails","sys_jobdetails"

                };

        internal static void AddSqlsugarSetup(this IServiceCollection services)

        {

            if (services is null)

            {

                throw new ArgumentNullException(nameof(services));

            }


            using (ServiceProvider provider = services.BuildServiceProvider())

            {


                List<ConnectionConfig> connectionConfigs = new List<ConnectionConfig>();


                services.GetConfiguration().GetSection("DBConfigs").Bind(connectionConfigs);


                ConnectionConfig? config = connectionConfigs.FirstOrDefault(it => it.ConfigId.ToString().ToLower() == App.GetConfig<string>("MainDB"));


                config.ConfigId = config.ConfigId.ToString().ToLower();

                config.IsAutoCloseConnection = true;

                config.MoreSettings = new ConnMoreSettings

                {

                    IsWithNoLockQuery = true,

                    IsAutoRemoveDataCache = true

                };

                config.InitKeyType = InitKeyType.Attribute;



                SqlSugarScope sqlSugarScope = new SqlSugarScope(config,

                //全局上下文生效

                db =>

                {

                    SetDbAop(db.GetConnection(config.ConfigId), config.DbType);


                    SetDbDiffLog(db.GetConnection(config.ConfigId), config.DbType, services.GetConfiguration());

                });

                services.AddDistributedMemoryCache();


                services.AddSingleton<ISqlSugarClient>(sqlSugarScope);


                services.TryAddScoped(typeof(ISqlDbContext), typeof(SqlDbContext));


                #region 注入仓储


                services.TryAddScoped(typeof(IBasicReadOnlyRepository<>), typeof(BasicReadOnlyRepository<>));


                services.TryAddScoped(typeof(IBasicRepository<>), typeof(BasicRepository<>));


                services.TryAddScoped(typeof(IGetDbRepository<>), typeof(GetDbRepository<>));


                #endregion



                //批量配置差异日志事件

                StaticConfig.CompleteInsertableFunc =

                StaticConfig.CompleteUpdateableFunc =

                StaticConfig.CompleteDeleteableFunc = it =>

                {

                    if (!tablelist.Contains(it.GetType().GenericTypeArguments[0].Name))

                    {

                        //反射的方法可能多个就需要用GetMethods().Where

                        var method = it.GetType().GetMethod("EnableDiffLogEvent");

                        method.Invoke(it, new object[] { null });

                    }

                };

            }

        }


        /// <summary>

        /// 配置Aop

        /// </summary>

        /// <param name="db"></param>

        internal static void SetDbAop(SqlSugarProvider db, DbType dbType)

        {

            var _logger = Log.CreateLogger<SqlSugarSqlLoggingMonitor>();


            var config = db.CurrentConnectionConfig;


            // 设置超时时间

            db.Ado.CommandTimeOut = 30;


            // 打印SQL语句

            db.Aop.OnLogExecuting = (sql, pars) =>

            {

                if (Debugger.IsAttached)

                {

                    var template = TP.Wrapper("正确SQL", "正确SQL", $"##SQL语句## {UtilMethods.GetSqlString(dbType, sql.Replace("\r\n", ""), pars)}");


                    _logger.LogInformation(template);

                }

            };

            db.Aop.OnError = (exp) =>

            {

                if (exp.Parametres == null) return;

                if (Debugger.IsAttached)

                {

                    var template = TP.Wrapper("错误SQL", "错误SQL", $"##SQL语句## {UtilMethods.GetSqlString(dbType, exp.Sql.Replace("\r\n", ""), (SugarParameter[])exp.Parametres)}");


                    _logger.LogError(template);

                }

            

            };


            // 数据审计 

            db.Aop.DataExecuting = (oldValue, entityInfo) =>

            {

                if (entityInfo.OperationType == DataFilterType.InsertByObject)

                {

                    if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(string))

                    {

                        var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);

                        if (Convert.ToString(id).IsNullOrWhiteSpace())

                            entityInfo.SetValue(IdGenerater.GetNextId());

                    }

                    if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))

                    {

                        var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);

                        if (Convert.ToString(id).IsNullOrWhiteSpace() || (long)id == 0)

                            entityInfo.SetValue(IdGenerater.GetNextId());

                    }

                }

            };


            //监听超过30秒的sql

            db.Aop.OnLogExecuted = (sql, pars) =>

            {

                //执行时间超过30秒

                if (db.Ado.SqlExecutionTime.TotalSeconds > 30)

                {

                    var template = TP.Wrapper("执行超过30秒的sql", "执行超过30秒的sql", $"##SQL语句## {UtilMethods.GetSqlString(dbType, sql.Replace("\r\n", ""), pars)}");

                    _logger.LogError(template);

                }

            };


            db.Aop.OnExecutingChangeSql = (sql, pars) => //可以修改SQL和参数的值

            {

                if (!sql.StartsWith("SELECT ") && pars is not null)

                {

                    foreach (var item in pars.Where(e => (e.DbType == System.Data.DbType.Date || e.DbType == System.Data.DbType.DateTime)))

                    {

                        if (item.Value is null)

                        {

                            item.Value = null;//处理日期传空的问题

                        }

                        if (((DateTime)item.Value).Year is 1900 or 1)

                        {

                            item.Value = null;//处理日期传空的问题

                        }

                    }

                }

                return new KeyValuePair<string, SugarParameter[]>(sql, pars);

            };

        }


        /// <summary>

        /// 开启库表差异化日志

        /// </summary>

        /// <param name="db"></param>

        /// <param name="config"></param>

        internal static void SetDbDiffLog(SqlSugarProvider db, DbType type, IConfiguration configuration)

        {

      

            db.Aop.OnDiffLogEvent = u =>

            {

                //bool isdifflog = true;//是否记录日志


                if (!u.AfterData.IsNullOrEmpty())

                {

                    var _logger = Log.CreateLogger<SqlSugarSqlLoggingDiffMonitor>();


                    var logDiff = new SysLogDiff

                    {

                        // 操作后记录(字段描述、列名、值、表名、表描述)

                        AfterData = u.AfterData,

                        // 操作前记录(字段描述、列名、值、表名、表描述)

                        BeforeData = u.BeforeData,

                        // 传进来的对象

                        BusinessData = JSON.Serialize(u.BusinessData),

                        // 枚举(insert、update、delete)

                        DiffType = u.DiffType.ToString(),

                        Sql = UtilMethods.GetSqlString(type, u.Sql, u.Parameters),

                        Parameters = JSON.Serialize(u.Parameters),

                        Duration = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds

                    };


                    // 创建日志上下文

                    var logContext = new LogContext();

                    logContext.Set("logDiffMonitor", JSON.Serialize(logDiff));


                    // 设置日志上下文

                    using var scope = _logger.ScopeContext(logContext);


                    try

                    {

                        if (u.AfterData is { Count: <= 100 })

                        {

                            var template = TP.Wrapper("差异信息", "差异信息", $"{JSON.Serialize(logDiff)}");

                            _logger.LogInformation(template);

                        }

                    }

                    catch (AggregateException)

                    {


                    }


                } 

            };


        }

    }


热忱回答3

  • Aop.OnExecutingChangeSql 本地调试可以进入这个方法没有的,发布之后就没有进入,具体看下什么原因


    0 回复
  • fate sta fate sta VIP0
    2026/3/23

    不存在这个问题。 只和你的代码有关系。比如路径读取等。或者AOP注册是否有效等。

    0 回复
  •         public SqlSugarProvider provider<T>(string configid)

            {

                var redisCache = lazyServiceProvider.LazyGetRequiredService<IRedisCacheManager>();

                var user = lazyServiceProvider.LazyGetRequiredService<IUserLoginInfo>();

                var _iconfiguration = lazyServiceProvider.LazyGetRequiredService<IConfiguration>();


                // 若实体贴有系统表特性,则返回默认的连接

                if (typeof(T).IsDefined(typeof(SystemTableAttribute), false))

                {

                    configid = "morelink";

                }

                else

                {

                    if (configid.IsNullOrWhiteSpace())

                    {

                        configid = user.GetLoginDb() is null ? "morelink" : user.GetLoginDb();

                    }

                }


                // 双重检查锁定,确保连接添加的原子性

                if (!iTenant.IsAnyConnection(configid))

                {

                    lock (_connectionLock)

                    {

                        // 再次检查,避免在锁等待期间其他线程已添加

                        if (!iTenant.IsAnyConnection(configid))

                        {

                            ConnectionConfig tenant = new();


                            List<ConnectionConfig> connectionConfigs = new List<ConnectionConfig>();


                            _iconfiguration.GetSection("DBConfigs").Bind(connectionConfigs);


                            //查询租户库,租户库不存在,则读取默认库

                            if (connectionConfigs.Any(it => it.ConfigId.ToString() == configid))

                            {

                                tenant = connectionConfigs.FirstOrDefault(it => it.ConfigId.ToString() == configid);

                            }

                            else

                            {

                                tenant = connectionConfigs.FirstOrDefault(it => it.ConfigId.ToString() == "default");


                                (tenant is null).BusinessException($"默认数据库连接缺失!");


                                tenant.ConnectionString = tenant.ConnectionString.Replace("database=default", $"database={configid}");

                                tenant.ConfigId = configid;

                            }


                            if (tenant is not null)

                            {

                                iTenant.AddConnection(new ConnectionConfig()

                                {

                                    ConfigId = tenant.ConfigId,

                                    DbType = tenant.DbType,

                                    ConnectionString = tenant.ConnectionString,

                                    IsAutoCloseConnection = true,

                                });


                                // 确保AOP只设置一次(使用锁内检查并添加)

                                if (!_aopRegistered.Contains(configid))

                                {

                                    SqlSugarSetup.SetDbAop(iTenant.GetConnection(configid), tenant.DbType);

                                    SqlSugarSetup.SetDbDiffLog(iTenant.GetConnection(configid), tenant.DbType, _iconfiguration);

                                    _aopRegistered.Add(configid);

                                }

                            }

                        }

                    }

                }

                

                return iTenant.GetConnection(configid);

            }


    是不是这个  SqlSugarProvider 有问题   SqlSugarSetup.SetDbAop

      /// <summary>

      /// 配置Aop

      /// </summary>

      /// <param name="db"></param>

      internal static void SetDbAop(SqlSugarProvider db, DbType dbType)


    0 回复