替换日志框架

master
zhangxiaofeng 8 months ago
parent dfa985f7e0
commit 57f592ddf5

@ -63,6 +63,9 @@
<Content Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="NLog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ProjectExtensions>

@ -0,0 +1,87 @@
<?xml version="1.0" encoding="utf-8"?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
throwExceptions="false"
internalLogLevel="off" internalLogFile="${basedir}/Logs/nlog-internal.log">
<variable name="MicrosoftLevel" value="${level:lowercase=true:truncate=4:when=level==LogLevel.Info or level==LogLevel.Warn}${when:when=level==LogLevel.Error:inner=fail}${when:when=level==LogLevel.Fatal:inner=crit}${when:when=level==LogLevel.Debug:inner=dbug}${when:when=level==LogLevel.Trace:inner=trce}" />
<variable name="MicrosoftLayout" value="${MicrosoftLevel}: ${logger}[${event-properties:EventId_Id:whenEmpty=0}]${newline} ${message}${onexception:inner=${newline}${exception:format=tostring}}" />
<targets>
<!--archiveAboveSize="10240000"表示单个文件最大10M-->
<!--maxArchiveFiles="30"表示同一文件夹下最多留存30个日志文件超出将删除-->
<target name="console" xsi:type="ColoredConsole" async="true" layout="${MicrosoftLayout}" useDefaultRowHighlightingRules="false" >
<highlight-row condition="contains(message, 'Now listening')" foregroundColor="Yellow"/>
<highlight-word foregroundColor="DarkGreen" regex="^info" />
<highlight-word foregroundColor="Yellow" regex="^warn" />
<highlight-word foregroundColor="Black" backgroundColor="Red" regex="^fail" />
<highlight-word foregroundColor="White" backgroundColor="Red" regex="^crit" />
</target>
<target name="all" xsi:type="File" maxArchiveFiles="30" archiveAboveSize="10240000"
fileName="${basedir}/Logs/${shortdate}/all.log"
layout="${longdate} | ${level} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}" />
<target name="error" xsi:type="File" maxArchiveFiles="30" archiveAboveSize="10240000"
fileName="${basedir}/Logs/${shortdate}/error.log"
layout="${longdate} | ${level} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}" />
<target name="big" xsi:type="AsyncWrapper">
<target xsi:type="File" maxArchiveFiles="30" archiveAboveSize="10240000"
fileName="${basedir}/Logs/${shortdate}/big.log"
layout="${longdate} | ${level} | ${message}" />
</target>
<target name="database" xsi:type="Database"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=EFinance;Persist Security Info=True;User ID=sa;Password=123456;">
<commandText>
insert into syslogs
(Application,Levels,Operatingtime,Operatingaddress,Userid,Logger,Callsite,Requesturl,Referrerurl,Action,Message,Exception)
values
(@application,@levels,@operatingtime,@operatingaddress,@userid,@logger,@callSite,@requesturl,@referrerurl,@action,@message,@exception);
</commandText>
<parameter name="@application" layout="WebApi" />
<parameter name="@levels" layout="${level}" />
<parameter name="@operatingTime" layout="${date}" />
<parameter name="@operatingaddress" layout="${aspnet-Request-IP}" />
<parameter name="@userid" layout="1" />
<parameter name="@logger" layout="${logger}" />
<parameter name="@callSite" layout="${callsite}" />
<parameter name="@requesturl" layout="${aspnet-request-url}" />
<parameter name="@referrerurl" layout="${aspnet-request}" />
<parameter name="@action" layout="${aspnet-mvc-action}" />
<parameter name="@message" layout="${message}" />
<parameter name="@exception" layout="${exception:tostring}" />
</target>
</targets>
<rules>
<!-- 说明:
日志等级MIN TRACE,DEBUG,INFO,WARN,ERROR,FATAL MAX
final设置了final后当此路由被匹配到时不会再匹配此路由下面的路由。未匹配到此路由时才会继续匹配下一个路由
name="*":表示全部匹配 -->
<!-- 捕获全部日志,适用于调试阶段跟踪日志-->
<!--<logger name="*" minlevel="Trace" writeTo="all" />-->
<!-- 捕获日志到控制台 -->
<logger name="*" minlevel="INFO" writeTo="console" />
<!-- 只捕获异常 -->
<logger name="*" minlevel="ERROR" writeTo="error" />
<!-- 不记录微软的日志(异常的日志除外,因为会在上面的两个规则中记录) -->
<logger name="Microsoft.*" minlevel="Trace" final="true" />
<!-- 保存大数据量的日志,采用异步的方式 -->
<logger name="BigDataLogger" writeTo="big" final="true" />
<!-- 普通日志,记录到文件 -->
<logger name="*" minlevel="INFO" writeTo="info" />
<!-- 普通日志,记录到库 -->
<!--<logger name="*" minlevel="INFO" writeTo="database" />-->
</rules>
</nlog>

