.NET Core 3.1 Azure Functions日志配置:本地与云端日志输出问题
问题场景
拥有.NET Core 3.1版本的Azure Functions应用,需要实现日志同时输出到本地Visual Studio对应窗口,以及Azure部署环境的“日志流(log stream)”中。当前已配置local.settings.json但本地Visual Studio的输出窗口无法看到日志语句。
函数示例代码:
[FunctionName("GetProjectLists")] public async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", Route = "project-lists/{projectId}")] HttpRequest req, ILogger log, [AccessToken] AccessTokenResult accessTokenResult, int projectId) { var error = AccessTokenReponse.ValidateResponse(accessTokenResult); if (error != null) { return error; } try { var userIdentity = new ClaimsIdentity(accessTokenResult.Principal.Claims); var account = await _tokenCache.GetAccount(userIdentity); // Check if the account is null or if the user is not an admin if (account == null || !account.isAdmin) { log.LogInformation($"User Identity: {userIdentity.Name}, Account ID: {account.id}, Account Admin: {account.isAdmin}"); // User is not authorized to access this resource return new StatusCodeResult(401); // Returns a 401 Unauthorized } // ... Do Work } catch (Exception ex) { return new BadRequestObjectResult(ex); } }
当前local.settings.json配置:
{ "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "UseDevelopmentStorage=true", "FUNCTIONS_WORKER_RUNTIME": "dotnet", "AzureWebJobsDashboard": "" }, "Logging": { "LogLevel": { "Default": "Information" } } }
本地开发环境配置(Visual Studio)
完善
local.settings.json的日志提供者配置
默认配置仅设置了日志级别,需显式开启Debug和Console输出提供者,确保日志能输出到Visual Studio窗口。更新后的配置如下:{ "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "UseDevelopmentStorage=true", "FUNCTIONS_WORKER_RUNTIME": "dotnet", "AzureWebJobsDashboard": "" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", // 过滤微软类库冗余日志 "Microsoft.Hosting.Lifetime": "Information" }, "Console": { "IncludeScopes": false }, "Debug": { "LogLevel": { "Default": "Information" } } } }选择正确的Visual Studio输出窗口
不要选择Debug选项卡,切换到Azure Functions选项卡,函数应用的运行日志、自定义日志都会输出到这个窗口。代码优化(可选)
在catch块中添加异常日志记录,确保异常信息也能被捕获:catch (Exception ex) { log.LogError(ex, "处理GetProjectLists请求时发生未预期异常"); return new BadRequestObjectResult(ex.Message); }
Azure部署环境配置(日志流)
启用Application Insights
在Azure门户的函数应用中,进入配置 -> 应用程序设置,添加或确认APPINSIGHTS_INSTRUMENTATIONKEY配置项,值为对应Application Insights实例的 instrumentation key,这是日志流的核心依赖。配置云端日志级别
可通过两种方式设置:- 门户方式:进入函数应用 -> 监测 -> 日志 -> 配置,设置默认日志级别为
Information; - 应用设置方式:添加应用程序设置
Logging__LogLevel__Default,值设为Information。
- 门户方式:进入函数应用 -> 监测 -> 日志 -> 配置,设置默认日志级别为
查看日志流
在Azure门户的函数应用中,进入监测 -> 日志流,选择应用程序日志选项卡,即可实时查看函数的日志输出,包括自定义的LogInformation、LogError等日志语句。
内容的提问来源于stack exchange,提问作者afriedman111

