新增差异日志记录到库

This commit is contained in:
不做码农 2023-07-20 18:20:59 +08:00
parent 1ba31c17cf
commit 95b0178dd4
10 changed files with 111 additions and 23 deletions

View File

@ -5,6 +5,8 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using System; using System;
using System.Security.Claims; using System.Security.Claims;
using System.Security.Principal;
using System.Xml.Linq;
namespace Infrastructure namespace Infrastructure
{ {
@ -28,6 +30,10 @@ namespace Infrastructure
/// </summary> /// </summary>
public static ClaimsPrincipal User => HttpContext?.User; public static ClaimsPrincipal User => HttpContext?.User;
/// <summary> /// <summary>
/// 获取用户名
/// </summary>
public static string UserName => User?.Identity?.Name;
/// <summary>
/// 获取Web主机环境 /// 获取Web主机环境
/// </summary> /// </summary>
public static IWebHostEnvironment WebHostEnvironment => InternalApp.WebHostEnvironment; public static IWebHostEnvironment WebHostEnvironment => InternalApp.WebHostEnvironment;

View File

@ -2,6 +2,7 @@ using Infrastructure;
using Infrastructure.Extensions; using Infrastructure.Extensions;
using SqlSugar; using SqlSugar;
using SqlSugar.IOC; using SqlSugar.IOC;
using System.Security.Principal;
using ZR.Model; using ZR.Model;
using ZR.Model.System; using ZR.Model.System;
@ -93,7 +94,7 @@ namespace ZR.Admin.WebApi.Extensions
}; };
db.GetConnectionScope(configId).Aop.OnError = (ex) => db.GetConnectionScope(configId).Aop.OnError = (ex) =>
{ {
var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value)); //var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
string sql = "【错误SQL】" + UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n"; string sql = "【错误SQL】" + UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n";
logger.Error(ex, $"{sql}\r\n{ex.Message}\r\n{ex.StackTrace}"); logger.Error(ex, $"{sql}\r\n{ex.Message}\r\n{ex.StackTrace}");
@ -101,7 +102,44 @@ namespace ZR.Admin.WebApi.Extensions
db.GetConnectionScope(configId).Aop.DataExecuting = (oldValue, entiyInfo) => db.GetConnectionScope(configId).Aop.DataExecuting = (oldValue, entiyInfo) =>
{ {
}; };
//差异日志功能
db.GetConnectionScope(configId).Aop.OnDiffLogEvent = it =>
{
//操作前记录 包含: 字段描述 列名 值 表名 表描述
var editBeforeData = it.BeforeData;//插入Before为null之前还没进库
//操作后记录 包含: 字段描述 列名 值 表名 表描述
var editAfterData = it.AfterData;
var sql = it.Sql;
var parameter = it.Parameters;
var data = it.BusinessData;//这边会显示你传进来的对象
var time = it.Time;
var diffType = it.DiffType;//enum insert 、update and delete
if (diffType == DiffType.delete)
{
string name = App.UserName;
foreach (var item in editBeforeData)
{
var pars = db.Utilities.SerializeObject(item.Columns.ToDictionary(it => it.ColumnName, it => it.Value));
SqlDiffLog log = new()
{
AfterData = pars,
BusinessData = data,
DiffType = diffType.ToString(),
Sql = sql,
TableName = item.TableName,
UserName = name,
AddTime = DateTime.Now
};
//logger.WithProperty("title", data).Info(pars);
db.GetConnectionScope(configId).Insertable(log).ExecuteReturnSnowflakeId();
}
}
//Write logic
};
db.GetConnectionScope(configId).CurrentConnectionConfig.MoreSettings = new ConnMoreSettings() db.GetConnectionScope(configId).CurrentConnectionConfig.MoreSettings = new ConnMoreSettings()
{ {
IsAutoRemoveDataCache = true IsAutoRemoveDataCache = true

View File

@ -164,6 +164,36 @@ namespace ZR.Admin.WebApi.Extensions
{ {
return context != null ? context.Request.QueryString.Value : ""; return context != null ? context.Request.QueryString.Value : "";
} }
/// <summary>
/// 获取body请求参数
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static string GetBody(this HttpContext context)
{
context.Request.EnableBuffering();
//context.Request.Body.Seek(0, SeekOrigin.Begin);
//using var reader = new StreamReader(context.Request.Body, Encoding.UTF8);
////需要使用异步方式才能获取
//return reader.ReadToEndAsync().Result;
string body = string.Empty;
var buffer = new MemoryStream();
context.Request.Body.Seek(0, SeekOrigin.Begin);
context.Request.Body.CopyToAsync(buffer);
buffer.Position = 0;
try
{
using StreamReader streamReader = new(buffer, Encoding.UTF8);
body = streamReader.ReadToEndAsync().Result;
}
finally
{
buffer?.Dispose();
}
return body;
}
/// <summary> /// <summary>
/// 设置请求参数 /// 设置请求参数
/// </summary> /// </summary>
@ -172,21 +202,14 @@ namespace ZR.Admin.WebApi.Extensions
public static void GetRequestValue(this HttpContext context, SysOperLog operLog) public static void GetRequestValue(this HttpContext context, SysOperLog operLog)
{ {
string reqMethod = operLog.RequestMethod; string reqMethod = operLog.RequestMethod;
string param; string param= string.Empty;
if (HttpMethods.IsPost(reqMethod) || HttpMethods.IsPut(reqMethod) || HttpMethods.IsDelete(reqMethod)) if (HttpMethods.IsPost(reqMethod) || HttpMethods.IsPut(reqMethod) || HttpMethods.IsDelete(reqMethod))
{ {
context.Request.Body.Seek(0, SeekOrigin.Begin); param = context.GetBody();
using var reader = new StreamReader(context.Request.Body, Encoding.UTF8);
//需要使用异步方式才能获取
param = reader.ReadToEndAsync().Result;
if (param.IsEmpty())
{
param = context.GetQueryString();
}
param = PwdRep().Replace(param, "***"); param = PwdRep().Replace(param, "***");
} }
else if (param.IsEmpty())
{ {
param = context.GetQueryString(); param = context.GetQueryString();
} }

View File

@ -24,6 +24,7 @@ namespace ZR.Admin.WebApi.Extensions
//db.CodeFirst.InitTables(entityes); //db.CodeFirst.InitTables(entityes);
//23个表,建议先使用下面方法初始化表,方便排查问题 //23个表,建议先使用下面方法初始化表,方便排查问题
db.CodeFirst.InitTables(typeof(SqlDiffLog));
db.CodeFirst.InitTables(typeof(SysUser)); db.CodeFirst.InitTables(typeof(SysUser));
db.CodeFirst.InitTables(typeof(SysRole)); db.CodeFirst.InitTables(typeof(SysRole));
db.CodeFirst.InitTables(typeof(SysDept)); db.CodeFirst.InitTables(typeof(SysDept));

View File

@ -99,9 +99,9 @@ builder.Services.AddDb(builder.Configuration, app.Environment);
//使用全局异常中间件 //使用全局异常中间件
app.UseMiddleware<GlobalExceptionMiddleware>(); app.UseMiddleware<GlobalExceptionMiddleware>();
//使可以多次多去body内容
app.Use((context, next) => app.Use((context, next) =>
{ {
//设置可以多次获取body内容
context.Request.EnableBuffering(); context.Request.EnableBuffering();
if (context.Request.Query.TryGetValue("access_token", out var token)) if (context.Request.Query.TryGetValue("access_token", out var token))
{ {

View File

@ -29,7 +29,6 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Folder Include="Controllers\" />
<Folder Include="Properties\PublishProfiles\" /> <Folder Include="Properties\PublishProfiles\" />
</ItemGroup> </ItemGroup>

View File

@ -0,0 +1,21 @@
namespace ZR.Model.System
{
[SugarTable("SqlDiffLog")]
public class SqlDiffLog
{
[SugarColumn(IsPrimaryKey = true)]
public long PId { get; set; }
public string TableName { get; set; }
[SugarColumn(Length = 4000)]
public object BusinessData { get; set; }
public string DiffType { get; set; }
[SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString)]
public string Sql { get; set; }
[SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString)]
public string BeforeData { get; set; }
[SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString)]
public string AfterData { get; set; }
public string UserName { get; set; }
public DateTime AddTime { get; set; }
}
}

View File

@ -56,7 +56,7 @@ namespace ZR.Repository
} }
public IInsertable<T> Insertable(T t) public IInsertable<T> Insertable(T t)
{ {
return Context.Insertable<T>(t); return Context.Insertable(t);
} }
#endregion add #endregion add
@ -212,13 +212,13 @@ namespace ZR.Repository
/// </summary> /// </summary>
/// <param name="obj"></param> /// <param name="obj"></param>
/// <returns></returns> /// <returns></returns>
public int Delete(object[] obj) public int Delete(object[] obj, string title = "")
{ {
return Context.Deleteable<T>().In(obj).ExecuteCommand(); return Context.Deleteable<T>().In(obj).EnableDiffLogEventIF(title.IsNotEmpty(), title).ExecuteCommand();
} }
public int Delete(object id) public int Delete(object id, string title = "")
{ {
return Context.Deleteable<T>(id).ExecuteCommand(); return Context.Deleteable<T>(id).EnableDiffLogEventIF(title.IsNotEmpty(), title).ExecuteCommand();
} }
public int DeleteTable() public int DeleteTable()
{ {

View File

@ -47,8 +47,8 @@ namespace ZR.Repository
#region delete #region delete
IDeleteable<T> Deleteable(); IDeleteable<T> Deleteable();
int Delete(object[] obj); int Delete(object[] obj, string title = "");
int Delete(object id); int Delete(object id, string title = "");
int DeleteTable(); int DeleteTable();
bool Truncate(); bool Truncate();

View File

@ -70,7 +70,7 @@ namespace ZR.Service.System
/// <returns>结果</returns> /// <returns>结果</returns>
public int DeleteOperLogByIds(long[] operIds) public int DeleteOperLogByIds(long[] operIds)
{ {
return Context.Deleteable<SysOperLog>().In(operIds).ExecuteCommand(); return Delete(operIds);
} }
/// <summary> /// <summary>