How to view application logging on Azure - c#

I have an aspnetcore 2.1 app running on azure.
I now want to view logging information to debug an issue that occurs only on Azure.
In the app, an ILogger<> is injected into the class and used:
this._logger.LogInformation("constructor**********************************************");
If I run the app in VS, I can see the output in both the debug output window, as well as the asp.net core web server output window.
I then publish and go on Azure and enable the Log Stream and view it. I do see information appearing in the log stream, but it is just the request information from IIS. I don't see any other log messages.
Is there anything else I need to do to see the logging information on Azure?

You can use Microsoft.Extensions.Logging.AzureAppServices. The package describes itself as:
Logger implementation to support Azure App Services 'Diagnostics logs' and 'Log stream' features.
Once you've installed the package, you'll need to update the logger configuration to use this new provider, which is usually done in Program.cs, like this:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging(loggingBuilder =>
{
loggingBuilder.AddAzureWebAppDiagnostics();
})
...
.UseStartup<Startup>();

You need to configure Application Insights with your application to see the logs generated.
You can read the steps from Enable diagnostics logging for web apps in Azure App Service

You need to install and configure Azure Application Insights for your project.
By configuring the Instrument Key in your application you can send all the kinds of logs from your application to Application Insights.
Install the below Nuget
Microsoft.ApplicationInsights.AspNetCore 2.2.0 NuGet packages
Configure the Application Insights in you asp.net core application
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
// Change to file post adding Application Insights Telemetry:
.UseApplicationInsights()
//
.UseStartup<Startup>()
.Build();
}
See this step by step instruction on how to configure application insights into your asp.net core

Related

Asp.Net Core Web Api and Vue.js client with IIS

