Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ILogger not logging to console after moving to Azure Functions OOB DI #1256

Closed
srivathsanvlb opened this issue Jun 21, 2019 · 10 comments
Closed
Assignees

Comments

@srivathsanvlb
Copy link

srivathsanvlb commented Jun 21, 2019

Hi Azure Functions Team,

I followed the steps in https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection and was able to successfully implement Azure Functions OOB DI instead of using "GetService" to instantiate classes.

But after moving to the OOB DI, ILogger is not logging any information to the console when debugging locally (Still yet to deploy and testing using App. Insights).

Here is the snippet of the code I am using.

Startup.cs (OOB DI used, This file resides in an Azure Function Project)

[assembly: FunctionsStartup(typeof(MyNameSpace.Startup))]
namespace MyNameSpace
{
    public class Startup : FunctionsStartup
    {
        private static IConfiguration _configuration;
        private static ILogger _logger;
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var services = builder.Services;
            //_logger = new LoggerFactory().AddConsole().CreateLogger(nameof(FunctionApp));
            //services.AddSingleton(_logger);
            _configuration = BuildConfiguration();
            services.AddSingleton(_configuration);
            services.AddTransient(typeof(IEntityRepository<>), typeof(EntityRepository<>));
            services.AddTransient<IUnitOfWork, UnitOfWork>();
            services.AddTransient<IMyService, MyService>();
                 }
            }
    }

Azure Function (.NET Core 2.1 project. DI works fine. Able to see the logged messages)

public class MyAzureFunction
  {
      private readonly IMyService __myService;
      public TenantInfoSyncService(IMyService myService)
      {
          _myService = myService;
      }
      [FunctionName("MyAzureFunction")]
      public async Task Run([TimerTrigger("%ValidTimerCron%")]TimerInfo myTimer, ILogger logger)
      {
          logger.LogInformation($"Execution started at: {DateTime.UtcNow}");
          try
          {
             await  _myService.MyFunction().ConfigureAwait(false);
          }
          catch (Exception ex)
          {
              logger.LogError(ex.ToString());
              throw;
          }
          logger.LogInformation($"Execution ended at: {DateTime.UtcNow}");
     }       
  }


MyService.cs (This resides in a separate .NET Core 2.1 project. Class Library project, which is referenced to the Azure Function Project)
But Logged messages not appearing in the console

public class MyService : IMyService
    {
        private readonly ILogger _logger;
        public MyService (ILogger logger)
        {
            _logger = logger;
        }
        public async Task MyFunction ()
        {
            _logger.LogInformation($"Information");
                 }
}

In the Startup.cs file, you would have noticed that I have two lines of code commented, ie

            //_logger = new LoggerFactory().AddConsole().CreateLogger(nameof(FunctionApp));
            //services.AddSingleton(_logger);

If I uncomment them, then I am able to see the logs from MyService.cs, but I think it should be supported DIed ILogger ie the above two lines shouldn't be required, right?, Should I use LoggerFactory separately?

I also tried Injecting ILogger<MyService> and also ILoggerFactory loggerFactory along with _logger = loggerFactory.AddConsole().CreateLogger<MyService>(); in the constructor of MyService.cs, but didn't log anything. The DI was successful for the logger, but it didn't log anything screen.

Note: Both the Azure function and the Services project have Microsoft.Extensions.Logging 2.2.0 installed.

@ColbyTresness
Copy link

@jeffhollan

@PramodValavala-MSFT
Copy link

I believe you are hitting this issue where the functions run time aggressively filters logs.

Could you try adding something like this in your host.json?

{
  "version": "2.0",
  "logging": {
    "logLevel": {
      "<namespace>.MyService": "Information"
    }
  }
}

To enable them for all classes in your nuget, you could do

{
  "version": "2.0",
  "logging": {
    "logLevel": {
      "<namespace>": "Information"
    }
  }
}

@jeffhollan
Copy link
Contributor

Thank you for jumping in @PramodValavala-MSFT - yes this is likely what it is. @brettsam we had a separate item tracking this before I believe? Is that still open?

@srivathsanvlb
Copy link
Author

I will try and reply back. Kindly keep the thread open for some time

@ggirard07
Copy link

Had the same issue and it indeed fixed it for me!
Looking forward for the proper issue ref tracking this.

@srivathsanvlb
Copy link
Author

I still didn't have time to check this as I was locked up in other stuff. If needed, kindly close the ticket. I will check back later and reach out if I face further trouble. Thanks for the support Microsoft.

@srivathsanvlb
Copy link
Author

Its working fine. Thanks one more. You can close the ticket if required.

dracan added a commit to dracan/AzureFunctionsLoggingIssue that referenced this issue Apr 4, 2020
@dracan
Copy link

dracan commented Apr 4, 2020

I'm having this issue, and the above-mentioned hosts.json fix doesn't resolve it for me. I've created a repro-case here:

https://github.com/dracan/AzureFunctionsLoggingIssue

Also, posted on StackOverflow yesterday before I found this current GitHub issue:
https://stackoverflow.com/questions/61019859/azure-functions-injected-iloggert-logs-arent-appearing

@dracan
Copy link

dracan commented Apr 5, 2020

Actually, I worked out that it's just the log stream where it's not working...

image

@brettsam
Copy link
Member

brettsam commented Apr 6, 2020

This is another subtlety about how that console/debug log works in the portal. It only displays log messages if it knows they come from this function -- which means they match the category Function.{FunctionName}.User. The ILogger we pass in uses this category automatically but anything you log with an external logger will not use this. We do this so that you don't get flooded with background messages in this view -- and unfortunately it filters out your own custom logger as well.

I've got an issue tracking this with one potential workaround: Azure/azure-functions-host#4689 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants