ASP.NET web application in Azure - How to log errors? - c#

I have a web application deployed to azure but I don't know how to log errors.
For testing purposes I have this ForceError method:
public string ForceError()
{
throw new Exception("just a test exception");
return "ok";
}
Which causes and error like this:
On Azure I enabled all Diagnostic logs like this:
But the error I forced does not appear in selected storage container.
Do you know what should I do to start logging all the errors from the application?

I am afraid just throwing an exception doesn't work in Azure Web application logging.
ASP.NET applications can use the System.Diagnostics.Trace class to log information to the application diagnostics log. The four methods in example below correspond with the diagnostic log levels:
Trace.TraceError("Message"); // Write an error message
Trace.TraceWarning("Message"); // Write a warning message
Trace.TraceInformation("Message"); // Write an information message
Trace.WriteLine("Message"); // Write a verbose message
Besides the basic information for logged events, blob storage log additional information such as the instance ID, thread ID, and a more granular timestamp (tick format) in CSV.
A great article here about logging tips and tools.
See also the Reference to the official Azure Web Apps Logging Document.

On Azure Websites, best way to log would be Application Insights, you can use free version to get insights about crashes/speed/performance.
However, Application Insights is little slower if you enable everything. But if you customize it and enable only error logging, it would push all logs to your azure application insights account and you will be able to monitor/analyze it very nicely.
For more details:
https://azure.microsoft.com/en-in/documentation/articles/app-insights-api-custom-events-metrics/
Instead of automatically configuring Application Insights, I would suggest, take an empty project, setup application insights. Notice all added config files and nuget packages. There is some insight config file, except application key/signature, you can turn off everything.
Only when you want to track an exception manually, you can create TelemetryClient and call TrackException method. You can pass more details if you need.

Related

ASP.NET Core 2.2 App Service hosted on Azure returning 500 without an exception being thrown

I have developed an App Service backend hosted on Azure using ASP.NET Core 2.2.
From time to time I'm getting a 500 status but I'm not able to find out where is that 500 being generated.
I'm using application Insights and I see on Failed Requests that sometimes there are some calls to my App Service which are returning 500.
If I reproduce that same call with same values with Postman I'm not getting any 500. There are also some End Client Apps making requests to this backend. I believe it's happening to them but why I can't reproduce the same result if I'm performing the same request with same values.
I know that 500 implies "Internal Server Error" and that it is related to the Application code but I've even configured my App Service to use a Global Error handling but I never get that 500 when I'm executing the same request that I see on Application Insights.
I have set on my Configure on StartUpp class the global error handling (just to show you that I have also enabled that)
app.UseExceptionHandler(config => ExceptionHandlingSettings.ConfigureGlobalExcpetionHandling(config));
I would like to know where or how to get more information in order to find out the code generating the error/exception because I guess there is some bug in my code which throws an unhandled exception.
Here are couple of steps which you can do to understand the root cause:
1- Change stdoutLogEnabled="false" to true and then check the logs at stdoutLogFile=".\logs\stdout". The error(s) there might tell you something.
The ASP.NET Core Module stdout log often records useful error messages not found in the Application Event Log. To enable and view stdout logs:
Navigate to the Diagnose and solve problems blade in the Azure portal.
Under SELECT PROBLEM CATEGORY, select the Web App Down button.
Under Suggested Solutions > Enable Stdout Log Redirection, select the button to Open Kudu Console to edit Web.Config.
In the Kudu Diagnostic Console, open the folders to the path site > wwwroot. Scroll down to reveal the web.config file at the bottom of the list.
Click the pencil icon next to the web.config file.
Set stdoutLogEnabled to true and change the stdoutLogFile path to: \?\%home%\LogFiles\stdout.
Select Save to save the updated web.config file.
Make a request to the app.
Return to the Azure portal. Select the Advanced Tools blade in the DEVELOPMENT TOOLS area. Select the Go→ button. The Kudu console opens in a new browser tab or window.
Using the navigation bar at the top of the page, open Debug console and select CMD.
Select the LogFiles folder.
Inspect the Modified column and select the pencil icon to edit the stdout log with the latest modification date.
When the log file opens, the error is displayed.
Please make sure to remove the logging once the inspection is completed.
2 - Use Middleware for handling erroneous request like app.UseDeveloperExceptionPage();
3- You can add application Insight in your app and try to put Info logging to understand what part of your code is causing the failure.
For additional reference, please check below doc:
https://learn.microsoft.com/en-us/aspnet/core/test/troubleshoot-azure-iis?view=aspnetcore-3.0
https://learn.microsoft.com/en-us/azure/azure-monitor/app/asp-net-exceptions
Hope it helps.

