3

I have a .Net Core 2.2 web app that uses the out-of-the-box ILogger to log information about the application. When debugging locally the information is logged as expected in the debug console. However, when the application is deployed to Azure as an App Service, the log entries are duplicated when viewed in the Azure LogStream.

On the Azure portal, Asp.Net Core Logging Extensions (v 2.2.0) is installed

This is the code(c#) where the logging is done in my web app

public class MyService : BackgroundService
{
    private readonly ILogger<MyService> _logger;

    public MyService(ILogger<MyService> logger)
    {
        _logger = logger;
    }

    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.Log(LogLevel.Information, "The service task is starting.");
        var count = 0;
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.Log(LogLevel.Information, $"The service task is doing background work. count is: {count}. Hashcode is: {_logger.GetHashCode()} on thread: {Thread.CurrentThread.ManagedThreadId}");

            // some background work

            count++;

            Task.Delay(60000, stoppingToken).GetAwaiter().GetResult();
        }

        _logger.Log(LogLevel.Information, "The service task is terminating.");

        return (Task.FromResult<object>(null));
    }
}

The logging is configured like this in program.cs file

    public static IWebHost BuildWebHost(string[] args)
    {
        return WebHost.CreateDefaultBuilder(args)
            .CaptureStartupErrors(true)
            .UseSetting(WebHostDefaults.DetailedErrorsKey, "true")
            .ConfigureLogging((logging) =>
                {
                    logging.AddAzureWebAppDiagnostics();
                })
            .UseStartup<Startup>()
            .Build();
    }

This is the backgroundservice from the nuget package: microsoft.extensions.hosting.abstractions\2.1.0

namespace Microsoft.Extensions.Hosting
{
    public abstract class BackgroundService : IHostedService, IDisposable
    {
        protected BackgroundService();
        public virtual void Dispose();
        // more methods
    }
}

Adding MyService to the Services collection

public class Startup
{
    private readonly ILoggerFactory _loggerFactory;
    private readonly ILogger _logger;
    private readonly ILogger _startupLogger;

    public Startup(IConfiguration configuration, ILoggerFactory loggerFactory)
    {
        Configuration = configuration;
        _loggerFactory = loggerFactory;
        _logger = _loggerFactory.CreateLogger("GlobalException");
        _startupLogger = _loggerFactory.CreateLogger(typeof(Startup));
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
       _startupLogger.LogInformation($"Adding common services");

       services.AddCommonServices(Configuration, _logger);
    }
}

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddCommonServices(this IServiceCollection services, IConfiguration configuration, ILogger logger)
    {
        services.AddMvc(options =>
        {
            options.Filters.Add(new ExceptionFilter(logger));
        })

        services.AddSingleton<IHostedService, MyService>();

        return services;
    }
}

This is the exception filter

public class ExceptionFilter : ExceptionFilterAttribute
{
    private readonly ILogger _logger;
    public ExceptionFilter(ILogger logger)
    {
        _logger = logger;
    }
    public override void OnException(ExceptionContext context)
    {
        _logger.LogInformation("There was an error processing your request.");

        base.OnException(context);
    }
}

In the Azure LogStream I was expecting a single line of output per task cycle like this: 2019-06-27 08:36:25.488 +00:00 [Information] MyService: Deferred background service task is doing background work. count is: 3. Hashcode is: 61705107 on thread: 1

But I am getting three duplicates like this:

2019-06-27 08:36:25.488 +00:00 [Information] MyService: The service task is doing background work. count is: 3. Hashcode is: 61705107 on thread: 1

2019-06-27 08:36:25.482 +00:00 [Information] MyService: The service task is doing background work. count is: 3. Hashcode is: 61705107 on thread: 1

2019-06-27 08:36:25.224 +00:00 [Information] MyService: The service task is doing background work. count is: 3. Hashcode is: 61705107 on thread: 1

Benajax
  • 31
  • 6
  • The log message in `MyService` doesn't match what you're getting in Azure log stream. I'm guessing that log message is coming from `BackgroundService`? If so, can provide the code for that? – Ryan Hill Jul 01 '19 at 15:36
  • Hi Ryan, the messages are coming from the background service. The real messages from the code above are: 2019-06-27 08:36:25.488 +00:00 [Information] MyService: The service task is doing background work. count is: count is: 3. Hashcode is: 61705107 on thread: 1 2019-06-27 08:36:25.482 +00:00 [Information] MyService: The service task is doing background work. count is: count is: 3. Hashcode is: 61705107 on thread: 1 2019-06-27 08:36:25.224 +00:00 [Information] MyService: The service task is doing background work. count is: count is: 3. Hashcode is: 61705107 on thread: 1 – Benajax Jul 03 '19 at 07:59
  • Can you include the code snippets from `BackgroundService` that's doing the logging? – Ryan Hill Jul 08 '19 at 14:30
  • Added the code snippets from the BackgroundService in the problem description above.The BackgroundService is functionality in a nuget package. – Benajax Jul 09 '19 at 08:04
  • How are you adding `MyService` to the service collection? – Ryan Hill Jul 09 '19 at 19:35
  • Hi Ryan, I have added a section of my startup file and the Services extension method to show my MyService is added ( as a singleton ) to the collection. You can checkout the line services.AddSingleton(); from above. Thanks. – Benajax Jul 10 '19 at 14:11
  • Hi Benajax, everything looks good there. One thing I did notice is the timestamps on the log entries you included are different. Where does `MyService` get referenced? – Ryan Hill Jul 10 '19 at 19:08
  • Hi Ryan, the only reference to MyService is in the set up as a singleton in the ServiceCollection extension above. Logstream is duplicating the logs with different timestamps. When debugging locally everything seems to work fine with no duplicate log entries. I am wondering whether the extensions responsible for logging when in azure cloud have an issue. Not sure what is happening. – Benajax Jul 13 '19 at 11:49
  • Sorry for the delay. I'll see what I kind out and let you know. – Ryan Hill Jul 17 '19 at 20:14
  • I created a basic web app (without the `ExceptionFilter`), enabled app & web server file system log stream via portal. When I'm connected to the log stream inside the portal, I'm not seeing the duplicate log entries and the count is incrementing as expected. Can you include your `ExceptionFilter` class? – Ryan Hill Jul 18 '19 at 02:23
  • Hi Ryan -, I have updated the post with the exception filter. Thanks for your continuous assistance. – Benajax Jul 22 '19 at 09:13
  • Hi Benajax, sorry for the late reply. I don't see anything in your `ExceptionFilter` class that would cause duplicate log entries. How is your App Service logs blade configured? – Ryan Hill Jul 30 '19 at 14:06

0 Answers0