skip to Main Content

I am currently working with an ASP.NET Core v6 Function App v4 and want to add logging so I can save the logs to the database.

In past projects I’ve used Log4Net package, I see there is a nuget package that allows us to use it for ASP.NET Core v6, but it’s mostly for web and API projects with Program.cs files. The Function App only comes with a Startup.cs and doesn’t allow you to add ILogger.

I am wondering if there is a way or a work around in adding this tool or logging to the project in general or what other options there are our there.

Here is the link to the repo/docs for the nuget package.
Microsoft.Extensions.Logging.Log4Net.AspNetCore

And the original Log4Net site:

Log4net

Added like so and get the error:

IFunctionHostBuilder does not contain a definition of ‘Logging’ and no accessible extension methedon ‘Logging’ accepting a first argument of type ‘IFunctionsHostbuilder’ could not be found (are you missing a using dir or an assembly ref)?

Code:

 public override void Configure(IFunctionsHostBuilder builder)
 {
    //...
    builder.Logging.AddLog4Net();
    //...
 }

I’m pretty new to the Function apps so any guidance would be grateful.

2

Answers


  1. You can get rid of Startup.cs file in favor of one-file Program.cs. Configuration is then almost the same as in ASP.NET Core app

    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    
    var hostBuilder = new HostBuilder()
        .ConfigureFunctionsWorkerDefaults();
    
    hostBuilder.ConfigureLogging(builder =>
    {
        builder.ClearProviders();
        builder.AddLog4Net("log4net.config");
    });
    var host = hostBuilder.Build();
    
    host.Run();
    

    Function

    using System.Net;
    using Microsoft.Azure.Functions.Worker;
    using Microsoft.Azure.Functions.Worker.Http;
    using Microsoft.Extensions.Logging;
    
    namespace Company.FunctionApp2;
    
    public  class MyHttpTriggerFunction
    {
        private readonly ILogger<MyHttpTriggerFunction> logger;
    
        public MyHttpTriggerFunction(ILogger<MyHttpTriggerFunction> logger)
        {
            this.logger = logger;
        }
    
        [Function("MyHttpTriggerFunction")]
        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;
            
        }
    }
    

    UPD:
    Your csproj file should contain:

    <ItemGroup>
        <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.18.0" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.12" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.13.0" />
        <PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="6.1.0" />
    </ItemGroup>
    

    To make app isolated, set configuration value in local.settings.json

    {
        "IsEncrypted": false,
        "Values": {
            "AzureWebJobsStorage": "UseDevelopmentStorage=true",
            "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated" <--- this
        }
    }
    

    and in Azure

    Azure

    Login or Signup to reply.
  2. You may consider serilog, will be much more easier to use for non-isolated function. No startup.cs/program.cs or other configuration needed.
    Create a project like below.
    enter image description here
    Install package Serilog Serilog.Sinks.Console``Serilog.Sinks.MSSqlServer
    Modify the Function1.cs like below

        public static class Function1
        {
            [FunctionName("Function1")]
            public static async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req)
            {
                var log = new LoggerConfiguration()
                .WriteTo.Console(new JsonFormatter())
               .WriteTo.MSSqlServer(
                            connectionString: "Data Source = 192.168.2.68; Initial Catalog = LogDb; User ID = sa; Password = xxxxx; TrustServerCertificate = True",
                            tableName:"function1_log",
                            autoCreateSqlTable:true               
                     )
                .CreateLogger();
    
                log.Information("A serilog information");
    ...
    

    Test
    enter image description here
    Check Sqlserver
    enter image description here
    Reference: https://stackify.com/logging-azure-functions/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search