@ -3,22 +3,19 @@ using Autofac.Extensions.DependencyInjection;
using EntrustSettle;
using EntrustSettle.Common;
using EntrustSettle.Common.Core;
using EntrustSettle.Common.Helper;
using EntrustSettle.Common.LogHelper;
using EntrustSettle.Extensions;
using EntrustSettle.Extensions.Middlewares;
using EntrustSettle.Extensions.ServiceExtensions;
using EntrustSettle.Filter;
using EntrustSettle.Hubs;
using EntrustSettle.Serilog.Utility;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.IdentityModel.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Serilog;
using NLog.Web;
using System.IdentityModel.Tokens.Jwt;
using System.Reflection;
using System.Text;
@ -48,11 +45,18 @@ internal class Program
{
config.AddJsonFile("appsettings.production.json", optional: true, reloadOnChange: true);
}
});
}).ConfigureLogging(logging =>
{
logging.ClearProviders();
//logging.AddConsole(); //表示程序启动后在弹出的黑框里记录日志
logging.AddDebug(); //表示程序启动后在VS中输出中显示日志
})
.UseNLog();
builder.ConfigureApplication();
// 2、配置服务
builder.Services.AddSingleton(new AppSettings(builder.Configuration));
builder.Services.AddSingleton(new LogLock(AppContext.BaseDirectory));
builder.Services.AddAllOptionRegister();
// 设置雪花id的workerId确保每个实例workerId都应不同
@ -70,8 +74,6 @@ internal class Program
builder.Services.AddDbSetup();
builder.Services.AddInitializationHostServiceSetup();
builder.Host.AddSerilogSetup();
builder.Services.AddMapsterSetup();
builder.Services.AddCorsSetup();
builder.Services.AddSwaggerSetup();
@ -199,13 +201,6 @@ internal class Program
// 返回错误码
app.UseStatusCodePages();
// Serilog请求日志
app.UseSerilogRequestLogging(options =>
{
options.MessageTemplate = SerilogRequestUtility.HttpMessageTemplate;
options.GetLevel = SerilogRequestUtility.GetRequestLevel;
options.EnrichDiagnosticContext = SerilogRequestUtility.EnrichFromRequest;
});
app.UseRouting();
@ -224,7 +219,7 @@ internal class Program
app.MapControllers();
app.MapHub<ChatHub>("/api2/chatHub");
//app.MapHub<ChatHub>("/api2/chatHub");
// 4、运行
app.Run();

@ -52,7 +52,7 @@
"Enabled": true
},
"LogToDB": {
"Enabled": true
"Enabled": false
}
},
"IPLog": {
@ -61,7 +61,7 @@
"Enabled": true
},
"LogToDB": {
"Enabled": true
"Enabled": false
}
},
"RecordAccessLogs": {
@ -70,7 +70,7 @@
"Enabled": true
},
"LogToDB": {
"Enabled": true
"Enabled": false
},
"IgnoreApis": "/api/test/demo1,/api/test/demo2"
},
@ -102,38 +102,38 @@
// Sql
"LogToDb": false,
//
"CachingAOP": {
"Enabled": true
},
//
"LogAOP": {
"Enabled": false,
// AOP
"ServiceAOPLog": {
"Enabled": true,
"LogToFile": {
"Enabled": true
},
"LogToDB": {
"Enabled": true
"Enabled": false
}
},
//
"TranAOP": {
"Enabled": true
},
// Sql
"SqlAOP": {
"SqlAOPLog": {
"Enabled": true,
"LogToFile": {
"Enabled": true
},
"LogToDB": {
"Enabled": true
},
// Sql
"LogToConsole": {
"Enabled": false
},
"LogToDB": {
"Enabled": false
}
},
//
"CachingAOP": {
"Enabled": true
},
//
"TranAOP": {
"Enabled": true
},
"SeedDBEnabled": false, //
"RoutePrefix": "", //
"UseLoadTest": false
@ -230,22 +230,11 @@
]
},
"Serilog": {
"MinimumLevel": {
/* VerboseDebugInformationWarningErrorFatal */
"Default": "Debug",
"Override": {
"Microsoft": "Information",
"Microsoft.AspNetCore": "Warning",
"System": "Warning",
"System.Net.Http.HttpClient": "Warning",
"Quartz": "Information"
}
}
},
// Quartz
"QuartzNetJob": {
"Enabled": true
},
//
"TimedJob": {
"Enabled": false
},

@ -21,18 +21,11 @@
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.1.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="8.0.0" />
<PackageReference Include="PinYinConverterCore" Version="1.0.2" />
<PackageReference Include="RSAExtensions" Version="1.1.1" />
<PackageReference Include="Serilog.Expressions" Version="4.0.0" />
<PackageReference Include="Serilog.Sinks.Async" Version="1.5.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.Elasticsearch" Version="9.0.3" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="NLog.Web.AspNetCore" Version="5.3.8" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.2.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
</ItemGroup>
<ItemGroup>

@ -1,5 +1,5 @@
using Microsoft.Extensions.DependencyModel;
using Serilog;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
@ -29,7 +29,7 @@ public static class RuntimeExtension
}
catch (Exception e)
{
Log.Debug(e, "GetAllAssemblies Exception:{ex}", e.Message);
LogManager.GetCurrentClassLogger().Error(e, "GetAllAssemblies Exception:{ex}", e.Message);
}
}

