首页 > 其他分享 >[Azure Developer]把Azure Function中ILogger对象静态化为静态方法提供日志记录

[Azure Developer]把Azure Function中ILogger对象静态化为静态方法提供日志记录

时间:2023-10-31 20:33:02浏览次数:33  
标签:Function 静态方法 static ILogger Azure logger public

问题描述

在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");
            }
        }

测试效果:

[Azure Developer]把Azure Function中ILogger对象静态化为静态方法提供日志记录_静态方法

 

方式二:定义静态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

 


当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!

标签:Function,静态方法,static,ILogger,Azure,logger,public
From: https://blog.51cto.com/u_13773780/8113930

相关文章

  • [Azure Developer]把Azure Function中ILogger对象静态化为静态方法提供日志记录
    问题描述在AzureFunction代码中,有默认的ILogger对象来记录函数的日志,如果函数引用了一些静态对象,是否有办法使用这个默认的ILogger对象来记录日志呢?usingSystem.Net;usingMicrosoft.Azure.Functions.Worker;usingMicrosoft.Azure.Functions.Worker.Http;usingMicrosoft......
  • soft Exponential activation function
    全文https://ieeexplore.ieee.org/document/7526959SoftExponentialActivationFunction ASoftExponentialActivationFunctionisaparametricneuronactivationfunctionthatisbasedontheinperpolationoftheidentity,logarithmandexponentialfunctions......
  • 【Azure Function App】如何修改Azure函数应用的默认页面呢?
    问题描述当在Azure中创建了一个函数应用(FunctionApp)后,访问默认URL会得到一个默认的页面。是否有办法修改这个默认页面呢?  问题解答在之前的博文中,介绍了修改AppService的默认页面。1:【Azure应用服务】AppService默认页面暴露Tomcat版本信息,存在安全风险 :https://www.cnbl......
  • python面向对象-学习笔记(三、类方法、实例方法、静态方法)
    方法相关方法的概念描述一个目标的行为动作和函数相似封装了一系列行为动作。比如一个人怎么吃,怎么喝,怎么玩...都可以被调用最主要区别:调用方式方法的划分实例方法:默认第一个参数是一个实例类方法:默认第一个参数是类静态方法:没有默认参数注意划分的依据:方法的第一......
  • 【Azure 存储服务】访问Azure Blob File遇见400-Condition Headers not support错误的
    ThisXMLfiledoesnotappeartohaveanystyleinformationassociatedwithit.Thedocumenttreeisshownbelow.问题描述在微软云存储账号的服务中,存储一些静态图片,然后通过AppService访问,但是遇见了400-conditionheadersnotsupport错误......
  • 【Azure Storage Account Table】询问批量将存储账户中的表嵌入另一个账户中的办法
    问题描述询问批量将存储账户中的表嵌入另一个账户中的办法? 问题解答方式一:使用 AzCopy 使用Azcopy做表格的导入导出,注意您需要使用Azcopy7.3版本来实现对Table的操作,可以选择导出到Blob中,这样导出的数据不会保存在本地,以及该指定支持并发导出。从表存储导出数据: https://le......
  • 【Azure Batch】在中国区批处理服务(Mooncake Batch Account)上实验自动池(Auto Pool)
    问题描述在AzureBatch的介绍文档中,提出了自动池的概念,它可以在任务完成后,自动删除Pool资源,详细介绍:https://docs.azure.cn/zh-cn/batch/nodes-and-pools#autopools& https://learn.microsoft.com/zh-cn/rest/api/batchservice/job/add?tabs=HTTP#autopoolspecification自动池是......
  • Azure DevOps 发布.Net项目到Windows IIS站点之pubxml
    通过VS中我们配置的pubxml进行发布trigger:-masterpool:vmImage:'windows-2022'variables:-group:GeexPublish-name:my-user-variablevalue:$[variables.UserName]#usesruntimeexpression-name:my-passed-variablevalue:$[variables.PassWord]......
  • C++ invoke与function的区别
    C++invokeinvoke是C++17标准引入的一个函数模板,用来调用可调用对象(CallableObject,如函数指针、函数对象、成员函数指针等)并返回结果。invoke提供了统一的调用语法,无论可调用对象的类型是什么,都可以使用同一种方式进行调用。详见:https://en.cppreference.com/w/cpp/utility/fu......
  • kernel function: the difference beween cdev_add and device_create
     Touseacharacterdriver,firstyoushouldregisteritwiththesystem.Thenyoushouldexposeittotheuserspace. 1.cdev_initandcdev_addfunctionsperformthecharacterdeviceregistration.cdev_addaddsthecharacterdevicetothesystem.When......