2
2
using System . Net ;
3
3
using GZCTF . Extensions ;
4
4
using Serilog ;
5
+ using Serilog . Context ;
5
6
using Serilog . Events ;
6
7
using Serilog . Filters ;
7
8
using Serilog . Sinks . File . Archive ;
@@ -16,7 +17,7 @@ public static class LogHelper
16
17
const string LogTemplate = "[{@t:yy-MM-dd HH:mm:ss.fff} {@l:u3}] " +
17
18
"{Substring(SourceContext, LastIndexOf(SourceContext, '.') + 1)}: " +
18
19
"{@m} {#if Length(Status) > 0}#{Status} <{UserName}>" +
19
- "{#if Length(IP) > 0}@ {IP}{#end}{#end}\n {@x}" ;
20
+ "{#if Length(IP) > 0} @ {IP}{#end}{#end}\n {@x}" ;
20
21
21
22
const string InitLogTemplate = "[{@t:yy-MM-dd HH:mm:ss.fff} {@l:u3}] {@m}\n {@x}" ;
22
23
@@ -83,7 +84,9 @@ public static void Log<T>(this ILogger<T> logger, string msg, string ip, TaskSta
83
84
public static void Log < T > ( this ILogger < T > logger , string msg , string uname , string ip , TaskStatus status ,
84
85
LogLevel ? level = null )
85
86
{
86
- using ( logger . BeginScope ( "{UserName}{Status}{IP}" , uname , status , ip ) )
87
+ using ( LogContext . PushProperty ( "UserName" , uname ) )
88
+ using ( LogContext . PushProperty ( "IP" , ip ) )
89
+ using ( LogContext . PushProperty ( "Status" , status . ToString ( ) ) )
87
90
{
88
91
logger . Log ( level ?? LogLevel . Information , "{msg:l}" , msg ) ;
89
92
}
@@ -93,15 +96,15 @@ public static void UseRequestLogging(this WebApplication app) =>
93
96
app . UseSerilogRequestLogging ( options =>
94
97
{
95
98
options . MessageTemplate =
96
- "[{StatusCode}] {Elapsed,8:####0.00}ms HTTP {RequestMethod,-6} {RequestPath} @ {RemoteIP }" ;
99
+ "[{StatusCode}] {Elapsed,8:####0.00}ms HTTP {RequestMethod,-6} {RequestPath} @ {IP }" ;
97
100
options . GetLevel = ( context , time , ex ) =>
98
101
context . Response . StatusCode == 204 ? LogEventLevel . Verbose :
99
102
time > 10000 && context . Response . StatusCode != 101 ? LogEventLevel . Warning :
100
103
context . Response . StatusCode > 499 || ex is not null ? LogEventLevel . Error : LogEventLevel . Debug ;
101
104
102
105
options . EnrichDiagnosticContext = ( diagnosticContext , httpContext ) =>
103
106
{
104
- diagnosticContext . Set ( "RemoteIP " , httpContext . Connection . RemoteIpAddress ) ;
107
+ diagnosticContext . Set ( "IP " , httpContext . Connection . RemoteIpAddress ) ;
105
108
} ;
106
109
} ) ;
107
110
0 commit comments