[Azure Developer]把Azure Function中ILogger对象静态化为静态方法提供日志记录
问题描述
在Azure Function代码中,有默认的ILogger对象来记录函数的日志,如果函数引用了一些静态对象,是否有办法使用这个默认的ILogger对象来记录日志呢?
using System.Net; using Microsoft.Azure.Functions.Worker; using Microsoft.Azure.Functions.Worker.Http; using Microsoft.Extensions.Logging; namespace Company.Function { public class HttpTrigger1 { private readonly ILogger _logger; public HttpTrigger1(ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger<HttpTrigger1>(); } [Function("HttpTrigger1")] public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req) { _logger.LogInformation("C# HTTP trigger function processed a request."); var response = req.CreateResponse(HttpStatusCode.OK); response.Headers.Add("Content-Type", "text/plain; charset=utf-8"); response.WriteString("Welcome to Azure Functions!"); return response; } } }
问题解答
可以的,有两种方式来实现:方式一是把_logger对象作为参数传递给静态方法,方式二是自定义一个静态ILogger 对象,然后在静态方法中使用。
方式一:把_logger对象作为参数传递
示例代码:
[Function("Function1")] public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req) { ... //Call Static Fun without _logger GetLocalStaticFun(); //Call static Fun with _logger GetLocalStaticFun(_logger); ... } public static void GetLocalStaticFun(ILogger _sublogger = null) { //TODO Logic process if (_sublogger != null) { _sublogger.LogInformation("this is static fucntion for testing...LogInformation. @2023/10/25"); } }
测试效果:
方式二:定义静态ILogger对象
示例代码:
static ILoggerFactory _staticLoggerFactory = LoggerFactory.Create(builder => { builder .AddFilter("Microsoft", LogLevel.Warning) .AddFilter("System", LogLevel.Warning) .AddConsole(); }); static ILogger _staticloger = _staticLoggerFactory.CreateLogger<Function1>(); public static void GetStaticLogFun() { _staticloger.LogInformation("Example log message form static class"); _staticloger.LogError("Example error message form static class"); }
注:以此种方式记录的日志,当部署到Azure Function App云服务后,通过在高级工具(kudu)站点查看日志时,与正常的日志不同,在与函数名同名的Folder中,而是在Host Folder中(C:\home\LogFiles\Application\Functions\Host)。
参考资料
ILoggerFactory static create: https://learn.microsoft.com/en-us/dotnet/core/extensions/logging?tabs=command-line#non-host-console-app
当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2022-10-31 【Azure 云服务】云服务(经典)迁移到云服务(外延支持)的八个问题
2021-10-31 【Azure 环境】ADAL(Azure Active Directory Authentication Library )迁移到MSAL(Microsoft Authentication Library)相关问题