受欢迎的博客标签

.NET Core version:ASP.NET Core 2.x

OS:windows server 2012 R2

 In ASP.NET Core 2.x, logging is created at the host builder. This means that logging is available through DI by default and can be injected into the Startup class.

step 1:Set whether startup errors should be captured in the configuration settings of the web host.

 public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)

                .CaptureStartupErrors(true) // use startup error page;Set whether startup errors should be captured in the configuration settings of the web host.
                                            //When enabled, startup exceptions will be caught and an error page will be returned.If disabled, startup exceptions will be propagated.
                                            // .UseSetting("detailedErrors", "true")
               .UseSetting(WebHostDefaults.DetailedErrorsKey, "true")
               .ConfigureLogging(builder => builder.AddNopLogger())
             




                .UseStartup<Startup>();
    }

 

step 2: write a custom LoggerProvider

  public class NopLoggerProvider : ILoggerProvider
    {

        private readonly IDisposable _optionsChangeToken;

       

       

        private class NopLogger : ILogger
        {
            public bool IsEnabled(LogLevel logLevel)
            {
                return true;
            }

            public void  Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
            {
                
                if (exception == null)
                {
                    return;
                }

                string path = "c:\\log";
                string filename = DateTime.Now.ToString("yyyy-MM-dd") + ".log";

                var directory = Path.GetDirectoryName(path);
                if (!string.IsNullOrWhiteSpace(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                              

                //come from :https://stackoverflow.com/questions/35310078/how-to-write-to-a-file-in-net-core
                var logPath = Path.Combine(path, filename);
               

                var logFile = System.IO.File.Open(logPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);

             
                var logWriter = new System.IO.StreamWriter(logFile);


                var builder = new StringBuilder();
                builder.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff zzz"));
                builder.Append(" [");
                builder.Append(logLevel.ToString());
                builder.Append("] ");
               // builder.Append(_category);
                builder.Append(": ");
                builder.AppendLine(formatter(state, exception));

                if (exception != null)
                {
                    builder.AppendLine(exception.ToString());
                }


                logWriter.WriteAsync(builder.ToString());

                logWriter.Flush();
                logFile.Flush(true);
                
                
            }

           

            public IDisposable BeginScope<TState>(TState state)
            {
                return null;
            }
        }

        public ILogger CreateLogger(string categoryName)
        {
            return new NopLogger();
        }
        public void Dispose()
        {
            _optionsChangeToken?.Dispose();
        }
    }

 

step 3: 

 

c:\log\2018-11-13.log

018-11-13 18:54:34.224 +08:00 [Information] : Connection id "0HLI9APIQ5U8R" bad request data: "Malformed request: invalid headers."
Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Malformed request: invalid headers.
   at Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException.Throw(RequestRejectionReason reason)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1Connection.TryParseRequest(ReadResult result, Boolean& endConnection)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequestsAsync[TContext](IHttpApplication`1 application)
2018-11-13 19:34:48.226 +08:00 [Information] : Connection id "0HLI9BG27RC33" bad request data: "Malformed request: invalid headers."
Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Malformed request: invalid headers.
   at Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException.Throw(RequestRejectionReason reason)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1Connection.TryParseRequest(ReadResult result, Boolean& endConnection)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequestsAsync[TContext](IHttpApplication`1 application)
2018-11-13 19:46:52.268 +08:00 [Information] : Connection id "0HLI9BMQ0U1C8" bad request data: "Malformed request: invalid headers."
Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Malformed request: invalid headers.
   at Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException.Throw(RequestRejectionReason reason)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1Connection.TryParseRequest(ReadResult result, Boolean& endConnection)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequestsAsync[TContext](IHttpApplication`1 application)
2018-11-13 19:46:52.272 +08:00 [Information] : Connection id "0HLI9BMQ0U1C8" bad request data: "Malformed request: invalid headers."
Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Malformed request: invalid headers.
   at Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException.Throw(RequestRejectionReason reason)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1Connection.TryParseRequest(ReadResult result, Boolean& endConnection)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequestsAsync[TContext](IHttpApplication`1 application)
2018-11-13 19:48:45.211 +08:00 [Information] : Connection id "0HLI9BNRM1TE0" bad request data: "Malformed request: invalid headers."
Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Malformed request: invalid headers.
   at Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException.Throw(RequestRejectionReason reason)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1Connection.TryParseRequest(ReadResult result, Boolean& endConnection)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequestsAsync[TContext](IHttpApplication`1 application)
2018-11-13 20:03:28.081 +08:00 [Information] : Connection id "0HLI9BNRM1TEM" bad request data: "Malformed request: invalid headers."
Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Malformed request: invalid headers.
   at Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException.Throw(RequestRejectionReason reason)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1Connection.TryParseRequest(ReadResult result, Boolean& endConnection)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequestsAsync[TContext](IHttpApplication`1 application)