From 95b0178dd401305c65c6ea4c8b1d7f1c74b35fe1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E4=B8=8D=E5=81=9A=E7=A0=81=E5=86=9C?= <599854767@qq.com>
Date: Thu, 20 Jul 2023 18:20:59 +0800
Subject: [PATCH] =?UTF-8?q?:sparkles:=20=E6=96=B0=E5=A2=9E=E5=B7=AE?=
=?UTF-8?q?=E5=BC=82=E6=97=A5=E5=BF=97=E8=AE=B0=E5=BD=95=E5=88=B0=E5=BA=93?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
Infrastructure/App/App.cs | 6 +++
ZR.Admin.WebApi/Extensions/DbExtension.cs | 42 +++++++++++++++++-
.../Extensions/HttpContextExtension.cs | 43 ++++++++++++++-----
ZR.Admin.WebApi/Extensions/InitTable.cs | 1 +
ZR.Admin.WebApi/Program.cs | 2 +-
ZR.Admin.WebApi/ZR.Admin.WebApi.csproj | 1 -
ZR.Model/System/SqlDiffLog.cs | 21 +++++++++
ZR.Repository/BaseRepository.cs | 12 +++---
ZR.Repository/IBaseRepository.cs | 4 +-
ZR.Service/System/SysOperLogService.cs | 2 +-
10 files changed, 111 insertions(+), 23 deletions(-)
create mode 100644 ZR.Model/System/SqlDiffLog.cs
diff --git a/Infrastructure/App/App.cs b/Infrastructure/App/App.cs
index 4c8357c..49a5b6a 100644
--- a/Infrastructure/App/App.cs
+++ b/Infrastructure/App/App.cs
@@ -5,6 +5,8 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
using System.Security.Claims;
+using System.Security.Principal;
+using System.Xml.Linq;
namespace Infrastructure
{
@@ -28,6 +30,10 @@ namespace Infrastructure
///
public static ClaimsPrincipal User => HttpContext?.User;
///
+ /// 获取用户名
+ ///
+ public static string UserName => User?.Identity?.Name;
+ ///
/// 获取Web主机环境
///
public static IWebHostEnvironment WebHostEnvironment => InternalApp.WebHostEnvironment;
diff --git a/ZR.Admin.WebApi/Extensions/DbExtension.cs b/ZR.Admin.WebApi/Extensions/DbExtension.cs
index 8a18433..8dd60e1 100644
--- a/ZR.Admin.WebApi/Extensions/DbExtension.cs
+++ b/ZR.Admin.WebApi/Extensions/DbExtension.cs
@@ -2,6 +2,7 @@ using Infrastructure;
using Infrastructure.Extensions;
using SqlSugar;
using SqlSugar.IOC;
+using System.Security.Principal;
using ZR.Model;
using ZR.Model.System;
@@ -13,7 +14,7 @@ namespace ZR.Admin.WebApi.Extensions
public static class DbExtension
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
-
+
///
/// 初始化db
///
@@ -93,7 +94,7 @@ namespace ZR.Admin.WebApi.Extensions
};
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";
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.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()
{
IsAutoRemoveDataCache = true
diff --git a/ZR.Admin.WebApi/Extensions/HttpContextExtension.cs b/ZR.Admin.WebApi/Extensions/HttpContextExtension.cs
index 8940c00..542065c 100644
--- a/ZR.Admin.WebApi/Extensions/HttpContextExtension.cs
+++ b/ZR.Admin.WebApi/Extensions/HttpContextExtension.cs
@@ -164,6 +164,36 @@ namespace ZR.Admin.WebApi.Extensions
{
return context != null ? context.Request.QueryString.Value : "";
}
+
+ ///
+ /// 获取body请求参数
+ ///
+ ///
+ ///
+ 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;
+ }
+
///
/// 设置请求参数
///
@@ -172,21 +202,14 @@ namespace ZR.Admin.WebApi.Extensions
public static void GetRequestValue(this HttpContext context, SysOperLog operLog)
{
string reqMethod = operLog.RequestMethod;
- string param;
+ string param= string.Empty;
if (HttpMethods.IsPost(reqMethod) || HttpMethods.IsPut(reqMethod) || HttpMethods.IsDelete(reqMethod))
{
- context.Request.Body.Seek(0, SeekOrigin.Begin);
- using var reader = new StreamReader(context.Request.Body, Encoding.UTF8);
- //需要使用异步方式才能获取
- param = reader.ReadToEndAsync().Result;
- if (param.IsEmpty())
- {
- param = context.GetQueryString();
- }
+ param = context.GetBody();
param = PwdRep().Replace(param, "***");
}
- else
+ if (param.IsEmpty())
{
param = context.GetQueryString();
}
diff --git a/ZR.Admin.WebApi/Extensions/InitTable.cs b/ZR.Admin.WebApi/Extensions/InitTable.cs
index 543f627..69bb24a 100644
--- a/ZR.Admin.WebApi/Extensions/InitTable.cs
+++ b/ZR.Admin.WebApi/Extensions/InitTable.cs
@@ -24,6 +24,7 @@ namespace ZR.Admin.WebApi.Extensions
//db.CodeFirst.InitTables(entityes);
//23个表,建议先使用下面方法初始化表,方便排查问题
+ db.CodeFirst.InitTables(typeof(SqlDiffLog));
db.CodeFirst.InitTables(typeof(SysUser));
db.CodeFirst.InitTables(typeof(SysRole));
db.CodeFirst.InitTables(typeof(SysDept));
diff --git a/ZR.Admin.WebApi/Program.cs b/ZR.Admin.WebApi/Program.cs
index 085ee6c..690339a 100644
--- a/ZR.Admin.WebApi/Program.cs
+++ b/ZR.Admin.WebApi/Program.cs
@@ -99,9 +99,9 @@ builder.Services.AddDb(builder.Configuration, app.Environment);
//使用全局异常中间件
app.UseMiddleware();
-//使可以多次多去body内容
app.Use((context, next) =>
{
+ //设置可以多次获取body内容
context.Request.EnableBuffering();
if (context.Request.Query.TryGetValue("access_token", out var token))
{
diff --git a/ZR.Admin.WebApi/ZR.Admin.WebApi.csproj b/ZR.Admin.WebApi/ZR.Admin.WebApi.csproj
index 630d749..23b6547 100644
--- a/ZR.Admin.WebApi/ZR.Admin.WebApi.csproj
+++ b/ZR.Admin.WebApi/ZR.Admin.WebApi.csproj
@@ -29,7 +29,6 @@
-
diff --git a/ZR.Model/System/SqlDiffLog.cs b/ZR.Model/System/SqlDiffLog.cs
new file mode 100644
index 0000000..c09f9cc
--- /dev/null
+++ b/ZR.Model/System/SqlDiffLog.cs
@@ -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; }
+ }
+}
diff --git a/ZR.Repository/BaseRepository.cs b/ZR.Repository/BaseRepository.cs
index 30a4a4b..e6d7351 100644
--- a/ZR.Repository/BaseRepository.cs
+++ b/ZR.Repository/BaseRepository.cs
@@ -56,7 +56,7 @@ namespace ZR.Repository
}
public IInsertable Insertable(T t)
{
- return Context.Insertable(t);
+ return Context.Insertable(t);
}
#endregion add
@@ -212,13 +212,13 @@ namespace ZR.Repository
///
///
///
- public int Delete(object[] obj)
+ public int Delete(object[] obj, string title = "")
{
- return Context.Deleteable().In(obj).ExecuteCommand();
+ return Context.Deleteable().In(obj).EnableDiffLogEventIF(title.IsNotEmpty(), title).ExecuteCommand();
}
- public int Delete(object id)
+ public int Delete(object id, string title = "")
{
- return Context.Deleteable(id).ExecuteCommand();
+ return Context.Deleteable(id).EnableDiffLogEventIF(title.IsNotEmpty(), title).ExecuteCommand();
}
public int DeleteTable()
{
@@ -376,7 +376,7 @@ namespace ZR.Repository
var result = source
.OrderByIF(parm.Sort.IsNotEmpty(), $"{parm.Sort.ToSqlFilter()} {(!string.IsNullOrWhiteSpace(parm.SortType) && parm.SortType.Contains("desc") ? "desc" : "asc")}")
.ToPageList(parm.PageNum, parm.PageSize, ref total);
-
+
page.TotalNum = total;
page.Result = result.Adapt>();
return page;
diff --git a/ZR.Repository/IBaseRepository.cs b/ZR.Repository/IBaseRepository.cs
index a1b4f66..697fa1f 100644
--- a/ZR.Repository/IBaseRepository.cs
+++ b/ZR.Repository/IBaseRepository.cs
@@ -47,8 +47,8 @@ namespace ZR.Repository
#region delete
IDeleteable Deleteable();
- int Delete(object[] obj);
- int Delete(object id);
+ int Delete(object[] obj, string title = "");
+ int Delete(object id, string title = "");
int DeleteTable();
bool Truncate();
diff --git a/ZR.Service/System/SysOperLogService.cs b/ZR.Service/System/SysOperLogService.cs
index 0671a78..9fc804e 100644
--- a/ZR.Service/System/SysOperLogService.cs
+++ b/ZR.Service/System/SysOperLogService.cs
@@ -70,7 +70,7 @@ namespace ZR.Service.System
/// 结果
public int DeleteOperLogByIds(long[] operIds)
{
- return Context.Deleteable().In(operIds).ExecuteCommand();
+ return Delete(operIds);
}
///