😎优化差异日志
This commit is contained in:
parent
4280ea6968
commit
0ec3eb98aa
@ -15,10 +15,16 @@ namespace Admin.NET.Core;
|
||||
public partial class SysLogDiff : EntityTenant
|
||||
{
|
||||
/// <summary>
|
||||
/// 差异数据
|
||||
/// 操作前记录
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDescription = "差异数据", ColumnDataType = StaticConfig.CodeFirst_BigString)]
|
||||
public string? DiffData { get; set; }
|
||||
[SugarColumn(ColumnDescription = "操作前记录", ColumnDataType = StaticConfig.CodeFirst_BigString)]
|
||||
public string? BeforeData { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 操作后记录
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDescription = "操作后记录", ColumnDataType = StaticConfig.CodeFirst_BigString)]
|
||||
public string? AfterData { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Sql
|
||||
@ -27,7 +33,7 @@ public partial class SysLogDiff : EntityTenant
|
||||
public string? Sql { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 参数 手动传入的参数
|
||||
/// 参数(手动传入的参数)
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDescription = "参数", ColumnDataType = StaticConfig.CodeFirst_BigString)]
|
||||
public string? Parameters { get; set; }
|
||||
|
||||
@ -30,6 +30,7 @@ public class SysLogDiffService : IDynamicApiController, ITransient
|
||||
return await _sysLogDiffRep.AsQueryable()
|
||||
.WhereIF(!string.IsNullOrWhiteSpace(input.StartTime.ToString()), u => u.CreateTime >= input.StartTime)
|
||||
.WhereIF(!string.IsNullOrWhiteSpace(input.EndTime.ToString()), u => u.CreateTime <= input.EndTime)
|
||||
.IgnoreColumns(u => new { u.BeforeData, u.AfterData })
|
||||
.OrderBy(u => u.CreateTime, OrderByType.Desc)
|
||||
.ToPagedListAsync(input.Page, input.PageSize);
|
||||
}
|
||||
@ -44,4 +45,15 @@ public class SysLogDiffService : IDynamicApiController, ITransient
|
||||
{
|
||||
return await _sysLogDiffRep.GetByIdAsync(id);
|
||||
}
|
||||
|
||||
///// <summary>
|
||||
///// 清空差异日志 🔖
|
||||
///// </summary>
|
||||
///// <returns></returns>
|
||||
//[ApiDescriptionSettings(Name = "Clear"), HttpPost]
|
||||
//[DisplayName("清空差异日志")]
|
||||
//public void Clear()
|
||||
//{
|
||||
// _sysLogDiffRep.AsSugarClient().DbMaintenance.TruncateTable<SysLogDiff>();
|
||||
//}
|
||||
}
|
||||
@ -29,6 +29,14 @@ public static class SqlSugarSetup
|
||||
{
|
||||
CustomTypeProvider = new SqlSugarTypeProvider()
|
||||
};
|
||||
//// 配置库表差异日志(审计)
|
||||
//StaticConfig.CompleteInsertableFunc =
|
||||
//StaticConfig.CompleteUpdateableFunc =
|
||||
//StaticConfig.CompleteDeleteableFunc = u =>
|
||||
//{
|
||||
// var method = u.GetType().GetMethod("EnableDiffLogEvent");
|
||||
// method.Invoke(u, [null]);
|
||||
//};
|
||||
|
||||
// 初始化所有库连接
|
||||
var dbOptions = App.GetConfig<DbConnectionOptions>("DbConnection", true);
|
||||
@ -304,41 +312,18 @@ public static class SqlSugarSetup
|
||||
|
||||
dbProvider.Aop.OnDiffLogEvent = async u =>
|
||||
{
|
||||
// 记录差异数据
|
||||
var diffData = new List<dynamic>();
|
||||
for (int i = 0; i < u.AfterData.Count; i++)
|
||||
{
|
||||
var diffColumns = new List<dynamic>();
|
||||
var afterColumns = u.AfterData[i].Columns;
|
||||
var beforeColumns = u.BeforeData[i].Columns;
|
||||
for (int j = 0; j < afterColumns.Count; j++)
|
||||
{
|
||||
if (afterColumns[j].Value.Equals(beforeColumns[j].Value)) continue;
|
||||
diffColumns.Add(new
|
||||
{
|
||||
afterColumns[j].IsPrimaryKey,
|
||||
afterColumns[j].ColumnName,
|
||||
afterColumns[j].ColumnDescription,
|
||||
BeforeValue = beforeColumns[j].Value,
|
||||
AfterValue = afterColumns[j].Value,
|
||||
});
|
||||
}
|
||||
diffData.Add(new
|
||||
{
|
||||
u.AfterData[i].TableName,
|
||||
u.AfterData[i].TableDescription,
|
||||
Columns = diffColumns
|
||||
});
|
||||
}
|
||||
if (u.AfterData.FirstOrDefault()?.TableName == nameof(SysLogDiff)) return;
|
||||
|
||||
var logDiff = new SysLogDiff
|
||||
{
|
||||
// 差异数据(字段描述、列名、值、表名、表描述)
|
||||
DiffData = JSON.Serialize(diffData),
|
||||
// 操作后记录(字段描述、列名、值、表名、表描述)
|
||||
AfterData = JSON.Serialize(u.AfterData),
|
||||
// 操作前记录(字段描述、列名、值、表名、表描述)
|
||||
BeforeData = JSON.Serialize(u.BeforeData),
|
||||
// 传进来的对象(如果对象为空,则使用首个数据的表名作为业务对象)
|
||||
BusinessData = u.BusinessData == null ? u.AfterData.FirstOrDefault()?.TableName : JSON.Serialize(u.BusinessData),
|
||||
// 枚举(insert、update、delete)
|
||||
DiffType = u.DiffType.ToString(),
|
||||
DiffType = u.DiffType.ToString().ToUpper(),
|
||||
Sql = u.Sql,
|
||||
Parameters = JSON.Serialize(u.Parameters.Select(e => new { e.ParameterName, e.Value, TypeName = e.DbType.ToString() })),
|
||||
Elapsed = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds
|
||||
|
||||
@ -93,12 +93,20 @@ export interface SysLogDiff {
|
||||
tenantId?: number | null;
|
||||
|
||||
/**
|
||||
* 差异数据
|
||||
* 操作前记录
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof SysLogDiff
|
||||
*/
|
||||
diffData?: string | null;
|
||||
beforeData?: string | null;
|
||||
|
||||
/**
|
||||
* 操作后记录
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof SysLogDiff
|
||||
*/
|
||||
afterData?: string | null;
|
||||
|
||||
/**
|
||||
* Sql
|
||||
@ -109,7 +117,7 @@ export interface SysLogDiff {
|
||||
sql?: string | null;
|
||||
|
||||
/**
|
||||
* 参数 手动传入的参数
|
||||
* 参数(手动传入的参数)
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof SysLogDiff
|
||||
|
||||
@ -53,49 +53,18 @@
|
||||
<template #empty>
|
||||
<el-empty :image-size="200" />
|
||||
</template>
|
||||
<template #row_content="{ row }">
|
||||
<el-card header="差异数据" style="width: 100%; margin: 5px">
|
||||
<el-table :data="item.columns" v-for="item in row.diffData" :key="item.tableName" :span-method="(data: any) => diffTableSpanMethod(data, item)" border style="width: 100%">
|
||||
<el-table-column label="表名" width="200">
|
||||
<template #default>
|
||||
{{ item.tableName }}
|
||||
<br />
|
||||
{{ item.tableDescription }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="columnName" label="字段描述" width="300" :formatter="(row: any) => `${row.columnName} - ${row.columnDescription}`" />
|
||||
<el-table-column prop="beforeValue" label="修改前" show-overflow-tooltip>
|
||||
<template #default="columnScope">
|
||||
<pre v-html="markDiff(columnScope.row.beforeValue, columnScope.row.afterValue, true)" />
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="afterValue" label="修改后" show-overflow-tooltip>
|
||||
<template #default="columnScope">
|
||||
<pre v-html="markDiff(columnScope.row.beforeValue, columnScope.row.afterValue, false)" />
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<el-table :data="[{ sql: row.sql }]" border style="width: 100%">
|
||||
<el-table-column prop="sql" label="SQL语句">
|
||||
<template #default>
|
||||
<pre class="sql" v-html="formatSql(row.sql)"></pre>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<el-table :data="row.parameters" border style="width: 100%">
|
||||
<el-table-column prop="parameterName" label="参数名" width="200" />
|
||||
<el-table-column prop="typeName" label="类型" width="100" />
|
||||
<el-table-column prop="value" label="值" />
|
||||
</el-table>
|
||||
</el-card>
|
||||
<template #row_diffType="{ row }">
|
||||
<el-tag v-if="row.diffType == 'INSERT'" type="primary"> {{ row.diffType }} </el-tag>
|
||||
<el-tag v-else-if="row.diffType == 'UPDATE'" type="success"> {{ row.diffType }} </el-tag>
|
||||
<el-tag v-else type="danger"> {{ row.diffType }} </el-tag>
|
||||
</template>
|
||||
<!-- <template #row_buttons="{ row }">
|
||||
<template #row_buttons="{ row }">
|
||||
<el-button icon="ele-InfoFilled" text type="primary" @click="handleView({ row })">详情</el-button>
|
||||
</template> -->
|
||||
</template>
|
||||
</vxe-grid>
|
||||
</el-card>
|
||||
|
||||
<!-- <el-dialog v-model="state.visible" draggable overflow destroy-on-close>
|
||||
<el-dialog v-model="state.visible" draggable overflow destroy-on-close>
|
||||
<template #header>
|
||||
<div style="color: #fff">
|
||||
<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Document /> </el-icon>
|
||||
@ -103,12 +72,7 @@
|
||||
</div>
|
||||
</template>
|
||||
<el-tabs v-model="state.activeTab">
|
||||
<el-tab-pane label="日志消息" name="message">
|
||||
<el-scrollbar height="calc(100vh - 250px)">
|
||||
<pre>{{ state.detail.message }}</pre>
|
||||
</el-scrollbar>
|
||||
</el-tab-pane>
|
||||
<el-tab-pane label="SQL" name="sql" :lazy="true">
|
||||
<el-tab-pane label="SQL" name="sql">
|
||||
<el-scrollbar height="calc(100vh - 250px)">
|
||||
<vue-json-pretty :data="state.detail.sql" showLength showIcon showLineNumber showSelectController />
|
||||
</el-scrollbar>
|
||||
@ -129,7 +93,7 @@
|
||||
</el-scrollbar>
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
</el-dialog> -->
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@ -141,9 +105,9 @@ import { VxeGridInstance, VxeGridListeners, VxeGridPropTypes } from 'vxe-table';
|
||||
import { useVxeTable } from '/@/hooks/useVxeTableOptionsHook';
|
||||
import { Local } from '/@/utils/storage';
|
||||
|
||||
// import VueJsonPretty from 'vue-json-pretty';
|
||||
// import 'vue-json-pretty/lib/styles.css';
|
||||
// import { StringToObj } from '/@/utils/json-utils';
|
||||
import VueJsonPretty from 'vue-json-pretty';
|
||||
import 'vue-json-pretty/lib/styles.css';
|
||||
import { StringToObj } from '/@/utils/json-utils';
|
||||
|
||||
import { getAPI } from '/@/utils/axios-utils';
|
||||
import { SysLogDiffApi } from '/@/api-services/api';
|
||||
@ -162,13 +126,12 @@ const state = reactive({
|
||||
},
|
||||
visible: false,
|
||||
detail: {
|
||||
message: '' as string | null | undefined,
|
||||
sql: undefined,
|
||||
parameters: undefined,
|
||||
afterData: undefined,
|
||||
beforeData: undefined,
|
||||
},
|
||||
activeTab: 'message',
|
||||
activeTab: 'sql',
|
||||
});
|
||||
|
||||
// 本地存储参数
|
||||
@ -181,17 +144,15 @@ const options = useVxeTable<SysLogDiff>(
|
||||
columns: [
|
||||
// { type: 'checkbox', width: 40 },
|
||||
{ field: 'seq', type: 'seq', title: '序号', width: 60, fixed: 'left' },
|
||||
{ field: 'expand', type: 'expand', width: 40, slots: { content: 'row_content' } },
|
||||
{ field: 'createTime', title: '操作时间', minWidth: 100, showOverflow: 'tooltip' },
|
||||
{ field: 'diffType', title: '差异操作', minWidth: 150, showOverflow: 'tooltip' },
|
||||
// { field: 'sql', title: 'Sql语句', minWidth: 150, showOverflow: 'tooltip' },
|
||||
// { field: 'parameters', title: '参数', minWidth: 150, showOverflow: 'tooltip' },
|
||||
{ field: 'elapsed', title: '耗时(ms)', minWidth: 150, showOverflow: 'tooltip' },
|
||||
{ field: 'message', title: '日志消息', minWidth: 150, showOverflow: 'tooltip' },
|
||||
{ field: 'createTime', title: '操作时间', width: 150, showOverflow: 'tooltip' },
|
||||
{ field: 'businessData', title: '业务对象', width: 150, showOverflow: 'tooltip' },
|
||||
{ field: 'diffType', title: '操作类型', width: 150, showOverflow: 'tooltip', slots: { default: 'row_diffType' } },
|
||||
{ field: 'sql', title: 'Sql语句', minWidth: 250, showOverflow: 'tooltip' },
|
||||
{ field: 'parameters', title: '参数', minWidth: 250, showOverflow: 'tooltip' },
|
||||
{ field: 'elapsed', title: '耗时(ms)', width: 100, showOverflow: 'tooltip' },
|
||||
// { field: 'beforeData', title: '操作前记录', minWidth: 150, showOverflow: 'tooltip' },
|
||||
// { field: 'afterData', title: '操作后记录', minWidth: 150, showOverflow: 'tooltip' },
|
||||
{ field: 'businessData', title: '业务对象', minWidth: 150, showOverflow: 'tooltip' },
|
||||
// { title: '操作', fixed: 'right', width: 100, showOverflow: true, slots: { default: 'row_buttons' } },
|
||||
{ title: '操作', fixed: 'right', width: 100, showOverflow: true, slots: { default: 'row_buttons' } },
|
||||
],
|
||||
},
|
||||
// vxeGrid配置参数(此处可覆写任何参数),参考vxe-table官方文档
|
||||
@ -246,158 +207,16 @@ const gridEvents: VxeGridListeners<SysLogDiff> = {
|
||||
},
|
||||
};
|
||||
|
||||
// // 查看详情
|
||||
// const handleView = async ({ row }: any) => {
|
||||
// const { data } = await getAPI(SysLogDiffApi).apiSysLogDiffDetailIdGet(row.id);
|
||||
// state.activeTab = 'message';
|
||||
// state.detail.message = data?.result?.diffType;
|
||||
// // 如果请求参数是JSON字符串,则尝试转为JSON对象
|
||||
// state.detail.sql = StringToObj(data?.result?.sql);
|
||||
// state.detail.parameters = StringToObj(data?.result?.parameters);
|
||||
// state.detail.afterData = StringToObj(data?.result?.afterData);
|
||||
// state.detail.beforeData = StringToObj(data?.result?.beforeData);
|
||||
// state.visible = true;
|
||||
// };
|
||||
|
||||
// 合并差异表格表名列
|
||||
const diffTableSpanMethod = ({ columnIndex, rowIndex }: any, itme: any) => {
|
||||
if (columnIndex === 0) {
|
||||
if (rowIndex === 0) {
|
||||
return {
|
||||
rowspan: itme.columns.length,
|
||||
colspan: 1,
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
rowspan: 0,
|
||||
colspan: 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
// 查看详情
|
||||
const handleView = async ({ row }: any) => {
|
||||
const { data } = await getAPI(SysLogDiffApi).apiSysLogDiffDetailIdGet(row.id);
|
||||
// 如果请求参数是JSON字符串,则尝试转为JSON对象
|
||||
state.detail.sql = StringToObj(data?.result?.sql);
|
||||
state.detail.parameters = StringToObj(data?.result?.parameters);
|
||||
state.detail.afterData = StringToObj(data?.result?.afterData);
|
||||
state.detail.beforeData = StringToObj(data?.result?.beforeData);
|
||||
state.visible = true;
|
||||
};
|
||||
|
||||
const formatSql = (sql: string) => {
|
||||
// 移除多余的空格
|
||||
let formatted = sql.replace(/\s+/g, ' ').trim();
|
||||
|
||||
// 替换反引号包裹的字段
|
||||
formatted = formatted.replace(/`([^`]+)`/g, '<span class="sql-backtick">`$1`</span>');
|
||||
|
||||
// 替换@参数
|
||||
formatted = formatted.replace(/(@\w+)/g, '<span class="sql-param">$1</span>');
|
||||
|
||||
// 替换SQL关键字
|
||||
formatted = formatted.replace(
|
||||
/\b(INSERT|DELETE|UPDATE|SELECT|FROM|SET|JOIN|ON|AND|OR|IN|NOT|IS|NULL|WHERE|TRUE|FALSE|LIKE|ORDER BY|GROUP BY|HAVING|LIMIT|AS|WITH|CASE|WHEN|THEN|ELSE|END)\b/g,
|
||||
'<span class="sql-keyword">$1</span>'
|
||||
);
|
||||
|
||||
// 智能换行
|
||||
// 在SET和VALUES后面添加换行
|
||||
formatted = formatted.replace(/(SET|VALUES)(?=\s)/g, '$1\n ');
|
||||
// 在逗号后面添加换行,除非是最后一个逗号
|
||||
formatted = formatted.replace(/,(?![^]*?,\s*$)(?=[^\s])/g, ',\n ');
|
||||
// 在WHERE前添加换行,如果WHERE前面不是逗号
|
||||
formatted = formatted.replace(/([\s\S]+)(WHERE)/g, '$1\n$2');
|
||||
|
||||
// 移除由于换行添加的多余空格
|
||||
formatted = formatted.replace(/\n\s*\n/g, '\n');
|
||||
|
||||
return formatted;
|
||||
};
|
||||
|
||||
function lcs(s1: string, s2: string): number[][] {
|
||||
const m = s1.length;
|
||||
const n = s2.length;
|
||||
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
|
||||
|
||||
for (let i = 1; i <= m; i++) {
|
||||
for (let j = 1; j <= n; j++) {
|
||||
if (s1[i - 1] === s2[j - 1]) {
|
||||
dp[i][j] = dp[i - 1][j - 1] + 1;
|
||||
} else {
|
||||
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp;
|
||||
}
|
||||
|
||||
function markDiff(oldData: any, newData: any, returnOld: boolean): string {
|
||||
if (typeof oldData !== 'string' || typeof newData !== 'string') {
|
||||
return `<span class="diff-${returnOld ? 'delete' : 'add'}">${returnOld ? oldData : newData}</span>`;
|
||||
}
|
||||
|
||||
const dp = lcs(oldData, newData);
|
||||
const m = oldData.length;
|
||||
const n = newData.length;
|
||||
let oldIndex = m,
|
||||
newIndex = n;
|
||||
const diffResult: { type: string; content: string }[] = [];
|
||||
|
||||
while (oldIndex > 0 || newIndex > 0) {
|
||||
if (oldIndex > 0 && newIndex > 0 && oldData[oldIndex - 1] === newData[newIndex - 1]) {
|
||||
diffResult.push({ type: 'unchanged', content: oldData[oldIndex - 1] });
|
||||
oldIndex--;
|
||||
newIndex--;
|
||||
} else if (newIndex > 0 && (oldIndex === 0 || dp[oldIndex][newIndex - 1] >= dp[oldIndex - 1][newIndex])) {
|
||||
diffResult.push({ type: 'add', content: newData[newIndex - 1] });
|
||||
newIndex--;
|
||||
} else {
|
||||
diffResult.push({ type: 'delete', content: oldData[oldIndex - 1] });
|
||||
oldIndex--;
|
||||
}
|
||||
}
|
||||
|
||||
const result = diffResult
|
||||
.reverse()
|
||||
.map((chunk) => {
|
||||
switch (chunk.type) {
|
||||
case 'add':
|
||||
return `<span class="diff-add">${chunk.content}</span>`;
|
||||
case 'delete':
|
||||
return `<span class="diff-delete">${chunk.content}</span>`;
|
||||
default:
|
||||
return chunk.content;
|
||||
}
|
||||
})
|
||||
.join('');
|
||||
|
||||
return result.replace(returnOld ? /<span class="diff-add">(.*?)<\/span>/g : /<span class="diff-delete">(.*?)<\/span>/g, '');
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.el-popper {
|
||||
max-width: 60%;
|
||||
}
|
||||
:deep(pre.sql) {
|
||||
white-space: pre-wrap;
|
||||
.sql-param {
|
||||
color: green;
|
||||
}
|
||||
.sql-keyword {
|
||||
color: blue;
|
||||
}
|
||||
.sql-backtick {
|
||||
color: blueviolet;
|
||||
}
|
||||
span.diff-unchanged {
|
||||
color: inherit;
|
||||
}
|
||||
span.diff-delete {
|
||||
color: red;
|
||||
}
|
||||
span.diff-add {
|
||||
color: green;
|
||||
}
|
||||
}
|
||||
:deep(pre) {
|
||||
span.diff-delete {
|
||||
color: red;
|
||||
}
|
||||
span.diff-add {
|
||||
color: green;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<style lang="scss" scoped></style>
|
||||
|
||||
Loading…
Reference in New Issue
Block a user