@ -1,42 +0,0 @@
using Serilog.Context;
using SqlSugar;
using System;
using System.Collections.Generic;
namespace EntrustSettle.Common.LogHelper;
public class LogContextExtension : IDisposable
{
private readonly Stack<IDisposable> _disposableStack = new Stack<IDisposable>();
public static LogContextExtension Create => new();
public void AddStock(IDisposable disposable)
{
_disposableStack.Push(disposable);
}
public IDisposable SqlAopPushProperty(ISqlSugarClient db)
{
AddStock(LogContext.PushProperty(LogContextStatic.LogSource, LogContextStatic.AopSql));
AddStock(LogContext.PushProperty(LogContextStatic.SqlOutToConsole,
AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToConsole", "Enabled" }).ObjToBool()));
AddStock(LogContext.PushProperty(LogContextStatic.SqlOutToFile,
AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToFile", "Enabled" }).ObjToBool()));
AddStock(LogContext.PushProperty(LogContextStatic.OutToDb,
AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToDB", "Enabled" }).ObjToBool()));
AddStock(LogContext.PushProperty(LogContextStatic.SugarActionType, db.SugarActionType));
return this;
}
public void Dispose()
{
while (_disposableStack.Count > 0)
{
_disposableStack.Pop().Dispose();
}
}
}

@ -1,42 +0,0 @@
using System.IO;
namespace EntrustSettle.Common.LogHelper;
public class LogContextStatic
{
static LogContextStatic()
{
if (!Directory.Exists(BaseLogs))
{
Directory.CreateDirectory(BaseLogs);
}
}
public const string BaseLogs = "Logs";
public const string BasePathLogs = @"Logs";
public const string LogSource = "LogSource";
public const string AopSql = "AOPSql";
public const string SqlOutToConsole = "OutToConsole";
public const string SqlOutToFile = "SqlOutToFile";
public const string OutToDb = "OutToDb";
public const string SugarActionType = "SugarActionType";
public static readonly string FileMessageTemplate = "{NewLine}Date{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel{Level}{NewLine}Message{Message}{NewLine}{Exception}" + new string('-', 100);
public static string Combine(string path1)
{
return Path.Combine(BaseLogs, path1);
}
public static string Combine(string path1, string path2)
{
return Path.Combine(BaseLogs, path1, path2);
}
public static string Combine(string path1, string path2, string path3)
{
return Path.Combine(BaseLogs, path1, path2, path3);
}
}

@ -1,13 +0,0 @@
using System;
namespace EntrustSettle.Common.LogHelper
{
public class LogInfo
{
public DateTime Datetime { get; set; }
public string Content { get; set; }
public string IP { get; set; }
public string LogColor { get; set; }
public int Import { get; set; } = 0;
}
}

@ -1,6 +1,6 @@
using EntrustSettle.Common.Helper;
using Newtonsoft.Json;
using Serilog;
using NLog;
using System;
using System.IO;
using System.Linq;
@ -10,6 +10,7 @@ namespace EntrustSettle.Common.LogHelper
{
public class LogLock
{
static Logger logger = null;
static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
static int WritedCount = 0;
static int FailedCount = 0;
@ -23,15 +24,13 @@ namespace EntrustSettle.Common.LogHelper
public static void OutLogAOP(string prefix, string traceId, string[] dataParas, bool IsHeader = true)
{
string AppSetingNodeName = "AppSettings";
string AppSetingName = "LogAOP";
string AppSetingName = "";
switch (prefix)
{
// AOP中使用
case "AOPLog":
AppSetingName = "LogAOP";
break;
case "AOPLogEx":
AppSetingName = "LogAOP";
// 自定义的AOP中使用
case "ServiceAOPLog":
case "ServiceAOPLogEx":
AppSetingName = "ServiceAOPLog";
break;
// 中间件中使用
@ -48,9 +47,9 @@ namespace EntrustSettle.Common.LogHelper
AppSetingName = "RequestResponseLog";
break;
// 暂时用不到
case "SqlLog":
AppSetingName = "SqlAOP";
// SqlSugarAOP中使用
case "SqlAOPLog":
AppSetingName = "SqlAOPLog";
break;
default:
break;
@ -58,15 +57,14 @@ namespace EntrustSettle.Common.LogHelper
if (AppSettings.app(new string[] { AppSetingNodeName, AppSetingName, "Enabled" }).ObjToBool())
{
if (AppSettings.app(new string[] { AppSetingNodeName, AppSetingName, "LogToDB", "Enabled" }).ObjToBool())
{
OutSql2LogToDB(prefix, traceId, dataParas, IsHeader);
}
if (AppSettings.app(new string[] { AppSetingNodeName, AppSetingName, "LogToFile", "Enabled" }).ObjToBool())
{
OutSql2LogToFile(prefix, traceId, dataParas, IsHeader);
}
if (AppSettings.app(new string[] { AppSetingNodeName, AppSetingName, "LogToDB", "Enabled" }).ObjToBool())
{
OutSql2LogToDB(prefix, traceId, dataParas, IsHeader);
}
}
}
@ -80,7 +78,7 @@ namespace EntrustSettle.Common.LogHelper
// 因进入与退出写入模式应在同一个try finally语句块内所以在请求进入写入模式之前不能触发异常否则释放次数大于请求次数将会触发异常
LogWriteLock.EnterWriteLock();
var folderPath = Path.Combine(_contentRoot, "Logs", DateTime.Now.ToString("yyyyMMdd"));
var folderPath = Path.Combine(_contentRoot, "Logs", DateTime.Now.ToString("yyyy-MM-dd"));
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
@ -90,7 +88,7 @@ namespace EntrustSettle.Common.LogHelper
var logFilePath = FileHelper.GetAvailableFileWithPrefixOrderSize(folderPath, prefix, 5);
switch (prefix)
{
case "AOPLog":
case "ServiceAOPLog":
AOPLogInfo apiLogAopInfo = JsonConvert.DeserializeObject<AOPLogInfo>(dataParas[1]);
//记录被拦截方法信息的日志信息
var dataIntercept = "" +
@ -104,7 +102,7 @@ namespace EntrustSettle.Common.LogHelper
$"【执行完成结果】:{apiLogAopInfo.ResponseJsonData}\r\n";
dataParas = new string[] { dataIntercept };
break;
case "AOPLogEx":
case "ServiceAOPLogEx":
AOPLogExInfo apiLogAopExInfo = JsonConvert.DeserializeObject<AOPLogExInfo>(dataParas[1]);
var dataInterceptEx = "" +
$"【操作时间】:{apiLogAopExInfo.ApiLogAopInfo.RequestTime}\r\n" +
@ -121,14 +119,11 @@ namespace EntrustSettle.Common.LogHelper
break;
}
var now = DateTime.Now;
string logContent = String.Join("\r\n", dataParas);
string logContent = null;
if (IsHeader)
{
logContent = (
"--------------------------------\r\n" +
DateTime.Now + "|\r\n" +
String.Join("\r\n", dataParas) + "\r\n"
$"--------------------------------\r\n{DateTime.Now:yyyy-MM-dd HH:mm:ss:fff} TraceId:{traceId}\r\n{String.Join("\r\n", dataParas)}\r\n"
);
}
else
@ -170,6 +165,11 @@ namespace EntrustSettle.Common.LogHelper
public static void OutSql2LogToDB(string prefix, string traceId, string[] dataParas, bool IsHeader = true)
{
if (logger == null)
{
logger = LogManager.GetCurrentClassLogger();
}
dataParas = dataParas.Skip(1).ToArray();
string logContent = String.Join("", dataParas);
@ -181,26 +181,23 @@ namespace EntrustSettle.Common.LogHelper
switch (prefix)
{
//DEBUG | INFO | WARN | ERROR | FATAL
case "AOPLog":
Log.Information(logContent);
case "ServiceAOPLog":
logger.Info(logContent);
break;
case "AOPLogEx":
Log.Error(logContent);
case "ServiceAOPLogEx":
logger.Error(logContent);
break;
case "RequestIpInfoLog":
//TODO 是否需要Debug输出
Log.Information(logContent);
logger.Info(logContent);
break;
case "RecordAccessLogs":
//TODO 是否需要Debug输出
Log.Information(logContent);
logger.Info(logContent);
break;
case "RequestResponseLog":
//TODO 是否需要Debug输出
Log.Information(logContent);
logger.Info(logContent);
break;
case "SqlLog":
Log.Information(logContent);
case "SqlAOPLog":
logger.Info(logContent);
break;
default:
break;

@ -99,33 +99,33 @@ namespace EntrustSettle.AOP
});
}
#endregion
#endregion
// 如果方案一不行,试试这个方案
//#region 方案二
// 如果方案一不行,试试这个方案
//#region 方案二
//var type = invocation.Method.ReturnType;
//var resultProperty = type.GetProperty("Result");
//DateTime endTime = DateTime.Now;
//string ResponseTime = (endTime - startTime).Milliseconds.ToString();
//apiLogAopInfo.ResponseTime = endTime.ToString("yyyy-MM-dd hh:mm:ss fff");
//apiLogAopInfo.ResponseIntervalTime = ResponseTime + "ms";
//apiLogAopInfo.ResponseJsonData = JsonConvert.SerializeObject(resultProperty.GetValue(invocation.ReturnValue));
//var type = invocation.Method.ReturnType;
//var resultProperty = type.GetProperty("Result");
//DateTime endTime = DateTime.Now;
//string ResponseTime = (endTime - startTime).Milliseconds.ToString();
//apiLogAopInfo.ResponseTime = endTime.ToString("yyyy-MM-dd hh:mm:ss fff");
//apiLogAopInfo.ResponseIntervalTime = ResponseTime + "ms";
//apiLogAopInfo.ResponseJsonData = JsonConvert.SerializeObject(resultProperty.GetValue(invocation.ReturnValue));
////dataIntercept += ($"【响应时间】:{ResponseTime}ms\r\n");
////dataIntercept += ($"【执行完成时间】:{endTime.ToString("yyyy-MM-dd hh:mm:ss fff")}\r\n");
////dataIntercept += ($"【执行完成结果】:{JsonConvert.SerializeObject(resultProperty.GetValue(invocation.ReturnValue))}\r\n");
////dataIntercept += ($"【响应时间】:{ResponseTime}ms\r\n");
////dataIntercept += ($"【执行完成时间】:{endTime.ToString("yyyy-MM-dd hh:mm:ss fff")}\r\n");
////dataIntercept += ($"【执行完成结果】:{JsonConvert.SerializeObject(resultProperty.GetValue(invocation.ReturnValue))}\r\n");
//Parallel.For(0, 1, e =>
//{
// //LogLock.OutLogAOP("AOPLog", new string[] { dataIntercept });
// LogLock.OutLogAOP("AOPLog", new string[] { apiLogAopInfo.GetType().ToString() + " - ResponseJsonDataType:" + type, JsonConvert.SerializeObject(apiLogAopInfo) });
//});
//Parallel.For(0, 1, e =>
//{
// //LogLock.OutLogAOP("ServiceAOPLog", new string[] { dataIntercept });
// LogLock.OutLogAOP("ServiceAOPLog", new string[] { apiLogAopInfo.GetType().ToString() + " - ResponseJsonDataType:" + type, JsonConvert.SerializeObject(apiLogAopInfo) });
//});
//#endregion
}
else
//#endregion
}
else
{
// 同步1
string jsonResult;
@ -149,8 +149,7 @@ namespace EntrustSettle.AOP
//dataIntercept += ($"【执行完成结果】:{jsonResult}");
Parallel.For(0, 1, e =>
{
//LogLock.OutLogAOP("AOPLog", new string[] { dataIntercept });
LogLock.OutLogAOP("AOPLog", _accessor.HttpContext?.TraceIdentifier,
LogLock.OutLogAOP("ServiceAOPLog", _accessor.HttpContext?.TraceIdentifier,
new string[] {apiLogAopInfo.GetType().ToString(), JsonConvert.SerializeObject(apiLogAopInfo)});
});
}
@ -193,8 +192,7 @@ namespace EntrustSettle.AOP
{
Parallel.For(0, 1, e =>
{
//LogLock.OutSql2Log("AOPLog", new string[] { JsonConvert.SerializeObject(apiLogAopInfo) });
LogLock.OutLogAOP("AOPLog", _accessor.HttpContext?.TraceIdentifier,
LogLock.OutLogAOP("ServiceAOPLog", _accessor.HttpContext?.TraceIdentifier,
new string[] {apiLogAopInfo.GetType().ToString(), JsonConvert.SerializeObject(apiLogAopInfo)});
});
});
@ -216,8 +214,7 @@ namespace EntrustSettle.AOP
// 异常日志里有详细的堆栈信息
Parallel.For(0, 1, e =>
{
//LogLock.OutLogAOP("AOPLogEx", new string[] { dataIntercept });
LogLock.OutLogAOP("AOPLogEx", _accessor.HttpContext?.TraceIdentifier,
LogLock.OutLogAOP("ServiceAOPLogEx", _accessor.HttpContext?.TraceIdentifier,
new string[] {apiLogAopExInfo.GetType().ToString(), JsonConvert.SerializeObject(apiLogAopExInfo)});
});
}

@ -1,35 +1,37 @@
using SqlSugar;
using System;
using Serilog;
using EntrustSettle.Common.LogHelper;
using EntrustSettle.Model;
using Yitter.IdGenerator;
using System.Threading.Tasks;
namespace EntrustSettle.Common.DB.Aop;
//namespace EntrustSettle.Common.DB.Aop;
public static class SqlSugarAop
{
public static void OnLogExecuting(ISqlSugarClient sqlSugarScopeProvider, string user, string table, string operate, string sql, SugarParameter[] p, ConnectionConfig config)
public static void OnLogExecuting(string sql, SugarParameter[] p, string user)
{
try
if (AppSettings.app(new string[] { "AppSettings", "SqlAOPLog", "Enabled" }).ObjToBool())
{
if (!AppSettings.app(new string[] { "AppSettings", "SqlAOP", "Enabled" }).ObjToBool()) return;
if (AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToConsole", "Enabled" }).ObjToBool() ||
AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToFile", "Enabled" }).ObjToBool() ||
AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToDB", "Enabled" }).ObjToBool())
if (AppSettings.app(new string[] { "AppSettings", "SqlAOPLog", "LogToFile", "Enabled" }).ObjToBool())
{
using (LogContextExtension.Create.SqlAopPushProperty(sqlSugarScopeProvider))
Parallel.For(0, 1, e =>
{
Log.Information("------------------ \r\n User:[{User}] Table:[{Table}] Operate:[{Operate}] ConnId:[{ConnId}]【SQL语句】: \r\n {Sql}",
user, table, operate, config.ConfigId, UtilMethods.GetNativeSql(sql, p));
}
// 完整sql语句
LogLock.OutLogAOP("SqlAOPLog", "",
[
$"【操作人】:{user}",
"【SQL语句】",
GetWholeSql(p, sql),
]);
// 参数化sql语句
//LogLock.OutLogAOP("SqlAOPLog", "", new string[] { GetParas(p), "【SQL语句】" + sql });
});
}
if (AppSettings.app(new string[] { "AppSettings", "SqlAOPLog", "LogToConsole", "Enabled" }).ObjToBool())
{
ConsoleHelper.WriteColorLine(string.Join("\r\n", new string[] { "--------", $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} " + GetWholeSql(p, sql) }), ConsoleColor.DarkCyan);
}
}
catch (Exception e)
{
Log.Error("Error occured OnLogExcuting:" + e);
}
}
@ -91,7 +93,15 @@ public static class SqlSugarAop
}
}
}
private static string GetWholeSql(SugarParameter[] paramArr, string sql)
{
foreach (var param in paramArr)
{
sql.Replace(param.ParameterName, param.Value.ObjToString());
}
return sql;
}
private static string GetParas(SugarParameter[] pars)
{
string key = "【SQL参数】";

@ -19,8 +19,6 @@
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" />
<PackageReference Include="NetDevPack.Security.JwtExtensions" Version="7.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Seq" Version="6.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Filters" Version="8.0.0" />
@ -29,7 +27,6 @@
<ItemGroup>
<ProjectReference Include="..\EntrustSettle.EventBus\EntrustSettle.EventBus.csproj" />
<ProjectReference Include="..\EntrustSettle.Serilog\EntrustSettle.Serilog.csproj" />
<ProjectReference Include="..\EntrustSettle.Services\EntrustSettle.Services.csproj" />
<ProjectReference Include="..\EntrustSettle.Tasks\EntrustSettle.Tasks.csproj" />
</ItemGroup>

@ -1,8 +1,8 @@
using AspNetCoreRateLimit;
using EntrustSettle.Common;
using Microsoft.AspNetCore.Builder;
using NLog;
using System;
using Serilog;
namespace EntrustSettle.Extensions.Middlewares
{
@ -24,7 +24,7 @@ namespace EntrustSettle.Extensions.Middlewares
}
catch (Exception e)
{
Log.Error($"Error occured limiting ip rate.\n{e.Message}");
LogManager.GetCurrentClassLogger().Error(e, "Error occured limiting ip rate. {ex}", e.Message);
throw;
}
}

@ -62,20 +62,6 @@ namespace EntrustSettle.Extensions.Middlewares
LogLock.OutLogAOP("RequestIpInfoLog", context.TraceIdentifier,
new string[] {requestInfo.GetType().ToString(), requestInfo}, false);
});
//try
//{
// var testLogMatchRequestInfo = JsonConvert.DeserializeObject<RequestInfo>(requestInfo);
// if (testLogMatchRequestInfo != null)
// {
// var logFileName = FileHelper.GetAvailableFileNameWithPrefixOrderSize(_environment.ContentRootPath, "RequestIpInfoLog");
// SerilogServer.WriteLog(logFileName, new string[] { requestInfo + "," }, false, "", true);
// }
//}
//catch (Exception e)
//{
// log.Error(requestInfo + "\r\n" + e.GetBaseException().ToString());
//}
request.Body.Position = 0;
}

@ -104,8 +104,6 @@ namespace EntrustSettle.Extensions.Middlewares
LogLock.OutLogAOP("RecordAccessLogs", context.TraceIdentifier,
new string[] {userAccessModel.GetType().ToString(), requestInfo}, false);
});
//var logFileName = FileHelper.GetAvailableFileNameWithPrefixOrderSize(_environment.ContentRootPath, "RecordAccessLogs");
//SerilogServer.WriteLog(logFileName, new string[] { requestInfo + "," }, false);
return Task.CompletedTask;
});
}

