View application logs in azure - azure

I have asp.net core 3.1 application. These are my settings for logging:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.AddAzureWebAppDiagnostics();
logging.AddConsole();
logging.AddDebug();
})
.UseStartup<Startup>();
And in code I use this _logger.LogInformation(). I can see logs in console when I run the app locally, but the question is how I can see it on my app service on Azure Portal?

Related

Azure App service with user-assigned managed identity cannot communicate with Azure App Configuration service

I am trying to use Azure App Configuration service from Azure Web App (Linux) using user-assigned managed identity but application crashes at start-up. My web application is built using AspNet Core 3.1.
This is the code I used in Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureAppConfiguration(config =>
{
var settings = config.Build();
var aacEndpoint = settings.GetSection("AzureAppConfig:Endpoint").Value;
config.AddAzureAppConfiguration(acfg =>
{
acfg.Connect(new Uri(aacEndpoint), new ManagedIdentityCredential("<ClientId of MI>"));
var projectkeysFilter = "VSSP.Web/*";
var projectTrimKeyPrefix = "VSSP.Web/";
acfg.Select(projectkeysFilter, LabelFilter.Null);
acfg.TrimKeyPrefix(projectTrimKeyPrefix);
});
})
.UseStartup<Startup>();
});
I have these configuration settings on Azure App Service:
AZURE_CLIENT_ID: <<xxClientId of MI>>
ASPNETCORE_ENVIRONMENT: DEV
User assigned managed identity is provisioned in azure web app and granted App Configuration Data Reader role in App Configuration service.
Endpoint configured in appsettings.json
"AzureAppConfig": {
"Endpoint": "https://app-zcfg-dev.azconfig.io"
}

Application Insight Logging in minimal API .netcore

I am working on minimal APIs and not quite sure how to add Azure App Insights logging.
Could someone please point me to any documentation?
In the older version of .netcore API we could do it in the program file by calling CreateWebHostBuilder and passing the App Insight values. But I can see we have WebApplicationBuilder in the minimal API, so not sure how to configure logging to Azure.
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(logging=> {
logging.AddApplicationInsights("your_insturmentation_key");
logging.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Trace); #you can set the logLevel here
});
}
Thanks in advance.
You can add Application Insight by adding the following line in your Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
// ....
services.AddApplicationInsightsTelemetry();
}
Further reading: Application Insights for ASP.NET Core applications

Azure App Service Log Stream in .NET Core 3.0 - Don't see any logs

I'm developing a .NET Core 3.0 web application and publishing it as an Azure App Service.
In one of the controller methods, I do this:
System.Diagnostics.Trace.TraceError("If you're seeing this, something wonderful happened");
Then I go in the Azure App Service - App Service Logs and enable "Application Logging". Next, I go in "Log stream", where I'm supposed to be able to see live debug logging, but I don't see anything.
Please advice!
...
Edited: I changed my Program.cs file a bit but it still doesn't work. Here's my Program.cs file:
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
})
.UseStartup<Startup>();
}
You need to change your logging to something like explained here. AFAIK System.Diagnostics.Trace is not really supported in ASP.NET Core.
This seemed to work:
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
//logging.ClearProviders();
//logging.AddConsole();
logging.AddApplicationInsights("Application insights Instrumentation Key");
})
.UseStartup<Startup>();

What to See Trace Logs for Azure App Service?

Using .NET Core 2 in Azure App Service. Don't see my logs. In the actual application, the logging code looks like this:
using System.Diagnostics;
...
Trace.WriteLine("Logging works");
I expected to see the Trace logs in the Log Stream, but I don't. I do see general API logs. What am I doing wrong? My config below:
I had the same issue for .NET core azure web app: Trace.WriteLine method does not work(not write message to Application logs) for .NET core, but work for .NET framework , and I find the issue about that.
As a workaround for .NET core web application, I suggest you can use ILogger, which can write message to Application Logs.
In Startup.cs -> Configure method, re-write Configure method like below:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//your other code
//add the following 2 lines of code.
loggerFactory.AddConsole();
loggerFactory.AddDebug();
app.UseStaticFiles();
//your other code
}
Then in HomeController.cs, add the following code:
public class HomeController : Controller
{
private readonly ILogger _logger;
public HomeController(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<HomeController>();
}
public IActionResult Index()
{
_logger.LogInformation("this is a information from ILogger...");
return View();
}
//other code
}
After publish to azure, and configure the Application Logging -> run the azure web app -> you can see the message is displayed in Application Logs:

ASP.NET 5 - Azure AD Authentication - Redirect Loop when run with DNX web command - secrets.json

I created a new ASP.NET 5 MVC 6 app (work and school accounts authentication) and I am getting a redirect loop when going to any authenticated page such as http://localhost:5000/Account/Signin. This happens if I publish the app and run web.cmd (DNX) in the command prompt.
What I do know is if I set the hosting environment to Development, the issue is resolved on my dev machine but copying the published app with the same "--ASPNET_ENV Development" setting to any other machine gets the redirect issue.
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel --ASPNET_ENV Development"
},
I can reproduce this consistently. Turning off Authentication also resolves the issue but not helpful for me. Publishing to Azure also works.
Firstly, I would like to know why setting the Hosting Environment to development fixes the redirect issue on my dev machine and secondly, I would like to know why it does not work on any other machine. Hosing in IIS on another machine also gives the redirect loop issue but it works fine in IIS express on my dev machine.
This is easy to reproduce. In VS 2015, create a new ASP.NET 5 web app, choose (work and school accounts authentication) and publish choosing File System. Go to the publish directory and run web.cmd. If it shows Hosting Environment Production, you will likely get the issue. Changing Environment to Development will fix the issue but copying the the published app to another machine will have the same redirect issue even if with the Hosting Environment set to Development.
UPDATE:
I now know that the settings for Azure AD authentication e.g. Authentication:AzureAd:AADInstance are in the secrets.json file %APPDATA%\microsoft\UserSecrets\\secrets.json . I can read them with the command line user-secret list. This secrets.json file is only loaded if the environment is set to Development which answers my first question:
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
The secrets.json file is also not part of the deployment package so that answers my second question of why it does not work when I copy the package to another machine.
I know need to work out how secrets.json is meant to be used in a production environment.
Startup.cs is here as requested:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Authentication.Cookies;
using Microsoft.AspNet.Authentication.OpenIdConnect;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace TestAzureAD
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseCookieAuthentication(options =>
{
options.AutomaticAuthenticate = true;
});
app.UseOpenIdConnectAuthentication(options =>
{
options.AutomaticChallenge = true;
options.ClientId = Configuration["Authentication:AzureAd:ClientId"];
options.Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"];
options.PostLogoutRedirectUri = Configuration["Authentication:AzureAd:PostLogoutRedirectUri"];
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
The settings for Azure AD authentication e.g. Authentication:AzureAd:AADInstance are in the secrets.json file %APPDATA%\microsoft\UserSecrets\secrets.json. This would also apply for other authentication types.
The secrets API can be used to manage the secrets. https://github.com/aspnet/Home/wiki/DNX-Secret-Configuration
dnu commands install Microsoft.Extensions.SecretManager
user-secret list
In development on the dev machine, the secrets.json file can be used but on other machines, which wont have the secrets.json file, the settings need to be read from appsettings.json and appsettings.[environmentname].json. Copying the secrets.json settings to appsettings.json resolves the issue as the azure authenication now knows where to go and no longer redirects to itself in a loop.
The startup code shows that the settings are read from appsettings.json and appsettings.[environmentname].json and also from secrets.json in Development environment.
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}

Resources