Wednesday, April 6, 2022

In-Process Azure Function, EF Core Logging using ILogger

In this post, let's see how we can configure EF Core logging using ILogger in an In-Process Azure Function.

First, I am registering my DbContext in the Startup.cs as follows.

Startup.cs

[assembly: FunctionsStartup(typeof(FunctionApp1.Startup))]
namespace FunctionApp1;
 
public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        IConfiguration configuration = builder.Services.BuildServiceProvider().GetService<IConfiguration>();
 
        builder.Services.AddDbContext<MyDbContext>(options =>
            options
                .UseSqlServer(configuration.GetValue<string>("MyDbContext_ConnectionString")));
    }
}

Then in my DbContext, I am overriding the OnConfiguring method as follows.

MyDbContext.cs

public class MyDbContext : DbContext
{
    private readonly IHostingEnvironment _hostingEnvironment;
    private readonly ILogger<MyDbContext> _logger;
 
    public MyDbContext(DbContextOptions options, 
        IHostingEnvironment hostingEnvironment, 
        ILogger<MyDbContext> logger) : base(options)
    {
        _hostingEnvironment = hostingEnvironment;
        _logger = logger;
    }
 
    public DbSet<Employee> Employees { getset; }
 
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // Only logging in Development environment to avoid unnecessary noice in Production Environment
        if (_hostingEnvironment.IsDevelopment())
        {
            optionsBuilder
                .LogTo(action =>
                {
                    _logger.LogInformation(action);
                    // TODO: Customize logging, use any LogTo Overload
                });
        }
    }
}

Here I am using DbContextOptionsBuilder.LogTo Method which was introduced in EF Core 5.0.

And now I am invoking the following function to generate some logs.

public class Function1
{
    private readonly MyDbContext _myDbContext;
 
    public Function1(MyDbContext myDbContext)
    {
        _myDbContext = myDbContext;
    }
 
    [FunctionName("Employees")]
    public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest request)
    {
        string requestBody = await new StreamReader(request.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        string name = data?.name;
 
        Employee employee = new()
        {
            Name = name
        };
        await _myDbContext.Employees.AddAsync(employee);
        await _myDbContext.SaveChangesAsync();
 
        return new OkObjectResult(employee);
    }
}

And now I can see EF Core Logging is getting triggered.

I am using App Insights, and I can see the logs there.

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment