Azure functions V3 logging exceptions in startup file - c#

Currently we are preapring a set of azure functions to trigger a blob storage. The function app V3 should do some kind of checks on startup. So I added the Startup.cs file in the VS solution. The problem what I'm having is that sometimes exceptions happen while performing these checks in the startup file. But I never find these exceptions in azure portal (application insights/exceptions). I tried many ways to implement logging there, but unfortunately the app keeps saying Host is not running without any logging in these logs:
I'm not talking about the logs of a specific function, I mean here the logs of the function app on startup.
This is the code where it throws the exception in startup.cs:
try
{
// async method CheckSomeBlobsFiles
CheckSomeBlobsFiles(connectionString,
blobContainerName, blobDirectoryName).GetAwaiter().GetResult();
}
catch (Exception e)
{
throw new Exception($"Error while checking database schemas: {e.Message}");
}

After some research, for the exceptions from Startup.cs, you can find it in azure portal -> Diagnose and solve problems blade.
The steps as beow:
1.Nav to azure portal -> your function app -> on the left side, click on Diagnose and solve problems -> then input function app down in the search box -> then click on the Function App Down or Reporting Errors. The screenshot as below:
2.In the new page of Function App Down or Reporting Errors, expand
Function Executions and Errors -> then expand Detected host offline in your function app. Then you can see the exceptions in the startup.cs are logged there(if it's not there, please specify a proper time range on this page). The screenshot as below:

Can you try with HttpRequestException as shown the following code?
catch (HttpRequestException ex)
{
throw new Exception($"Error while checking database schemas: {e.Message}");
}

Related

Azure database randomly stopped working after publishing UWP app

Ive made an app that uses Azure easy tables and connects using the following:
try
{
await ctv.combatDrillsTable.Initialization;
await ctv.combatDrillsTable.InitLocalStoreAsync();
await AddItemsAsync();
}
catch
{
var addError = new MessageDialog("Connection to your drills could not be established at this time, returning to " +
"main menu");
await addError.ShowAsync();
if (MainPage.MyFrame.CanGoBack)
{
MainPage.MyFrame.GoBack();
}
}
This was doing a GET request fine the last few weeks but now the connection error throws, I checked my Azure portal and the drills are there, the server overview shows the following:
HTTP Error stats
Im not really sure whats wrong and why Azure has just decided to stop working. I get the same results on bith my local machince is Visual Studio 2017 and the app installed on windows from the store.
Im not really sure whats wrong and why Azure has just decided to stop working.
Firstly, you need to enable logs in Azure, in that case you could access the information logged by Azure and check the logs to find the detail reason. Details for how to do please reference this article.
Since you're using easy table, the azure backend should be node.js. After enabled logs, you could access logs by address like: https://{your app name}.scm.azurewebsites.net/api/vfs/LogFiles/Application/index.html.
If you still cannot resolve your issues by checking the log details, you could upload the log for further looking.

Auto restart windows service

I am trying to a Window Service in C#, which should be running always. If there is a crash or shutdown, then it should automatically restart. I considered using Service controller class, but the problem is how to handle if both Service Controller & Service go down at same time.
Is there a watchdog functionality in Windows with which I can register and it takes care of the service start up?
You could consider using recovery options of service. It can be set through properties of the service when running services.msc.
Please look here and here for more information.
Adding to the above recommended pattern, probably it's a good idea to
Catch the unhandled exception by subscribing to the appdomain.unhandledexception event.
And unload the application domain so that the windows service manager will
initiate the recovery procedure.
AppDoamin.currentAppDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);
void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
Environment.Exit(-1);
}
One recommended pattern here is to set the service start up options to 'Auto' and also, ensure the core functionality of your service is wrapped in a try/catch block.
try
{
// core code here.
}
catch (Exception ex)
{
// log it for debugging and swallow so that service doesn't crash.
}
this ensures that your service is always running. the code will not crash it, and when the machine reboots etc., the service is auto started.

Error handler in Azure Websites does not log all exceptions

