[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
当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!