【问题标题】:Azure function doesn't run async methodAzure 函数不运行异步方法
【发布时间】:2020-07-26 12:38:05
【问题描述】:

我有一个不在 Azure 中运行的 Azure 函数。 它在本地运行,但在 Azure 中不运行。我有一个 try/catch,它没有捕获任何异常,但在日志中我得到“2020-07-26T12:23:00.021 [错误] 发生异常。” 不明白我做错了什么。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using FluentEmail.Core;
using FluentEmail.Core.Models;
using FluentEmail.Mailgun;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;

namespace SendEmailFunction
{
    public static class SendEmailFunction
    {
        private const string EmailSubject = "Collaboration proposal";

        [FunctionName("SendEmailFunction")]
        public static async Task Run([TimerTrigger("0 */1 * * * *")] TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            try
            {
              var path = Path.Combine(Directory.GetCurrentDirectory(), "1.csv");
              List<string> lines = (await File.ReadAllLinesAsync(path)).ToList();
            }
            catch (Exception ex)
            {
                log.LogError($"An exception occured.", ex);
            }
        }
    }
}

这是我得到的日志:

2020-07-26T12:35:00.007 [信息] C# 定时器触发函数执行于:7/26/2020 12:35:00 PM

2020-07-26T12:35:00.030 [错误] 发生异常。

2020-07-26T12:35:00.045 [信息] 执行“SendEmailFunction”(成功,Id=8b5d1b47-37de-4f84-8936-d31b19f0f73d,持续时间=42ms)

【问题讨论】:

  • “[错误] 发生异常。” - 不是一个非常有用的日志消息。记录异常的内容怎么样?
  • 我猜你的电子邮件设置在服务器上不同,或者电子邮件服务器不接受来自 Azure 函数的请求。
  • 我在 try/catch 中有 cod,我记录了异常,如我共享的代码中所示:catch (Exception ex) { log.LogError($"发生异常。 “, 前任); } 但我什么也没得到。我的猜测是某些东西导致函数崩溃并且代码没有到达捕获部分。
  • 您使用错误的LogError 重载来记录异常:docs.microsoft.com/en-us/dotnet/api/… 您使用的是string, object[] 重载,而不是exception, string 重载。虽然这实际上并不能纠正您的问题,但它会为您提供有关异常的更多信息。此外,在“字符串”消息中记录一些有意义的内容,例如 ex.Message
  • 甚至不要传递 ex.Message... 当您将异常作为第一个参数传递时,它会自动作为格式化的一部分输出。相反,向您发送一条有意义的消息“无法执行某些功能”,以帮助您稍后追踪它。还要查找 ILogger 接口的用法。您不应该使用 string.Format 或字符串插值$"" 您应该在消息中使用占位符,然后将这些占位符的值作为附加参数传递。这一切都基于对结构化日志记录的支持(AppInsights 和 Azure 日志记录支持)

标签: c# azure azure-functions azure-function-app azure-function-async


【解决方案1】:

Kritner 的回答很有帮助,因为它让我看到了异常。

这是因为它没有找到我从中读取值的文件。我通过构造这样的路径来解决这个问题: var path = Path.Combine(context.FunctionAppDirectory, "1.csv");

context 是 Microsoft.Azure.WebJobs 命名空间中的 ExecutionContext。

现在已经修复了。

谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 2022-11-16
    • 2016-07-08
    • 2021-04-15
    相关资源
    最近更新 更多