Log4net: Log Context Only for Exception - exception

I'm looking for a way to collect a set of data that will only be used for debugging. I.e., the data should only be logged if I log an exception. When I get an exception argument with ILog.Error, Fatal or Debug I want to log the extra information. When logging other data with an exception, the extra information should not be logged.
I plan to use the GlobalContext or ThreadContext for building the dataset.
My idea was to hook into Log4Net and attach to an event I would imagine, to alter the message pattern to include contexts, but I can't find any event that would help me. Perhaps there is an easier way?
What do you think about the overall design of this? Am I on the right track or am I missing something?
If this way is good, how can I implement it?

Hooking in and changing the pattern doesn't feel quite right. I would suggest looking at the filter stuff. So you would set up your "ForMessagesWithExceptionsOnly" appender which uses the MessagesWithExceptionOnly filter. This appender would ofcourse only process messages that contains an exception.
To implement your MessagesWithExceptionOnly filter, have a look at FilterSkeleton.

Related

Is it better to handle MessagingEntityNotFoundException or should i check for Topic existance before sending message

In the code sample in documentation for Microsoft ServiceBus following code is used to make sure that the topic exists.
// Create the topic if it does not exist already
string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
var namespaceManager =
NamespaceManager.CreateFromConnectionString(connectionString);
if (!namespaceManager.TopicExists("TestTopic"))
{
namespaceManager.CreateTopic("TestTopic");
}
But I want to know how expensive the TopicExists call will be, if I put this code before sending the message. (assume that I don't want to have initialization code separately)
Alternative approach is to be optimistic and send the message without checking for topic existence and handling MessagingEntityNotFoundException. In case of the exception we can create the topic and retry sending the message.
The second approach seems better to me, but I couldn't find any reference supporting it. So I want to know that, is there a particular reason that Microsoft in their documentation and samples chose the first approach rather than handling the exception.
One thing to bear in mind is that you need Manage permissions to the bus to create a topic. You may not want to grant this level of permission to all your clients as this can be a bit of a security risk, e.g. a client could create a subscription to read messages it's not supposed to see.
Calling TopicExists() before opening a client connection isn't very expensive and will give rise to more graceful code. If you wait for an exception to be tripped before creating anything then you may find you have a slew of failed messages on your hands.
I normally have a separate process for creating and updating the structure of the bus. How practical this is depends on how many topics and queues you are creating.

Which exceptions should I handle?

I am designing a WinForms application.
At the moment, all my exceptions are being logged at the UI level.
However, for none of them, do I do anything other than logging. Is this indicative of a bad design?
Furthermore, in one method (.NET's method execute a command on a windows service), it can throw exceptions of type Win32Exception and InvalidOperationException.
With an exception like FileNotFound, I could prompt the user to provide another file (although .NET has methods built-in to check for the file's existence), but with exceptions like the above, they are down to low-level problems with the machine, so these can only be logged really.
Is this the right way to go with deciding which exceptions to catch? Also, should I catch or throw ArgumentNullException? It indicates a problem with the code, right?
(I'll use Eric Lippert's taxonomy of exceptions throughout the answer.)
If there is nothing you can do about it, then just log and bail out of the current operation, screen or the entire application, depending on the seriousness of the error. Just don't try to proceed in the face of fatal exceptions. In some extreme cases (like an AccessViolationException), just logging or even letting your finally blocks run may not be a good idea because you don't know what will happen if you run code in a corrupt process.
FileNotFoundException and other exogenous exceptions you should handle anyways. Even though you can check if a file exists beforehand, nothing prevents it from becoming inaccessible in between the check and its use. These exceptions depend on external conditions that you have no control over, so you should be prepared to handle them.
You should never catch ArgumentNullException or any other boneheaded exceptions. If it hurts when you do that, don't do it. If you pass a null argument when you shouldn't, then don't pass it. Fix the code so that it deals with the null reference beforehand.

In which layer should logging of SQL exceptions occur?

Let's pretend for a moment that I have an application which has the following layers: a UI, Controller, Business Logic, and Data Access layer. The UI talks to the Controller, the Controller talks to the Business Logic, and the Business Logic talks to the Data Access layer. Let's also pretend I have a table in the database that houses error messages and exceptions that the administrator can use to troubleshoot problems with the application.
If a SQL exception is thrown in the Data Access Layer (e.g. there is a network issue, string would be truncated, etc.), how far up should the exception information make it before being logged? Ideally the log would contain messages from various layers that would give enough information for a developer to track down the issue. Is it OK for a SQL exception in the Data Access layer to get tossed all the way up to the UI and logged there? Or should it be caught locally, logged, and either rethrown or wrapped in another custom exception? Or should the Data Access layer return a special type that has a flag indicating whether there was an issue, and if so, it also attaches exception information. Also, is it a security concern for SQL exception/stack trace information to make it as far as the UI?
I realize this might be a little subjective for a questions but I'm curious as to what the experts say. Please let me know if you need clarification.
No exception should escape out of the service layer. If you remove the UI, wouldn't you want the services to still be functional?
This also makes sense because it's easy to put your logging into aspects and apply them declaratively to the service interfaces.
You can wrap and rethrow if the custom exception adds value.

grails and mysql batch processing

I'm trying to implement the advice found in this great blog post for batch processing in grails with MySQL. The problem that I'm having is that inclusion of periodic calls to session.clear() in my loop causes org.hibernate.LazyInitializationException's to be thrown. There's a quote down in the comments section of the page:
You’re second point about potentially
causing LIEs is absolutely true. If
you’re doing other things outside of
importing with the current thread,
you’ll want to make sure to reattach
any objects to the session after
you’re doing your clearing.
But how do I do that? Can anyone help me specifically understand how to "reattach any objects to the session after I'm done clearing?
I'm also interested in parallelizing the database insertion process so that I can take advantage of having a multi core processor. Can anyone provide advice on how to do that in Grails?
Grails has a few methods to help with this (they leverage hibernate under the covers).
If you know an object is detached, you can use the attach method to reconnect it.
If you've made changes to the object while it was detatched, you can use merge.
If for whatever reason, you're not sure if an object is attached to the session, you can use the link text method to find out if it is or isn't.
It might also be worth reviewing the Hibernate documentation on Session.

Windows Workflow Foundation, Exceptions and retry's?

I have a sequential workflow with a number of Activities. One of these activities needs to access my paid S3 account. It works fine, but to be cautious, I would like to make sure it can handle unexpected situations, such as 'Host not found' or some timeout, etc.
So .. i would normally put the code inside a TRY / CATCH. That's fine .. but i'm not sure of what i should do with the workflow .. because if the code fails to complete correctly, the rest of the workflow shouldn't occur (based on the logic of this workflow).
So, i wanted to maybe retry the connect a few times .. and if that finally fails, call an Email Activity and terminate workflow.
Can anyone make any suggestions, links to vid's or screenies that help show what is the best practice for this?
cheers!
You might also want to have a look at this blog article on a custom Retry activity:
http://www.pluralsight.com/community/blogs/matt/archive/2007/11/28/49315.aspx
Looks like it is just what you might need!
Take a look at the FaultHandlerActivity, which is used to handle an Exception of the type specified by the FaultType property. Some links about error handling in WF:
Fault Handling in Workflows
Using the FaultHandlerActivity Activity
Exception and Error Handling (partial book chapter)
Another way is to use the Activity.HandleFault method, which is called when an exception is raised within the context of the execution of your activity.