@ -9,6 +9,8 @@ using EntrustSettle.Common.LogHelper;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.Ocsp;
using Polly;
namespace EntrustSettle.Extensions.Middlewares
{
@ -66,27 +68,22 @@ namespace EntrustSettle.Extensions.Middlewares
{
var request = context.Request;
var sr = new StreamReader(request.Body);
RequestLogInfo requestResponse = new RequestLogInfo()
var bodyData = await sr.ReadToEndAsync();
var logContent = new string[]
{
Path = request.Path,
QueryString = request.QueryString.ToString(),
BodyData = await sr.ReadToEndAsync()
$"请求 - [Path]:{request.Path}",
$"[QueryString]:{request.QueryString}",
$"[Body]:{bodyData}"
};
var content = JsonConvert.SerializeObject(requestResponse);
//var content = $" QueryData:{request.Path + request.QueryString}\r\n BodyData:{await sr.ReadToEndAsync()}";
if (!string.IsNullOrEmpty(content))
Parallel.For(0, 1, e =>
{
Parallel.For(0, 1, e =>
{
//LogLock.OutSql2Log("RequestResponseLog", new string[] { "Request Data:", content });
LogLock.OutLogAOP("RequestResponseLog", context.TraceIdentifier,
new string[] { "Request Data - RequestJsonDataType:" + requestResponse.GetType().ToString(), content });
});
//SerilogServer.WriteLog("RequestResponseLog", new string[] { "Request Data:", content });
LogLock.OutLogAOP("RequestResponseLog",
context.TraceIdentifier,
logContent);
});
request.Body.Position = 0;
}
request.Body.Position = 0;
}
private void ResponseDataLog(HttpResponse response)
@ -94,18 +91,23 @@ namespace EntrustSettle.Extensions.Middlewares
var responseBody = response.GetResponseBody();
// 去除 Html
var reg = "<[^>]+>";
//var reg = "<[^>]+>";
if (!string.IsNullOrEmpty(responseBody))
{
var isHtml = Regex.IsMatch(responseBody, reg);
//var isHtml = Regex.IsMatch(responseBody, reg);
var logContent = new string[]
{
$"响应 - [StatusCode]:{response.StatusCode}",
$"[Body]:{responseBody}",
};
Parallel.For(0, 1, e =>
{
//LogLock.OutSql2Log("RequestResponseLog", new string[] { "Response Data:", ResponseBody });
LogLock.OutLogAOP("RequestResponseLog", response.HttpContext.TraceIdentifier,
new string[] { "Response Data - ResponseJsonDataType:" + responseBody.GetType().ToString(), responseBody });
LogLock.OutLogAOP("RequestResponseLog",
response.HttpContext.TraceIdentifier,
logContent);
});
//SerilogServer.WriteLog("RequestResponseLog", new string[] { "Response Data:", responseBody });
}
}
@ -126,7 +128,6 @@ namespace EntrustSettle.Extensions.Middlewares
LogLock.OutLogAOP("RequestResponseLog", response.HttpContext.TraceIdentifier,
new string[] { "Response Data - ResponseJsonDataType:" + responseBody.GetType().ToString(), responseBody });
});
//SerilogServer.WriteLog("RequestResponseLog", new string[] { "Response Data:", responseBody });
}
}
}

