简体   繁体   中英

How to log to azure app logs in Azure Functions V2?

Azure web apps, and by extension Azure Functions, allow sending log messages to blob storage as configured in the "diagnostic logs" configuration section.

However, the default ILogger instance you get passed to your C# Functions (v2) implementation ignores that setting. Instead, it seems you need to build a logger manually to use this functionality, as demonstrated below. Note that you need to add Microsoft.Extensions.Logging.AzureAppServices from NuGet to compile this.

[FunctionName("myfun")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequest req, 
    ILogger log)
{
    log.LogInformation("This does not end up in the app log.");

    var factory = new LoggerFactory().AddAzureWebAppDiagnostics();

    var log2 = factory.CreateLogger("MyFun");
    log2.LogInformation("This *does* end up in the app log, if configured.");
    log2.LogError("Fake error for testing logging functionality (2)");
}

My question: is there a more elegant way to get a logger that writes to the configured App Log blob storage? I would have expected that the log passed to the function already would have this functionality (maybe triggered by observing that an app log is configured), but by default it hasn't, and I don't see a clear path to how to add it, neither via configuration, nor by replacing the ILogger log argument by something else.

For Azure Function V2 you can use the injected ILogger to log all your logs as application insights and then you can go to your function application from azure portal > Application Insights > then choose Analytics (logs) > then you can use this query to retrieve all the logs:

    traces
    where appName == "YourAppName"

For the old function V2 you can use the injected traceWriter and integrate it with any logger so you can find your logs in auto created blob storage table related to this Function application and you can check it easily using Microsoft Azure Storage Explorer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM