Search code examples
azureloggingserilogazure-webjobssdkazure-webjobs-continuous

Serilog: azure webjob logging doesn't seem to work when hosted in azure?


I have azure webjob sdk (v3.0.3) app which has been configured to use serilog for logging. The log seems to work when I run the app locally in my system. Below is the configuration:

    static void Main(string[] args)
        {
            try
            {
                var builder = new HostBuilder()
                        .ConfigureAppConfiguration(SetupConfiguration)
                        .ConfigureLogging(SetupLogging)
                        .ConfigureServices(SetupServices)
                        .ConfigureWebJobs(webJobConfiguration =>
                        {
                            webJobConfiguration.AddTimers();
                            webJobConfiguration.AddAzureStorageCoreServices(); //this is to store logs in azure storage 
                        })
                        .UseSerilog()
                    .Build();
                builder.Run();
            }
}

The code for SetupConfiguration is below:

  private static void SetupConfiguration(HostBuilderContext hostingContext, IConfigurationBuilder builder)
        {
            var env = hostingContext.HostingEnvironment;
            _configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build();
        }

The code for setting up services:

private static void SetupServices(HostBuilderContext hostingContext, IServiceCollection serviceCollection)
    {
        serviceCollection.AddSingleton<IConfiguration>(_configuration);
        Log.Logger = new LoggerConfiguration()
            .ReadFrom.Configuration(_configuration)
            .CreateLogger();
        _logger = serviceCollection.BuildServiceProvider().GetRequiredService<ILoggerFactory>().CreateLogger("test");
    }

The logging is setup as following:

  private static void SetupLogging(HostBuilderContext hostingContext, ILoggingBuilder loggingBuilder)
        {
            loggingBuilder.SetMinimumLevel(LogLevel.Information);
            loggingBuilder.AddConsole();
            loggingBuilder.AddDebug();
            loggingBuilder.AddSerilog(dispose: true);
        }

In my TimerTrigger method I'm using the logger:

[Singleton]
        public async static Task Trigger([TimerTrigger("%Job%")]TimerInfo myTimer)
        {           
          _logger.LogInformation($"From Trigger {DateTime.UtcNow.ToString()}");

        }

In appSettings.json, serilog is configured as follows:

"Serilog": {
    "MinimumLevel": "Information",
    "WriteTo": [
        {
            "Name": "RollingFile",
            "Args": {
                "pathFormat": ".\\Log\\log-{Date}.txt",
                "retainedFileCountLimit": 7,
                "fileSizeLimitBytes": 5000000,
                "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss} {EventId} [{Level}] [{Properties}] {Message}{NewLine}{Exception}"
            }
        }
    ]
}

the folder "Log" and the log files get created when i run the app locally. But when I publish the webjob, the "Log" folder or the log file is not created in the "app_data" folder of webjob. Can anyone help me figureout how to configure serilog to make it work with webjobs?

Following are the nuget packages used: enter image description here


Solution

  • If you want to use serilog in WebJob , you need to install this package Serilog.Extensions.WebJobs. Then after configuring the serilog, you would be able to use it.

    You must inject the ILogger rather than using the global Log.Logger otherwise the log messages will not be written to the Microsoft Azure WebJobs dashboard.

    About the detailed description about how to configure and use serilog, you could refer to this doc.

    Hope this could help you, if you still have other questions, please let me know.