In this blog I have summarized the best practices for error handling and logging.
1) Appropriate use of try/catch.
2) Log sufficient contextual information. All exceptions are logged(with userid , page or proc name, timestamps ,inner exception , stack trace , if the method is very critical pass method parameters) to database and to file system in case database fails/not responding.
3) For quick diagnosis of problems it is important to log the actual error with all possible information.However the end user should be shown friendly message only.
4) If multiple agents are inserting and updating in a table , ensure that the agent initiating the change is logged.
5) Do not rely on exceptions in the code and write code that avoids exceptions.We should avoid using exceptions to control normal program flow because it can lead to significant impact on performance.
6) Use try-catch in your data layer to catch all database exceptions and ensure this exception handler should record all exceptions from the database. Following details should be recorded : name of the command being executed, stored procedure name, parameters, connection string used etc. After logging the exception, it may be re thrown to another layer .
7) An application level error handler needs to be in place where all general exceptions can be handled.
8) We should avoid throwing exceptions in constructors and destructors.
9) All important tables should have audit data ie : CreatedBy, CreatedOn, UpdatedBy, UpdatedOn
10) Don’t log sensitive data that can pose security risks. You can use masking to log sensitive
information such as: user name/password, email address, phone number, SSN, account
11) Provide an ability to enable / disable debug or informational logs in production environment
without requiring to bring down the system
Messages in this level contain extensive contextual information which is mostly used for problem diagnosis.
These messages contain some execution status information in a production environment.
These indicates a potential problem in the system.
These indicates a serious problem in the system.
System, application, component, thread
Some of the above information is automatically retrieved by the logging implementation if using third party frameworks. To include it in the messages, you only need to configure an appropriate layout pattern.
What to Log
System startup, shutdown, restart, and abnormal termination (crash)
Resources exhausted, capacity reached
Threshold / Limit reached (such as disk space full, memory exhausted, or processor load too high)