【问题标题】:How can i get logs/debugging for an error 500?如何获取错误 500 的日志/调试?
【发布时间】:2019-06-20 08:33:00
【问题描述】:

我正在开发一个 .NET Core 2.0 Web 应用程序。我有一个模拟数据库,其中应用程序运行良好。今天我创建了一个干净的数据库,并在 IIS Express 和常规 IIS 上都得到了这个错误 500。 问题是:我无法调试为什么会抛出错误 500。应用程序刚刚运行。

我目前已经尝试过:

  • 通过激活stdoutLogEnabled="true" 检查 IIS 日志,创建的唯一日志是:

托管环境:生产内容根路径: C:\Users\pistolon\Downloads\peto 现在正在听: http://localhost:13361 应用程序已启动。按 Ctrl+C 关闭。

  • 从 startup.cs 文件开始调试。

当我切换回模拟数据库时,它可以正常工作。

你们中的任何人都可以指出我在哪里可以获得例外或记录吗?

【问题讨论】:

    标签: asp.net asp.net-mvc iis asp.net-core .net-core


    【解决方案1】:

    您可以使用Event ViewerVisual Studio Remote Debugging 来调试您部署的应用程序。

    此外,您可以使用像 Serilog 这样的日志框架,并使用其中一个像 file sink 这样的接收器,并创建一个中间件来捕获和记录您的异常,并将它们的 StackTrace、Message、Source 写入日志文件,您可以阅读它们。

    这里是 ErrorHandlingMiddleware 实现:

    public class ErrorHandlingMiddleware
    {
        readonly RequestDelegate _next;
        static ILogger<ErrorHandlingMiddleware> _logger;
    
        public ErrorHandlingMiddleware(RequestDelegate next,
            ILogger<ErrorHandlingMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }
    
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }
    
        static async Task HandleExceptionAsync(
             HttpContext context,
             Exception exception)
        {
            string error = "An internal server error has occured.";
    
            _logger.LogError($"{exception.Source} - {exception.Message} - {exception.StackTrace} - {exception.TargetSite.Name}");
    
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            context.Response.ContentType = "application/json";
    
            await context.Response.WriteAsync(JsonConvert.SerializeObject(new
            {
                error
            }));
        }
    }
    

    用法

    app.UseMiddleware<ErrorHandlingMiddleware>();
    

    【讨论】:

      【解决方案2】:

      我不认为这是足够的信息,但是如果您在使用真实数据库时看到 500 错误并且模拟数据库正常工作,我敢打赌您的问题与连接字符串有关.您还可以检查以确保您也在开发环境中。

      更新:你也可以尝试使用 app.UseDeveloperExceptionPage();

      【讨论】:

      • app.UseDeveloperExceptionPage();为我工作,谢谢!我可以看到错误并调试它。
      • 只是想说我花了 14 分钟才弄清楚如何解决这个问题。谢谢!我花了一整天的时间!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-13
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多