@ -1,9 +1,9 @@
using EntrustSettle.Common;
using Microsoft.AspNetCore.Builder;
using NLog;
using Swashbuckle.AspNetCore.SwaggerUI;
using System;
using System.IO;
using Serilog;
namespace EntrustSettle.Extensions.Middlewares
{
@ -28,7 +28,7 @@ namespace EntrustSettle.Extensions.Middlewares
if (streamHtml.Invoke() == null)
{
var msg = "swagger_index.html的属性必须设置为嵌入的资源";
Log.Error(msg);
LogManager.GetCurrentClassLogger().Error(msg);
throw new Exception(msg);
}

@ -62,10 +62,11 @@ namespace EntrustSettle.Extensions
List<string[]> aopInfos = new()
{
new string[] { "缓存AOP", AppSettings.app("AppSettings", "CachingAOP", "Enabled") },
new string[] { "服务日志AOP", AppSettings.app("AppSettings", "LogAOP", "Enabled") },
new string[] { "事务AOP", AppSettings.app("AppSettings", "TranAOP", "Enabled") },
new string[] { "Sql执行AOP", AppSettings.app("AppSettings", "SqlAOP", "Enabled") },
new string[] { "Sql执行AOP控制台输出", AppSettings.app("AppSettings", "SqlAOP", "LogToConsole", "Enabled") },
new string[] { "服务层AOP日志", AppSettings.app("AppSettings", "ServiceAOPLog", "Enabled") },
new string[] { "Sql执行AOP日志", AppSettings.app("AppSettings", "SqlAOPLog", "Enabled") },
new string[] { "Sql执行AOP日志记录到文件", AppSettings.app("AppSettings", "SqlAOPLog", "LogToFile", "Enabled") },
new string[] { "Sql执行AOP日志记录控制台", AppSettings.app("AppSettings", "SqlAOPLog", "LogToConsole", "Enabled") },
};
new ConsoleTable

@ -1,6 +1,5 @@
using EntrustSettle.Common;
using Microsoft.AspNetCore.Builder;
using Serilog;
namespace EntrustSettle.Extensions.ServiceExtensions;
@ -17,8 +16,8 @@ public static class ApplicationSetup
{
App.IsRun = false;
//清除日志
Log.CloseAndFlush();
NLog.LogManager.Flush();
NLog.LogManager.Shutdown();
});
}
}

