What to See Trace Logs for Azure App Service? - azure

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:

Related

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>();

Passing Configuration and Initializing a Client in Azure Functions w/ Dependency Injection

I'm creating a new Azure Functions with a Queue trigger. A key requirement is for me to use my existing class libraries that I created in my ASP.NET Core app so that I can access my Repository methods. I also have my own clients that handle communication with some third party services.
I need help with creating instances of my clients and passing configuration to them which is IConfiguration.
Here's what my Startup.cs looks like in my Azure Functions project:
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MyApp.Infrastructure.Clients;
using MyApp.Infrastructure.Interface;
using MyApp.Infrastructure.Repositories;
[assembly: FunctionsStartup(typeof(MyTestFunction.Startup))]
namespace MyTestFunction
{
public class Startup : FunctionsStartup
{
public IConfiguration Configuration { get; }
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddSingleton(new MyApp.Infrastructure.Clients.MyClient123(Configuration));
builder.Services.AddTransient<ICommunicationsRepository, CommunicationsRepository>();
}
}
}
In my ASP.NET Core app's Startup.cs, I do have a constructor that handles the configuration -- see below -- but not sure how to handle this Azure Functions.
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
Looks like this is not a recommended approach:
https://github.com/Azure/azure-functions-host/issues/4464#issuecomment-513017446
I've decided to update my class libraries in my ASP.NET Core app so that I use Azure KeyVault in both my API and Azure Functions apps.

Azure APP Service Application Log not working

I have an Azure App for a .net core API, which in turn has a Sub Application (Virtual Directory). I have enabled Application log in the Diagnostic setting in the Azure Portal. I had done this for a another service and worked fine. When I have the services with multiple Virtual Directory setup it fails. Do we need any extra code in the Configure section if we have this scenario?
I can't reproduce the issue you mentioned. It works well to get Application logs. I also created a Virtual Directory in App Service. (refer to this article). And we needn’t to add extra code. You could follow my steps.
In Azure portal>APP Service>Application settings(create virtual directory ‘janley’):
Code in application: (Add the trace info).
public ActionResult Index()
{
Trace.TraceInformation("my trace info Home/Index");
return View();
}
public ActionResult About()
{
Trace.TraceInformation("my trace info Home/About");
return View();
}
public ActionResult Contact()
{
Trace.TraceInformation("my trace info Home/Contact");
return View();
}
You could see the logs in KuDu like this:
Besides, for more details about how to trace and view the application logs, you could read this article.
Changing the app from .net core to .net framework worked for me!

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