首页 > 解决方案 > HTTP 触发 Azure 函数:OutOfMemoryException 未登录监视器

问题描述

我只是在浏览 Azure 函数,并试图在发生异常时检查 Azure 函数的行为。我浏览了 Microsoft 提供的有关错误处理的文档,并制作了一个非常简单的 HTTP 触发器。这里是

代码

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log, ExecutionContext context)
{
 log.LogInformation("C# HTTP trigger function processed a request.");

 string name = req.Query["name"];

try
{
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;
    switch (name)
        {
            case "OutOfMemoryException":               
                throw new System.OutOfMemoryException();
            case "NullReferenceException":
                throw new System.NullReferenceException();
            case "IndexOutOfRangeException":
                throw new System.IndexOutOfRangeException();
            case "InvalidOperationException":
                throw new System.InvalidOperationException();
            case "ArgumentNullException":
                throw new System.ArgumentNullException();
            default:
                break;
        }
}
catch(System.Exception ex)
{
    throw;
}

return name != null
    ? (ActionResult)new OkObjectResult($"Hello, {name}")
    : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}

问题

发生内存不足异常时,我无法查看日志。它不在这里,也不在应用程序洞察中,它被登录到控制台,但只有那个临时。在列表中的前两个日志之间,我触发了 OutOfMemoryException,但是没有日志。

这是 Azure 中的一个已知问题吗?

监控截图

在此处输入图像描述

标签: c#azureazure-functionsazure-application-insights

解决方案


OutOfMemoryException与您列表中的其他人相比,这是一个特殊的例外。一旦抛出此异常,函数主机将被关闭,并且不会像您发现的那样将日志发送到 Application Insights。

IMO,OutOfMemoryException通常由函数主机本身抛出和处理,因为我们可能没有方法来处理我们自己的代码中的内存问题。如果您要设置自己的内存限制,我的建议是不要将异常抛出到函数主机,我们可以自己记录异常。

catch(System.Exception ex)
{
    log.LogError(ex, ex.Message);
}

我们还可以跟踪 kudu 中的所有日志,转到https://<functionAppName>.scm.azurewebsites.net/DebugConsole并导航到D:\home\LogFiles\Application\Functions\function\<FunctionName>以检查特定于功能的日志。


推荐阅读