skip to Main Content

I am trying to get logging working for the DefaultAzureCredential in Visual Studio. I setup up the logging but when I get a DefaultAzureCredential token no logging in outputed in Visual Studio console.

Here is my program.cs

private static void Main(string[] args)
 {
     using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger();
     var builder = WebApplication.CreateBuilder(args);
     builder.Logging.AddAzureWebAppDiagnostics();
     builder.Logging.AddConsole();

     // Add services to the container.
     builder.Services.AddControllersWithViews();

     var app = builder.Build();

     // Configure the HTTP request pipeline.
     if (!app.Environment.IsDevelopment())
     {
         app.UseExceptionHandler("/Home/Error");
         // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
         app.UseHsts();
     }


     app.UseHttpsRedirection();
     app.UseStaticFiles();

     app.UseRouting();

     app.UseAuthorization();

     app.MapControllerRoute(
         name: "default",
         pattern: "{controller=Home}/{action=Index}/{id?}");

     app.Run();
 }

Here is how I am getting the token

     DefaultAzureCredentialOptions options = new DefaultAzureCredentialOptions
  {
      Diagnostics =
      {
          LoggedHeaderNames = { "x-ms-request-id" },
          LoggedQueryParameters = { "api-version" },
          IsLoggingContentEnabled = true,
          IsLoggingEnabled = true,
          IsAccountIdentifierLoggingEnabled = true
      },
      ExcludeManagedIdentityCredential = true
  };

  var credential = new DefaultAzureCredential(options); 
  
  AccessToken token = credential.GetToken(new Azure.Core.TokenRequestContext(new[] { "https://database.windows.net/.default" }));

Any suggestions on why this isn’t working?

2

Answers


  1. I setup up the logging but when I get a DefaultAzureCredential token no logging in outputed in Visual Studio console.

    Firstly, check you have added the necessary NuGet package for logging. Use the Microsoft.Extensions.Logging.Console package for logging to the console.

    • Then, in the Program.cs file, configure logging to include Azure.Identity logs. Set the log level for Azure.Identity namespace to Information or Debug

    Code:

    using Microsoft.Extensions.Logging;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
    
    // Configure logging
    builder.Logging.AddConsole(); // Add logging to the console
    
    // Set logging level for Azure.Identity namespace
    builder.Logging.SetMinimumLevel(LogLevel.Debug); // or LogLevel.Information
    
    // Configure Application Insights telemetry.
    builder.Services.AddApplicationInsightsTelemetry(builder.Configuration["ApplicationInsights:InstrumentationKey"]);
    
    builder.Services.AddControllersWithViews(options =>
    {
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
        options.Filters.Add(new AuthorizeFilter(policy));
    });
    builder.Services.AddRazorPages()
        .AddMicrosoftIdentityUI();
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthentication();
    app.UseAuthorization();
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
    });
    
    app.Run();
    

    Transaction search:

    enter image description here

    Authentication log:
    enter image description here

    Login or Signup to reply.
  2. The Azure SDK packages emit logs to ETW. You’ve hooked up the AzureEventSourceListener, which will capture them, but you’re not writing those captured logs anywhere. For example, to emit them to the console, you’d need to create a console logger:

    using AzureEventSourceListener listener = 
        AzureEventSourceListener.CreateConsoleLogger();
    

    To integrate with ILogger and the ASP.NET logging infrastructure, the easiest way is to use the AzureEventSourceLogForwarder from the Microsoft.Extensions.Azure package, which implicitly starts a listener and writes the captured logs to ILogger for you.
    That would look something like the following, in which AddAzureClientsCore creates and starts the forwarder on your behalf.

    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddAzureClientsCore(true);
    

    More discussion and examples can be found in Logging with the Azure SDK for .NET.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search