I'm trying to create an app with Asp.Net Core (.NET 6.0) as backend and Vue.js as frontend. I've created the .NET project inside Visual Studio 2022, added SPA Extensions and finally my Program.cs file look like this:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Used by single page application requirements.
builder.Services.AddSpaStaticFiles(options =>
{
options.RootPath = "wwwroot";
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.UseStaticFiles();
if (!app.Environment.IsDevelopment())
{
app.UseSpaStaticFiles();
}
app.UseSpa(configuration =>
{
configuration.Options.SourcePath = "wwwroot";
if (app.Environment.IsDevelopment())
{
configuration.UseProxyToSpaDevelopmentServer("http://localhost:5002");
}
});
app.Run();
Deploying code with setttings:
Delete existing files
Configuration Release
Target net6.0 Framework
Target win-x64 Runtime
Produce me a folder containing wwwroot folder with frontend files and many files for my backend application. I put them in an application inside iis server with an application pool configured as:
.NET CLR Version 4.0
Integrated pipeline mode
But my application can only load index.html file but not any .js or .css.
My application has a binding like this:
https://app.domain.it/app-name and she try to open https://app.domain.it/filename.ext file each time, failing, since file is in a https://app.domain.it/app-name/wwwroot/file.ext and he's searching for https://app.domain.it/file.ext
Anyone could help me?
Edit 1: since I've selected Self-contained mode, I don't need the .NET 6 runtime installed on server host, right?
My recommendation is to create two different Application Pools and then deploy the .net core solution as your API (a) and the vue-app as your UI (b) separately.
(a) Standard Deployment with neither a project reference to UI-project nor a configuration of the pipeline regarding Static and default Files (app.UseStaticFiles(); app.UseDefaultFiles(); not necessary )
(b) right click on vue project in VS and "Open in Terminal" -> then npm run build -> then go to dist folder and copy content to physical path for respective application pool on IIS
Solution worked for me. Let me know if it is a solution for you as well and if you have any questions. Hope I could help you.

Service Starts, but The Program does not Run

We've created a new hosted service using .NET Core 3.1 and the WorkerService template.
We want to run this service as a "Windows Service".
If I run the program manually using a Powershell shell, it runs fine with no problems.
So I then added it as a windows service. To do this, I followed these steps:
Added the Microsoft.Extensions.Hosting.WindowsServices package
Added the following to CreateHostBuilder:
public static IHostBuilder CreateHostBuilder(Serilog.ILogger logger, string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService() // <-- added this line
.ConfigureAppConfiguration(configurationBuilder =>
{
configurationBuilder.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true);
})
Published it to a folder (zipped it and copied to server).
Added it as a service:
PS C:\Windows\system32> sc.exe create MyService binpath= "C:\Program Files\Services\MyService.exe"
5. Opened the Services snap-in and started the service.
The snap-in shows that it has a status of "running".
However, the program does not seem to actually do anything. It is not logging anything, including the most basic "Starting up" log message.
I even added a Seq sink on the off-chance that there was an IO problem preventing it from writing to a file. But nothing.
Can anyone identify what I am doing wrong?
As per comment on issue 36065, when a .NET Core 3.1 worker service runs as a windows service "Directory.GetCurrentDirectory() will point to %WINDIR%\system32". Therefore to get the current directory, you could use some reflection and something like:
public static IHostBuilder CreateHostBuilder(Serilog.ILogger logger, string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService() // <-- added this line
.ConfigureAppConfiguration(configurationBuilder =>
{
configurationBuilder.SetBasePath(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))
.AddJsonFile("appsettings.json", optional: true);
});
Worth noting, according to this comment, it's resolved in .NET 5.0

Static file not served through IIS but serving through localhost - ASP.NET Core 3.1 MVC & C#

I am new to programming, and I was able to solve most of the issues all by myself. But this issue goes over my head.
I am using Visual Studio to run my app locally. When I click on "IIS Express" within VS to run the app, the app is opening in a browser with url http://localhost:1234/ and serving static files.
However when I use IIS to host my app, like when I type myapp.com in my browser, I am seeing website in plain text. And no static files (css, js) are being served.
Not sure what is causing the issue. I googled for long time and read lot of posts, but most of them are asking to check if IIS has static role service turned or suggesting to use app.UseStaticFiles() within startup.cs file. Which in my case is done.
program.cs:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
Startup.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseDefaultFiles();
app.UseStaticFiles();
}
Any help is much appreciated.
I didnt know that when we publish it to "files and folder" from Visual studio, any changes that we make in Visual studio will not go through to published folder. Because of this reason "app.UseStaticFiles();" command (that I wrote after publishing) is not passed on to published folder. I had to delete the published folder and republish to make everything work fine.

logging.AddAzureWebAppDiagnostics() does not work in .net core 2.2

I've updated my project from .net core 2.1 to 2.2 and then logging.AddAzureWebAppDiagnostics() in Program.cs no longer works.
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddAzureWebAppDiagnostics();
})
.UseStartup<Startup>()
.Build();
}
'ILoggingBuilder' does not contain a definition for 'AddAzureWebAppDiagnostics' and no accessible extension method 'AddAzureWebAppDiagnostics' accepting a first argument of type 'ILoggingBuilder' could be found (are you missing a using directive or an assembly reference?
Referring to this document,
If targeting .NET Framework or referencing the Microsoft.AspNetCore.App metapackage, add the provider package to the project. Invoke AddAzureWebAppDiagnostics on an ILoggerFactory instance:
So the way might be slightly different from the previous one. How do I fix this issue?
The documentation is a bit tricky but if read carefully it become clear that following steps should be undertaken (for NET Core):
Microsoft.Extensions.Logging.AzureAppServices should be installed
There is NO need to call logging.AddAzureWebAppDiagnostics();
Logging can be configured using following code
// file startup.cs
using Microsoft.Extensions.Logging.AzureAppServices;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
//...
services.Configure<AzureFileLoggerOptions>(Configuration.GetSection("AzureLogging"));
}
}
File appsettings.json should contain
"AzureLogging": {
"FileName" : "azure-diagnostics-",
"FileSizeLimit": 50024,
"RetainedFileCountLimit": 5
}
Logging should be turned on on Azure Portal. After enabling, Azure Portal may ask for installing addon. Message requiring to install addon will appear on logging config page.
Call logger.LogWarning ("message"); in your code to write to log file. If you use LogWarning be sure to set Level to Warning or more detailed (Info or Debug)

Host RestAPI inside IIS

I have a rather simple .NET WebApi application which I'm trying to host inside IIS. Followed all of the instructions from MS site about this.
here is the startup method for it.
public static void Main(string[] args)
{
var host = WebHost.CreateDefaultBuilder(args)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
I configured the Application pool to not use any managed code but I'm getting still this error in logs
Application startup exception: System.InvalidOperationException: Application is running inside IIS process but is not configured to use IIS server.
at Microsoft.AspNetCore.Server.IIS.Core.IISServerSetupFilter.<>c__DisplayClass2_0.<Configure>b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.Internal.AutoRequestServicesStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
crit: Microsoft.AspNetCore.Hosting.Internal.WebHost[6]
I'm out of any ideas what can be wrong.
Any suggestions?
Using .NET Core 2.2
For InProcess, it uses IISHttpServer.
For your code, you are configuring UseKestrel() which uses out-of-process.
For solution, remove the .UseKestrel() line.
public static void Main(string[] args)
{
var host = WebHost.CreateDefaultBuilder(args)
//.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
For more details, refer ASP.NET Core Module.
I want to use UseKestrel().
When I create .net core 2.0 or 2.1 project. I can use UseKestrel()
But If I create .net core 2.2 project I couldn't use UseKestrel()
I solved this problem like that
Create new .net core 2.0 or 2.1 project. Then, you can upgrade .net core project to 2.2. It will work.
But it is not effective solution.

Categories