优化sql日志写入文件
This commit is contained in:
@@ -40,7 +40,6 @@ namespace ZR.Admin.WebApi.Extensions
|
||||
DbType = (IocDbType)dbType,
|
||||
IsAutoCloseConnection = true
|
||||
}
|
||||
//...增加其他数据库
|
||||
};
|
||||
SugarIocServices.AddSqlSugar(iocList);
|
||||
ICacheService cache = new SqlSugarCache();
|
||||
@@ -59,23 +58,33 @@ namespace ZR.Admin.WebApi.Extensions
|
||||
private static void SetSugarAop(SqlSugarClient db, IocConfig iocConfig, ICacheService cache)
|
||||
{
|
||||
var config = db.GetConnection(iocConfig.ConfigId).CurrentConnectionConfig;
|
||||
|
||||
|
||||
string configId = config.ConfigId;
|
||||
db.GetConnectionScope(configId).Aop.OnLogExecuting = (sql, pars) =>
|
||||
db.GetConnectionScope(configId).Aop.OnLogExecuted = (sql, pars) =>
|
||||
{
|
||||
string log = $"【db{configId} SQL语句】{UtilMethods.GetSqlString(config.DbType, sql, pars)}\n";
|
||||
if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
|
||||
logger.Warn(log);
|
||||
else if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("TRUNCATE", StringComparison.OrdinalIgnoreCase))
|
||||
logger.Error(log);
|
||||
else
|
||||
if (sql.TrimStart().StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
logger.Info(log);
|
||||
}
|
||||
else if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
logger.Warn(log);
|
||||
}
|
||||
else if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("TRUNCATE", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
logger.Error(log);
|
||||
}
|
||||
else
|
||||
{
|
||||
log = $"【db{configId} SQL语句】dbo.{sql} {string.Join(", ", pars.Select(x => x.ParameterName + " = " + GetParsValue(x)))};\n";
|
||||
logger.Info(log);
|
||||
}
|
||||
};
|
||||
|
||||
db.GetConnectionScope(configId).Aop.OnError = (e) =>
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
logger.Error(e, $"执行SQL出错:{e.Message}");
|
||||
logger.Error(e, $"执行SQL出错:{e.Message},{e.StackTrace}");
|
||||
};
|
||||
|
||||
db.GetConnectionScope(configId).CurrentConnectionConfig.MoreSettings = new ConnMoreSettings()
|
||||
@@ -103,6 +112,15 @@ namespace ZR.Admin.WebApi.Extensions
|
||||
db.CodeFirst.SetStringDefaultLength(512).InitTables(entityes);
|
||||
}
|
||||
|
||||
private static object GetParsValue(SugarParameter x)
|
||||
{
|
||||
if (x.DbType == System.Data.DbType.String || x.DbType == System.Data.DbType.DateTime || x.DbType == System.Data.DbType.String)
|
||||
{
|
||||
return "'" + x.Value + "'";
|
||||
}
|
||||
return x.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 数据过滤
|
||||
/// </summary>
|
||||
|
||||
Reference in New Issue
Block a user