Enterprise library Logging application block fails to write to database - c#

In my application I am using Enterprise library logging application block for logging exception to DB.Also, I am using fluent API to configure the logging application block.
Things I noticed:
When I was not using the Fluent API and database logging fails it logged the exception to windows event log.(version 5.0)
But when i used it(Fluent API), In case of database failure it is not logging exception anywhere not even in windown event log.
My Question:
Is it a normal behavior of Enterprise library logging application block?
Is there any way that using fluent API I can get the functionality what I was getting without it, Meaning (in case db logging fails log to windows event log).
Feel free to suggest in case of any discrepancy. :-)

The exact syntax depends on your existing configuration. Assuming you have no trace listener or formatter already configured that you want to use:
configurationSourceBuilder
.ConfigureLogging()
.SpecialSources.LoggingErrorsAndWarningsCategory
.SendTo.EventLog("Event Log Listener")
.FormatWith(new FormatterBuilder().TextFormatterNamed("Text Formatter"));
If you already have an Event Log trace listener configured that you want to use (named "Event Log Listener" in this example):
configurationSourceBuilder
.ConfigureLogging()
.SpecialSources.LoggingErrorsAndWarningsCategory
.SendTo.SharedListenerNamed("Event Log Listener");
If you already have a log formatter configured that you want to use (named "Text Formatter" in this example):
configurationSourceBuilder
.ConfigureLogging()
.SpecialSources.LoggingErrorsAndWarningsCategory
.SendTo.EventLog("Event Log Listener")
.FormatWithSharedFormatter("Text Formatter");

Related

How to track down AppInsights internal error

Some general setup of my system:
Windows x64
.net 3.1
AspNet.Core
Serilog + AppInsights writer
Recently, we started to observe many trace logs like below. I think something went wrong when we try to write log into AppInsights. But we can see our logs. It seems we have everything we wanted logging into AppInsights correctly. But we also have this unwanted trace message logged in as well, and there are a lot of them.
This trace message happens on my local machine, in our Azure AKS environment. But the stack trace is too short to help locating the origin of the error.
AI (Internal): [Microsoft-ApplicationInsights-Core] [msg=Log Error];[msg=Exception while initializing Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers.ClientIpHeaderTelemetryInitializer, exception message - System.ObjectDisposedException: Request has finished and HttpContext disposed.
Object name: 'HttpContext'.
at Microsoft.AspNetCore.Http.DefaultHttpContext.ThrowContextDisposed()
at Microsoft.AspNetCore.Http.DefaultHttpContext.get_Features()
at Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers.TelemetryInitializerBase.Initialize(ITelemetry telemetry)
at Microsoft.ApplicationInsights.TelemetryClient.Initialize(ITelemetry telemetry)]
I tried to create an environment, with Asp.net core application & .net3.1 for track down the logs (Request, exceptions, users, failure, trace etc.)
Here are the steps i followed : Added application insight telemetry to my application and install the NuGet package Microsoft.ApplicationInsights.AspNetcore
And in startup.cs under services.AddControllersWithViews(); add
services.AddApplicationInsightsTelemetry(Configuration["APPINSIGHTS_CONNECTIONSTRING"]);
After deploy the app to azure and for tracing the logs go to my created Application insights> Transaction search>view data ,Where we can see all of our logs as below also to identify if there is any error occurs.
Also we can download all our logs and track down for the application using kudu-console.
Go to App service>Advance tools>Go
For more information please refer the below links:
.MS DOC | Explore .NET/.NET Core and Python trace logs in Application Insights
.SO Thread | Application Insights not showing stack trace for errors
.Blog| Using Azure Application Insights For Exception Logging In C#

NLog - how to configure to conditionally write to Database and on exception to Email and on exception to File

Previously I had built a logging class where I could choose Either to write to an Oracle database (as a separate connection), or if there was an exception to then send a SMTP email, or if that had an exception to write to a physical file (using the DefaultLogWriter from the Microsoft.VisualBasic.Logging namespace).
Now that I am writing a new WinForms application where the database is SQL Server ... and because Transactions are handled differently vs Oracle ... I wanted to use NLog (because of its pre-built ability to write to always run outside of transaction).
When calling an instantiated object of NLog.Logger defined as
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
is it possible for the call to Logger.<LogLevel> to be configured so that exceptions roll downhill (ex. 1st try the Database, 2nd try sending an email, 3rd write to a file)?
Thanks for your time and any suggestions you offer.
I think FallBackGroup is what you are looking for:
https://github.com/NLog/NLog/wiki/FallbackGroup-target

