0

这是我拥有的代码的胆量。我想写入日志以进行故障排除。它不喜欢其他方法。我看到了一些例子,他们讨论了如何实现这一点,但我找不到真正的代码来尝试。

我正在门户中编写 Azure 函数。

非常感谢任何帮助。

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

   bool isGood = Verify(myKey, myInput;

   return code != null
        ? (ActionResult)new OkObjectResult($"Request Successful")
        : new BadRequestObjectResult("Bad Request");

} // End Main

public static bool Verify(String key, String input)

    {

        log.LogInformation("Write something here");

    return;

    }

    private static string CreateToken(string message, string secret)

    {
        log.LogInformation("Write something here");
        return;
    }
4

2 回答 2

1

您需要将 ILogger 传递给您的方法,将其分配给 Run 方法中的静态变量:

选项1:

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

   bool isGood = Verify(myKey, myInput, log);
   var token = CreateToken("abc","def",log);

   return code != null
        ? (ActionResult)new OkObjectResult($"Request Successful")
        : new BadRequestObjectResult("Bad Request");

} // End Main

public static bool Verify(String key, String input, ILogger log)

    {

        log.LogInformation("Write something here");

    return true;

    }

    private static string CreateToken(string message, string secret, ILogger log)

    {
        log.LogInformation("Write something here");
        return "";
    }

选项2:

public static class Function1
{
   private static ILogger _log = null;
   public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
   {
    _log = log;
    log.LogInformation("C# HTTP trigger function processed a request.");

   bool isGood = Verify(myKey, myInput;

   return code != null
        ? (ActionResult)new OkObjectResult($"Request Successful")
        : new BadRequestObjectResult("Bad Request");

} // End Main

public static bool Verify(String key, String input)

    {

        _log.LogInformation("Write something here");

    return true;

    }

    private static string CreateToken(string message, string secret)

    {
        _log.LogInformation("Write something here");
        return "";
    }
}
于 2020-02-05T23:44:00.920 回答
0

在类级别创建一个静态 ILogger,在 Azure Functions 调用的方法之一中分配它,然后在其他类中使用它。

public static class LogTest
{
    static ILogger _log;

    [FunctionName("LogTest")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        _log = log;
        log.LogInformation("C# HTTP trigger function processed a request.");

        LogIt("Log this");

        return (ActionResult)new OkObjectResult($"Done logging");
    }

    private static void LogIt(string s)
    {
        _log.LogInformation(s);
    }
}
于 2020-02-05T23:00:24.623 回答