I have a site, that uses StackExchange.Exceptional to log exceptions. Problem is, that it does not log all exceptions, like on my development machine.
If it would not log any exceptions, I would think that some configuration/permissions are not working on Azure Websites, may be module is not loaded/working, but for example if I misstype controller action, I get an exception logged:
A public action method 'Logi' was not found on controller 'Acme.Controllers.AccountController'.
I've tried running site using release configuration localy, it works without problem.
As I understand, StackExchange.Exceptional is http module, that is logging unhandled exceptions using this code:
protected virtual void OnError(object sender, EventArgs args)
{
var app = (HttpApplication)sender;
var ex = app.Server.GetLastError();
LogException(ex, app.Context);
}
(https://github.com/NickCraver/StackExchange.Exceptional/blob/master/StackExchange.Exceptional/ExceptionalModule.cs#L36)
May be in some cases on Windows Azure it does not receive OnError event, any ideas what to check, where to search for a clue?
I've managed to replicate the same behaviour on local machine with added this setting:
<customErrors mode="On">
As long as RemoteOnly mode is default, I wasn't seeing problem on local development machine. Not sure why, but when customErrors are enabled, some exceptions were not logged through http handler.

Windows Service not running after installing

I have created a windows service to send mail when service is started. The service works fine like it sends mail when i debug the service and run it via code. But the service is not working after i install it. It is not sending any mail after i install the service.
Can anyone please suggest me the solution?
There is an excellent chance that the service lacks permission to perform one or more actions when run as a service account.
Check the Windows Event Log for any related error messages. As a test, you can configure your service to run as the same user you log on with (just to make sure the issue is permission based... do NOT leave that configuration active as it is a major security hole).
Debugging service is a bit difficult.
use try..catch block with writing messages to file in every method; for example
try
{
..
}
catch(Exception ex)
{
SaveMessage(ex.ToString());
}
Save message method would be:
static void SaveMessage(string s)
{
StreamWriter sw = new StreamWriter(#"C:\service_exceptions_file.txt", true);
sw.WriteLine(s);
sw.Close();
}
Then you will see where is the problem.
Also you can add some messages in your code via abovementioned method to see what parts of code are working without problems
In your Main() method, just add the following lines before ServiceBase.Run(ServicesToRun); :
#if DEBUG
while(!Debugger.IsAttached)
{
Thread.Sleep(1000);
}
#endif
Then install your service and launch it.
While it's launching, attach your debugger to your service's process (Debug Menu => Attach to process) and you should be able to debug it.
Don't forget to set your breakpoints before launching your service.

Handle exception on service startup

I'm writing a series of Windows services. I want them to fail if errors are thrown during startup (in OnStart() method). I had assumed that merely throwing an error in OnStart() would do this, but I'm finding that instead it "Starts" and presents me with a message stating "The service has started, but is inactive. Is this correct?" (Paraphrase). How do I handle the error so it actually fails to start the service?
If the main thing you want is for the Services window to report that there was an error, from what I've tried (.NET3.5 on Windows 7), the only way to do this is by setting the ExitCode. I recommend setting it to 13816, since this results in the message, "An unknown error has occurred." See the windows error codes.
The sample below accomplishes three things.
Setting ExitCode results in a useful message for the end-user. It doesn't affect the Windows Application log but does include a message in the System log.
Calling Stop results in a "Service successfully stopped" message in the Application log.
throwing the exception results in a useful log entry in the Application log.
protected override void OnStart(string[] args) {
try {
// Start your service
}catch (Exception ex) {
// Log exception
this.ExitCode = 13816;
this.Stop();
throw;
}
}
if you are running .NET 2.0 or higher, you can use ServiceBase.Stop to stop the service from OnStart. Otherwise call Stop from a new thread.
ref [devnewsgroups] (http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic50404.aspx)
(news group gone)
Move all of your startup logic to a separate method, and Throw exceptions (or call OnStop) from that seperate method.
OnStart has some oddities when starting up. I have found that if OnStart() has no more than one line in it, then I dont get the "The service started and then stopped.Some services stop automatically if they have no work to do" message, and thrown exceptions will terminate the process and log to the app event log.
Also with the seperate startup method, you can use a technique like this to debug it without attaching. http://www.codeproject.com/KB/dotnet/DebugWinServices.aspx

Categories