Azure - Create Function App - At least one resource deployment operation failed

I get this error message while deploying on Azure. Any ideas what this could be?
Step 1. Create a function app.
Step 2. Unable to progress (from the Create Function App) in Azure. I get -
Deployment to resource group 'FunctionApp' failed.
Additional details from the underlying API that might be helpful: At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/arm-debug for usage details.
Step 3. I've checked various places. https://aka.ms/arm-debug - this error message is not listed.
How do I fix this? I've not started - I've created a Function App and it's not creating the function app...
If you want to manage Azure resource, you need have your subscription Owner role. More information please refer to this link.
You could check your user role on Portal.

Asp.net Core azure web app logging

I have an asp.net core deployed to azure, and I am trying to configure logging to my application using the Microsoft.Extentions.Logging interfaces.
currently my app is writing the logs to Log Files folder in the web app storage.
This seems like the right place to log my changes. However, I want to view these logs in a normal interface - downloading a text file everytime, is kinda annoying.
I have looked into application insights, and azure diagnostic logs, but none of them suggest how to work with it using the ILogger interface.
First of all you have to configure logs in your application on Azure:
There is also an option to look at the application console output:
You can also configure Storage on Azure and save logs there (you can configure that in Diagnostic logs section).
If you want to use the Log Stream in an easy way in Azure, you can do this:
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
var sourceSwitch = new SourceSwitch("DefaultSourceSwitch");
sourceSwitch.Level = SourceLevels.Information;
loggerFactory.AddTraceSource(sourceSwitch, new TextWriterTraceListener(writer: Console.Out));
}
TraceListener will ensure that your logs will go to the standard trace output.
You also need to enable stdoutLogEnabled in the web.config (set it to true).
<aspNetCore stdoutLogEnabled="true" />
If you do these two things, you will see all your logs and system logs as well in the LogStream. You can control the level yourself.
P.S. This will work only on Full .NET Framework
P.P.S. I think if you turn on logging to blob under Diagnostic logs setting in Azure, you can have it saved to blob. So everything will happen without you writing any code and manually writing to some location.

Application Insights from a non web app returns 404

I' writing an Azure webJob which is ultimately a console app before it is deployed. I'm trying to add Application Insights to this so I can have Telemetry Results. However since this is not a Web app of any sort Telemetry isnt a recognised part of the project.
When I atempt to add telemetry manually and set any details of the TelemetryConfiguration.Active frame work I am presented with the following error:
TelemetryConfiguration.Active.InstrumentationKey = settingsKey;
Exception:
'Microsoft.WindowsAzure.Storage.StorageException' in Microsoft.WindowsAzure.Storage.dll
Additional information: The remote server returned an error: (404) Not Found.
However if I run an ODATA mvc app in the solution all telemetry works fine 'out of the box'.
Any direction of how to set up Insights via the SDK would be very usful as I'm struggling to find and good documentaion for non web app examples.
The host code its self is based on the standard examples of web jobs:
JobHost host = new JobHost();
host.Start();
var task = host.CallAsync(typeof(Functions).GetMethod("MessageHandlingLoop"));
task.Wait();
host.Stop();
Telemetry Code then in the MessageHandlingLoop()
Thanks in advance!
Stack trace that you mentioned is not from ApplicationInsights. SDK does not use WindowsAzure.Storage.
As far as examples. Here is the documentation: https://azure.microsoft.com/en-gb/documentation/articles/app-insights-windows-desktop/
Also you can take a look at how worker role is instrumented (it is closer to console than web examples): https://github.com/Microsoft/ApplicationInsights-Home/tree/master/Samples/AzureEmailService

IdentityServer3 - Exception handling

Is there a way to handle exceptions ourselves. We have custom user service code inside our identityserver project and would like to know without diving through logs when errors occur.
We have a centralized error logger for all our apps. I'd imagine something similar needed if using 3rd party exception lib (airbrake etc).
Is there something possible at the moment or is this ticket solving my problem
https://github.com/IdentityServer/IdentityServer3/issues/2012
If you care about the error logging - the event service will log all unhandled exceptions.
The issue you mentioned would allow you to have more control over direct error handling (e.g. setting a custom http response) - but that's backlog right now.

Categories