@ -7,7 +7,7 @@ using EntrustSettle.IServices.Base;
using EntrustSettle.Repository.Base;
using EntrustSettle.Repository.UnitOfWorks;
using EntrustSettle.Services.Base;
using Serilog;
using NLog;
using System;
using System.Collections.Generic;
using System.IO;
@ -31,7 +31,7 @@ namespace EntrustSettle.Extensions
if (!(File.Exists(servicesDllFile) && File.Exists(repositoryDllFile)))
{
var msg = "Repository.dll和service.dll 丢失因为项目解耦了所以需要先F6编译再F5运行请检查 bin 文件夹,并拷贝。";
Log.Error(msg);
LogManager.GetCurrentClassLogger().Error(msg);
throw new Exception(msg);
}
@ -50,7 +50,7 @@ namespace EntrustSettle.Extensions
cacheType.Add(typeof(BlogTranAOP));
}
if (AppSettings.app(new string[] { "AppSettings", "LogAOP", "Enabled" }).ObjToBool())
if (AppSettings.app(new string[] { "AppSettings", "ServiceAOPLog", "Enabled" }).ObjToBool())
{
builder.RegisterType<BlogLogAOP>();
cacheType.Add(typeof(BlogLogAOP));

@ -1,8 +1,12 @@
using EntrustSettle.Common;
using EntrustSettle.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using Quartz.Spi;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace EntrustSettle.Extensions
{
@ -24,22 +28,22 @@ namespace EntrustSettle.Extensions
if (AppSettings.app("QuartzNetJob", "Enabled").ObjToBool())
{
services.AddSingleton<IJobFactory, JobFactory>();
services.AddTransient<JobHydSubmitQuartz>(); //Job使用瞬时依赖注入
//services.AddTransient<JobHydSubmitQuartz>(); //Job使用瞬时依赖注入
services.AddSingleton<ISchedulerCenter, SchedulerCenterServer>();
}
//批量注入Quartz版的定时任务
//var baseType = typeof(IJob);
//var pith = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
//var assemblie = Assembly.LoadFrom(Path.Combine(pith, "EntrustSettle.Tasks.dll"));
//var implementTypes = assemblie.GetTypes()
// .Where(t => baseType.IsAssignableFrom(t) && t.IsClass)
// .ToArray();
var baseType = typeof(IJob);
var pith = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
var assemblie = Assembly.LoadFrom(Path.Combine(pith, "EntrustSettle.Tasks.dll"));
var implementTypes = assemblie.GetTypes()
.Where(t => baseType.IsAssignableFrom(t) && t.IsClass)
.ToArray();
//foreach (var implementType in implementTypes)
//{
// services.AddTransient(implementType);
//}
foreach (var implementType in implementTypes)
{
services.AddTransient(implementType);
}
}
}
}

