How can I inject the default azure function logger in other classes?

Viewed 535

I´m using azure functions using dotnet core 3.1 and I cannot make my custom logs work as expected.

In my values section of the local.settings.json file i put the following key: APPINSIGHTS_INSTRUMENTATIONKEY and i read on the docs that the functions runtime add the log automatically.

I can see the default logs on the application insights panel, but my custom logs are not being write there. On my class I did this:

     private readonly ILogger<LoginService> _logger;
     public CustomService(ILogger<CustomService> logger)
     {
          _logger = logger;
     }

     public void Test() 
     {
          _logger.LogError("TestLog");
     } 

How is the proper way of injecting the default logging in the constructor of other classes which is not the function method itself?

1 Answers

ILogger is indeed not a valid injections. ILogger does work and creates a filter of type T. However you need to manually add the ability to listen to custom filters (in this case your class) for them to show up. you can do that in host.json. Here's a sample.

host.json:

{
    "version": "2.0",
    "logging": {
        "applicationInsights": {
            "samplingExcludedTypes": "Request",
            "samplingSettings": {
                "isEnabled": true
            }
        },
        "logLevel": {
            "Hollan.Functions.HttpTrigger": "Information"
        }
    }
}

HttpTrigger.cs

   public class HttpTrigger
    {
        private readonly ILogger<HttpTrigger> _log;

        public HttpTrigger(ILogger<HttpTrigger> log)
        {
            _log = log;
        }

        [FunctionName("HttpTrigger")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req)
        {
            _log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
        }
    }
}

Source: https://github.com/Azure/Azure-Functions/issues/1484

Related