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
Firstly, check you have added the necessary NuGet package for logging. Use the
Microsoft.Extensions.Logging.Console
package for logging to the console.Program.cs
file, configure logging to include Azure.Identity logs. Set the log level forAzure.Identity
namespace toInformation
orDebug
Code:
Transaction search:
Authentication log:
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:To integrate with
ILogger
and the ASP.NET logging infrastructure, the easiest way is to use theAzureEventSourceLogForwarder
from theMicrosoft.Extensions.Azure
package, which implicitly starts a listener and writes the captured logs toILogger
for you.That would look something like the following, in which AddAzureClientsCore creates and starts the forwarder on your behalf.
More discussion and examples can be found in Logging with the Azure SDK for .NET.