@ -1,38 +0,0 @@
using EntrustSettle.Common;
using EntrustSettle.Common.LogHelper;
using EntrustSettle.Serilog.Configuration;
using EntrustSettle.Serilog.Extensions;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Debugging;
using System;
using System.IO;
namespace EntrustSettle.Extensions.ServiceExtensions;
public static class SerilogSetup
{
public static IHostBuilder AddSerilogSetup(this IHostBuilder host)
{
if (host == null) throw new ArgumentNullException(nameof(host));
var loggerConfiguration = new LoggerConfiguration()
.ReadFrom.Configuration(AppSettings.Configuration)
.Enrich.FromLogContext()
//输出到控制台
.WriteToConsole()
//将日志保存到文件中
.WriteToFile()
//配置日志库
.WriteToLogBatching();
Log.Logger = loggerConfiguration.CreateLogger();
//Serilog 内部日志
var file = File.CreateText(LogContextStatic.Combine($"SerilogDebug{DateTime.Now:yyyyMMdd}.txt"));
SelfLog.Enable(TextWriter.Synchronized(file));
host.UseSerilog();
return host;
}
}

@ -114,9 +114,7 @@ namespace EntrustSettle.Extensions
// 打印SQL语句
dbProvider.Aop.OnLogExecuting = (s, parameters) =>
{
SqlSugarAop.OnLogExecuting(dbProvider, App.User?.Name.ObjToString(), ExtractTableName(s),
Enum.GetName(typeof(SugarActionType), dbProvider.SugarActionType), s, parameters,
config);
SqlSugarAop.OnLogExecuting(sql: s, p: parameters, user: App.User?.Name?.ObjToString());
};
// 数据初始化

