1+ #nullable disable
2+
3+ using System ;
4+ using System . Net ;
5+ using AngleSharp . Io ;
6+ using Microsoft . AspNetCore . Http ;
7+ using Microsoft . AspNetCore . Http . Extensions ;
8+ using NLog ;
9+
10+ namespace VocaDb . Web . Code
11+ {
12+ public static class ErrorLogger
13+ {
14+ public const int Code_BadRequest = ( int ) HttpStatusCode . BadRequest ;
15+ public const int Code_Forbidden = ( int ) HttpStatusCode . Forbidden ;
16+ public const int Code_NotFound = ( int ) HttpStatusCode . NotFound ;
17+ public const int Code_InternalServerError = ( int ) HttpStatusCode . InternalServerError ;
18+
19+ private static readonly Logger s_log = LogManager . GetCurrentClassLogger ( ) ;
20+
21+ /// <summary>
22+ /// Logs HTTP error code sent to a client.
23+ /// This method is mostly for client errors (status code 4xx).
24+ ///
25+ /// Client info and error summary will be logged.
26+ /// Full exceptions should be logged separately using <see cref="LogException"/>.
27+ /// </summary>
28+ /// <param name="request">HTTP request. Cannot be null.</param>
29+ /// <param name="code">HTTP response code.</param>
30+ /// <param name="msg">Optional simple message, usually exception message.</param>
31+ /// <param name="level">Logging level, optional.</param>
32+ public static void LogHttpError ( HttpRequest request , int code , string msg = null , LogLevel level = null )
33+ {
34+ if ( string . IsNullOrEmpty ( msg ) )
35+ s_log . Log ( level ?? LogLevel . Warn , RequestInfo ( $ "HTTP error code { code } for", request ) ) ;
36+ else
37+ s_log . Log ( level ?? LogLevel . Warn , RequestInfo ( $ "HTTP error code { code } ({ msg } ) for", request ) ) ;
38+ }
39+
40+ public static void LogException ( HttpRequest request , Exception ex , LogLevel level = null )
41+ {
42+ s_log . Log ( level ?? LogLevel . Error , ex , RequestInfo ( "Exception for" , request ) ) ;
43+ }
44+
45+ public static void LogMessage ( HttpRequest request , string msg , LogLevel level = null )
46+ {
47+ s_log . Log ( level ?? LogLevel . Error , RequestInfo ( msg + " for" , request ) ) ;
48+ }
49+
50+ public static string RequestInfo ( string msg , HttpRequest request )
51+ {
52+ var userHostAddress = request . HttpContext . Connection . RemoteIpAddress ;
53+ var userHostName = request . GetTypedHeaders ( ) . Host ;
54+ var httpMethod = request . Method ;
55+ var pathAndQuery = request . GetEncodedPathAndQuery ( ) ;
56+ var userAgent = request . Headers [ HeaderNames . UserAgent ] ;
57+ var urlReferrer = request . GetTypedHeaders ( ) . Referer ;
58+ return $ "{ msg } '{ userHostAddress } ' [{ userHostName } ], URL { httpMethod } '{ pathAndQuery } ', UA '{ userAgent } ', referrer '{ urlReferrer } '";
59+ }
60+ }
61+ }
0 commit comments