Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serilog Azure Function V3

I would like to know how I can use Serilog in Azure function. I have created a startup class in my function with the following setup:

 var loggerConfiguration = new LoggerConfiguration()
            .WriteTo.Console()
            .CreateLogger();

 builder.Services.AddLogging(op => op.AddSerilog(loggerConfiguration));

How do I inject the ILogger from serilog into my Function?

using Serilog;

namespace LogFunction

public class XX
{
    [FunctionName("XX")]
    public void Run([TimerTrigger("*/60 * * * * *")]TimerInfo myTimer, ILogger log)
    {
        log.Information("Log this object {Car}", car); //using serilog not Microsoft.Extensions.Logging
    }
}

As you can see above I am referencing the ILogger from Serilog and not Microsoft Logging.

like image 459
hello world Avatar asked Sep 19 '20 15:09

hello world


1 Answers

One possible solution would be that you let inject the logger in the constructor of your function class.

public class XX
{
    private ILogger _logger;
    public XX(ILogger logger)
    {
        _logger = logger;
    }

    [FunctionName("XX")]
    public void Run([TimerTrigger("*/60 * * * * *")]TimerInfo myTimer)
    {
        _logger.Information("Log this object {Car}", car); //using serilog not Microsoft.Extensions.Logging
    }
}
like image 118
Sebastian Achatz Avatar answered Oct 12 '22 13:10

Sebastian Achatz