@ -3,7 +3,7 @@ using EntrustSettle.Common.Extensions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Serilog;
using NLog;
using Swashbuckle.AspNetCore.Filters;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
@ -86,7 +86,7 @@ namespace EntrustSettle.Extensions
}
catch (Exception ex)
{
Log.Error("EntrustSettle.Api.xml和EntrustSettle.Model.xml 丢失,请检查并拷贝。\n" + ex.Message);
LogManager.GetCurrentClassLogger().Error(ex, "EntrustSettle.Api.xml和EntrustSettle.Model.xml 丢失,请检查并拷贝。" );
}
// 开启加权小锁

@ -4,7 +4,7 @@ using EntrustSettle.Services.Base;
namespace EntrustSettle.Services
{
public class FilesService : BaseServices<Annex>, IAnnexService
public class AnnexService : BaseServices<Annex>, IAnnexService
{
}
}

@ -4,7 +4,7 @@ using EntrustSettle.Services.Base;
namespace EntrustSettle.Services
{
public class OrderFileService : BaseServices<OrderAnnex>, IOrderAnnexService
public class OrderAnnexService : BaseServices<OrderAnnex>, IOrderAnnexService
{
}
}

@ -21,8 +21,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntrustSettle.Extensions",
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntrustSettle.EventBus", "EntrustSettle.EventBus\EntrustSettle.EventBus.csproj", "{17C9E9DC-E926-4C90-9025-3DAC55D7EDA3}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntrustSettle.Serilog", "EntrustSettle.Serilog\EntrustSettle.Serilog.csproj", "{7F9057F0-ED8D-4694-B590-7D75C012DF00}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{383975B9-C8E6-407E-A6F9-E36E2E45331F}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
@ -72,10 +70,6 @@ Global
{17C9E9DC-E926-4C90-9025-3DAC55D7EDA3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{17C9E9DC-E926-4C90-9025-3DAC55D7EDA3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{17C9E9DC-E926-4C90-9025-3DAC55D7EDA3}.Release|Any CPU.Build.0 = Release|Any CPU
{7F9057F0-ED8D-4694-B590-7D75C012DF00}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7F9057F0-ED8D-4694-B590-7D75C012DF00}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7F9057F0-ED8D-4694-B590-7D75C012DF00}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7F9057F0-ED8D-4694-B590-7D75C012DF00}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

Loading…
Cancel
Save