Ver Fonte

增加请求日志中间件

陈国伟 há 4 anos atrás
pai
commit
f220613178

+ 7 - 1
FastGithub.ReverseProxy/DomainResolver.cs

@@ -1,5 +1,6 @@
 using DNS.Client;
 using Microsoft.Extensions.Caching.Memory;
+using Microsoft.Extensions.Logging;
 using System;
 using System.Linq;
 using System.Net;
@@ -15,6 +16,7 @@ namespace FastGithub.ReverseProxy
     {
         private readonly IMemoryCache memoryCache;
         private readonly FastGithubConfig fastGithubConfig;
+        private readonly ILogger<DomainResolver> logger;
         private readonly TimeSpan cacheTimeSpan = TimeSpan.FromSeconds(10d);
 
         /// <summary>
@@ -24,10 +26,12 @@ namespace FastGithub.ReverseProxy
         /// <param name="fastGithubConfig"></param>
         public DomainResolver(
             IMemoryCache memoryCache,
-            FastGithubConfig fastGithubConfig)
+            FastGithubConfig fastGithubConfig,
+            ILogger<DomainResolver> logger)
         {
             this.memoryCache = memoryCache;
             this.fastGithubConfig = fastGithubConfig;
+            this.logger = logger;
         }
 
         /// <summary>
@@ -74,6 +78,8 @@ namespace FastGithub.ReverseProxy
                 {
                     throw new FastGithubException($"dns({dns})被污染:解析{domain}为{address}");
                 }
+
+                this.logger.LogInformation($"[{domain}->{address}]");
                 return address;
             }
             catch (FastGithubException)

+ 2 - 18
FastGithub.ReverseProxy/HttpClientHanlder.cs

@@ -1,5 +1,4 @@
-using Microsoft.Extensions.Logging;
-using System;
+using System;
 using System.Net.Http;
 using System.Net.Security;
 using System.Net.Sockets;
@@ -14,18 +13,14 @@ namespace FastGithub.ReverseProxy
     class HttpClientHanlder : DelegatingHandler
     {
         private readonly DomainResolver domainResolver;
-        private readonly ILogger<HttpClientHanlder> logger;
 
         /// <summary>
         /// YARP的HttpClientHandler
         /// </summary>
         /// <param name="domainResolver"></param> 
-        public HttpClientHanlder(
-            DomainResolver domainResolver,
-            ILogger<HttpClientHanlder> logger)
+        public HttpClientHanlder(DomainResolver domainResolver)
         {
             this.domainResolver = domainResolver;
-            this.logger = logger;
             this.InnerHandler = CreateSocketsHttpHandler();
         }
 
@@ -62,7 +57,6 @@ namespace FastGithub.ReverseProxy
             };
         }
 
-
         /// <summary>
         /// 替换域名为ip
         /// </summary>
@@ -82,16 +76,6 @@ namespace FastGithub.ReverseProxy
                 };
                 request.RequestUri = builder.Uri;
                 request.Headers.Host = uri.Host;
-
-                var context = request.GetSniContext();
-                if (context.IsHttps && context.TlsSniValue.Length > 0)
-                {
-                    this.logger.LogInformation($"[{address}--Sni->{uri.Host}]");
-                }
-                else
-                {
-                    this.logger.LogInformation($"[{address}--NoSni->{uri.Host}]");
-                }
             }
             return await base.SendAsync(request, cancellationToken);
         }

+ 8 - 1
FastGithub.ReverseProxy/KestrelServerOptionsExtensions.cs

@@ -92,7 +92,14 @@ namespace FastGithub
             }
             catch (Exception)
             {
-                logger.LogWarning($"安装根证书{caPublicCerPath}失败:请手动安装到“将所有的证书都放入下载存储”\\“受信任的根证书颁发机构”");
+                if (OperatingSystem.IsWindows())
+                {
+                    logger.LogWarning($"安装根证书{caPublicCerPath}失败:请手动安装到“将所有的证书都放入下载存储”\\“受信任的根证书颁发机构”");
+                }
+                else
+                {
+                    logger.LogWarning($"安装根证书{caPublicCerPath}失败:请根据你的系统平台要求安装和信任根证书");
+                }
             }
         }
 

+ 58 - 0
FastGithub.ReverseProxy/RequestLoggingMilldeware.cs

@@ -0,0 +1,58 @@
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Logging;
+using System.Diagnostics;
+using System.Threading.Tasks;
+
+namespace FastGithub.ReverseProxy
+{
+    /// <summary>
+    /// 请求日志中间件
+    /// </summary>
+    sealed class RequestLoggingMilldeware
+    {
+        private readonly ILogger<RequestLoggingMilldeware> logger;
+
+        /// <summary>
+        /// 请求日志中间件
+        /// </summary>
+        /// <param name="logger"></param>
+        public RequestLoggingMilldeware(ILogger<RequestLoggingMilldeware> logger)
+        {
+            this.logger = logger;
+        }
+
+        /// <summary>
+        /// 执行请求
+        /// </summary>
+        /// <param name="context"></param>
+        /// <param name="next"></param>
+        /// <returns></returns>
+        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
+        {
+            var stopwatch = new Stopwatch();
+            stopwatch.Start();
+
+            try
+            {
+                await next(context);
+            }
+            finally
+            {
+                stopwatch.Stop();
+            }
+
+            var request = context.Request;
+            var response = context.Response;
+            var message = $"{request.Method} {request.Scheme}://{request.Host}{request.Path} responded {response.StatusCode} in {stopwatch.Elapsed.TotalMilliseconds} ms";
+
+            if (500 <= response.StatusCode && response.StatusCode <= 599)
+            {
+                this.logger.LogError(message);
+            }
+            else
+            {
+                this.logger.LogInformation(message);
+            }
+        }
+    }
+}

+ 11 - 0
FastGithub.ReverseProxy/ReverseProxyApplicationBuilderExtensions.cs

@@ -9,6 +9,17 @@ namespace FastGithub
     /// </summary>
     public static class ReverseProxyApplicationBuilderExtensions
     {
+        /// <summary>
+        /// 使用请求日志中间件
+        /// </summary>
+        /// <param name="app"></param> 
+        /// <returns></returns>
+        public static IApplicationBuilder UseRequestLogging(this IApplicationBuilder app)
+        {
+            var middlware = app.ApplicationServices.GetRequiredService<RequestLoggingMilldeware>();
+            return app.Use(next => context => middlware.InvokeAsync(context, next));
+        }
+
         /// <summary>
         /// 使用https反向代理中间件
         /// </summary>

+ 1 - 0
FastGithub.ReverseProxy/ReverseProxyServiceCollectionExtensions.cs

@@ -20,6 +20,7 @@ namespace FastGithub
                 .AddHttpForwarder()
                 .AddSingleton<DomainResolver>()
                 .AddTransient<HttpClientHanlder>()
+                .AddSingleton<RequestLoggingMilldeware>()
                 .AddSingleton<ReverseProxyMiddleware>();
         }
     }

+ 5 - 1
FastGithub/Program.cs

@@ -41,7 +41,11 @@ namespace FastGithub
                 })
                 .ConfigureWebHostDefaults(web =>
                 {
-                    web.Configure(app => app.UseHttpsReverseProxy("README.html"));
+                    web.Configure(app =>
+                    {
+                        app.UseRequestLogging();
+                        app.UseHttpsReverseProxy("README.html");
+                    });
                     web.UseKestrel(kestrel => kestrel.ListenHttpsReverseProxy());
                 });
         }