Get Log From Production Environment

We Have A C# Application That Runs On Many Client Machines And We Have Very Lines Of Code Like This:
try{exceptionalMethod();}//all type of exceptions may be throw here (system.exception,our business exceptions ,...)
catch{MessageBox.Show("Error");randomMethod();}//we don't have any log here
How We Can Log All CLR First Chance Exceptions In Log File In Production Environment.
Attention: We Can't Install AnyThing On the client's Machine(If We Can, We Use Adplus And Windows Debuggers With Very Simple Configuration File).
But We Can Insert Minimum Changes In Code And Ship New Version.

ASP.Net Web API exception filter, logging to database failing

In our ASP.Net Web API application we are planning to handle the handle exceptions via Global exception filter attribute, as detailed in the following link.
We are planning to log the exception to in multiple medium like database, files using NLog. what baffles me is a medium like Database, if we log and there's an exception like database down, connection timeout and multiple others, then it will go in infinite loop, as it will keep try to log the exception, which will be keep returning an exception.
Is there a mechanism to restrict it 1 or 2 tries and after that fail silently, not enter an infinite loop, any pointers
We are planning to log the exception to in multiple medium like
database, files using NLog. what baffles me is a medium like Database,
if we log and there's an exception like database down, connection
timeout and multiple others, then it will go in infinite loop, as it
will keep try to log the exception, which will be keep returning an
exception.
That's why you should make absolutely sure that your logging code never fails. For example by wrapping it in a try/catch statement.

Why does my c# Windows service stop running without any messages being written to the application event log?

I am fairly new to Windows services. I created an installer for my c# Windows service and the installation on the server (Windows Server 2003) appears to have worked. When it's started, it writes Service started successfully to the log. When it's stopped, it writes Service stopped successfully. However, sometimes the service stops running without writing anything to the log, so I start it back up manually. When I look at the log afterward, it says Service started successfully as expected. It's weird seeing that in the log twice in a row being that it's obviously missing an entry where the service had somehow stopped running.
What could be the potential causes for this? I have the service set up as automatic and installed it to run for all users. I was under the impression that this means the service starts automatically whenever the machine boots up. How can I find out why it stopped? Do services that crash automatically write to the event log or do I have to handle exceptions in such a way that they log their own reason for the crash?
Edit: Some additional info:
I have it set up to log on as Local System Account
Under Recovery options, I have it set up to restart on first failure. I don't have anything for second or subsequent failures.
Update: An answerer recommended a global exception handler. While I won't implement this as a permanent fix, it will at least help me figure out where the problem is occurring. I actually tested this with my installed service and it works. I found out that unhandled exceptions actually do crash the service without writing anything to the log at all. I thought it'd at least report some application error, but it doesn't.
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
//other code here
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Utilities.WriteIt(e.ExceptionObject as Exception);
}
It's always best to handle the exceptions. At least use a global exception handler and write it to a logfile
It sounds like your service is failing unexpectedly without doing any form of exception-handling and/or logging. Windows services do not automatically write exceptions to the Event Log - it's up to you to handle exceptions and (if they're fatal) write them out somewhere so that you can diagnose the problem.
At the very least, I'd recommend a logfile somewhere (perhaps in the service executable folder, or preferably somewhere else that's easy to get to and won't run afoul of permissioning issues) and a standard logging method that all your exception-handlers call to write their messages to.
If a service quits unexpectedly because of some exception, I am not sure it would end up in the Event Log automatically.
I would highly recommend a logging suite like log4net for more thorough logging. You'll be able to provide a multitude of logging 'levels' (debug traces to see if you reached some code, info traces for important events, error traces to log exceptions).
You can look here for an example of a EventLogAppender. However, I would suggest starting with getting a FileAppender, one of the easiest logs to create, working first and then add a second appender for the Event Log.

Categories