Exception Management - Techcello · 2014. 7. 10. · 6 Exception Handling Exception Management...
Transcript of Exception Management - Techcello · 2014. 7. 10. · 6 Exception Handling Exception Management...
Cello How-To Guide
Exception Management
2
Exception Handling
Exception Management
Contents 1 Exception handling ..................................................................................................................................... 3
1.1.1 Exception Storage ........................................................................................................................ 3
1.1.2 Exception Service ......................................................................................................................... 5
1.1.3 Example Consumption ................................................................................................................. 5
1.1.4 Exception logging related Configuration...................................................................................... 6
1.1.5 Viewing Exceptions and logs in UI ................................................................................................ 9
1.1.6 How to disable Logging ................................................................................................................ 9
2 Contact Information ................................................................................................................................. 11
3
Exception Handling
Exception Management
1 Exception handling
Exceptions are the standard mechanism for reporting errors occur in the application and the proper usage of
exceptions adds to a consistent framework design and allows error reporting from members, such as
constructors, that cannot have a return type.
A matured, well architected application will be the one, if it adheres to the following aspects.
Auditable – all actions that affect user/data/application state are formally tracked.
Traceable – To determine who/when/where/how an activity occurred throughout the application.
High integrity – Logged information must not be overwritten or tampered by local or remote users.
CelloSaaS Framework provides a wrapper over Microsoft’s Enterprise Library to help SaaS application
developers to capture and manage the exceptions with ease. The Exception Service help the application to
track down the entire exception messages to help the developers and operations team to analyze and find
the root cause of the issue.
Note: Never log critical, secured or important data. If required please mask or encrypt them before writing
to log.
Recommendation:
Generally, Exception logging is considered as a bad practice, because of the improper implementations i.e.
Capturing exceptions throughout all the tiers/layers, unnecessarily throwing the error codes etc. The
recommended approach would be to validate the exception inputs and throw specific exceptions only if the
validation fails. Always write code which works under certain well defined boundary, and throw exceptions
instead of logging and continuing the logic or failing safely. This helps to ensure the written application is
stable (exceptions occurrences are less or null).
1.1.1 Exception Storage
The storage destination has to be decided in the first place as to where the exceptions have to be stored. The
Exceptions can be stored in
1. File
2. Database
4
Exception Handling
Exception Management
1.1.1.1 Logging to a file destination
To log the exception in file, use the Microsoft EnterpriseLibrary’s TraceListeners. By default use the
RollingFlatFileTraceListener as follows in the logging.config. (Refer screenshot below)
Logging.Config
1.1.1.2 Logging to Database To log the exceptions in database, use the cello’s DatabaseTraceListener under CelloSaaS.Library namespace.
Cello’s database listener can be added as following in the Logging.config file. To change the database, update databaseInstanceName (highlighted above) in the config file.
<add name="EventScheduler Listner" fileName="Logs\EventScheduler.log"
type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener,
Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData,
Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35" timeStampPattern="yyyy-MM-dd" rollFileExistsBehavior="Increment"
rollInterval="Day" traceOutputOptions="None" rollSizeKB="4096" />
<add name="Database Trace Listener" type="CelloSaaS.Library.DatabaseTraceListener, CelloSaaS.Library" listenerDataType="CelloSaaS.Library.DatabaseTraceListenerData, CelloSaaS.Library" databaseInstanceName="CelloSaaSConnectionString" writeLogStoredProcName="WriteExceptionLog" addCategoryStoredProcName="AddExceptionCategory" formatter="Text Formatter" traceOutputOptions="LogicalOperationStack, DateTime, Timestamp" />
5
Exception Handling
Exception Management
Logging.Config
Note:
Developers need to create only one database trace listener and redirect all category logs to it.
Developers are advised to have either DB Listener or File Lister for a given application to avoid
duplication of data in both DB as well as File.
1.1.2 Exception Service
1.1.3 Example Consumption
/// Handles the exception with the configured policies /// <param name="exception">Exception to handle</param> /// <param name="policyName">Policy name of the handler (defaults to GlobalExceptionLogger if null)</param> /// <returns>boolean specifying if the exception needs to be rethrown</returns> bool HandleException(Exception exception, string policyName);
try { // your code goes here } catch (DbException dbException) { ExceptionService.HandleException(dbException, null); // uses default policy ExceptionService.HandleException(dbException, "EmployeeExceptionPolicy”); }
6
Exception Handling
Exception Management
1.1.4 Exception logging related Configuration Add the below configurations in web.config under <<CofigSections>> (Refer the below Screenshot) file to
enable exception and logging in your application.
Step 1 :
Web.Config
Step 2:
Add the below configuration in logging.config file found under Config Folder inside the web project. Refer
Screenshot
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging" /> <section name="exceptionHandling"
type="CelloSaaS.Library.Configuration.ExceptionHandlingSettings, CelloSaaS.Library"
/></configSections>
<loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="General" logWarningsWhenNoCategoriesMatch="true"> <listeners> <!-- Writes Logs to Database --> <add name="Database Trace Listener" type="CelloSaaS.Library.DatabaseTraceListener, CelloSaaS.Library" listenerDataType="CelloSaaS.Library.DatabaseTraceListenerData, CelloSaaS.Library" databaseInstanceName="CelloSaaSConnectionString" writeLogStoredProcName="WriteExceptionLog" addCategoryStoredProcName="AddExceptionCategory" formatter="Text Formatter" traceOutputOptions="LogicalOperationStack, DateTime, Timestamp" /> <!-- Writes logs to Windows Event logger --> <add name="Formatted EventLog TraceListener" source="CelloSaaS Application" formatter="Text Formatter" log="Application" machineName="" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="None" />
7
Exception Handling
Exception Management
<!--- Below writes logs to file which will be rolled each day up-to 4MB max file size per roll --> <add name="General Listener" fileName="Logs\UnHandledExceptions.log"
type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener
, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTr
aceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35" timeStampPattern="yyyy-MM-dd"
rollFileExistsBehavior="Increment" rollInterval="Day" traceOutputOptions="None"
rollSizeKB="4096" />
</listeners>
<formatters>
<add name="Text Formatter" template="Timestamp: {timestamp}
Message:
{message}
Category: {category}
Priority: {priority}
EventId:
{eventid}
Severity: {severity}
Title:{title}
Machine: {machine}
Application
Domain: {appDomain}
Process Id: {processId}
Process Name: {processName}
Win32
Thread Id: {win32ThreadId}
Thread Name: {threadName}
Extended Properties:
{dictionary({key} - {value}
)}"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter,
Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Database Trace Listener" /> <!--- Add this to log to database -->
<add name="General Listener" /> <!--- Add this to log to file -->
</listeners>
</add>
</categorySources>
</loggingConfiguration>
8
Exception Handling
Exception Management
Logging.Config
Step4 :
Finally add the below configurations in the ExceptionHandling.config file located in Config Folder inside the
Web Project.
ExceptionHandling.config
<exceptionHandling> <exceptionPolicies> <add name="GlobalExceptionLogger"> <exceptionTypes> <add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" postHandlingAction="None" name="Exception"> <exceptionHandlers> <add logCategory="General" eventId="100" severity="Error" title="Enterprise Library Exception Handling" formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.XmlExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" priority="0" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="General Logging Handler" /> </exceptionHandlers> </add> </exceptionTypes> </add>
</exceptionPolicies>
</exceptionHandling>
9
Exception Handling
Exception Management
More information on configuration visit https://entlib.codeplex.com/
Note: Incase if you want to use separate database to store the Exceptions, the necessary Scripts and store
procedures related to Exception management feature are available in the DBScripts.sql provided in the
package.
1.1.5 Viewing Exceptions and logs in UI
CelloSaaS provides User interface to view, search exceptions captured in the application.
To access the Exception details, navigate to Monitor -> Exceptions & Logs
Exception & Logs
Note: Exception User Interface is only applicable when CelloSaaS database trace listener is used and not for
File Listener.
1.1.6 How to disable Logging
Logging can be either disabled throughout the application or disable for selective modules or features. To
avoid Exception logging, you can simply change the configuration in Logging.config present in the Config
folder under the Web Project (Refer the below Screenshot).
Change the Switch Value to either one of the below values.
Switch Value Description
All Allows all events through
Critical Allows only Critical events through. A critical event is a fatal error or application crash
10
Exception Handling
Exception Management
Error Allows Critical and Error events through. An Error event is a recoverable error.
Information Allows Critical, Error, Warning, and Information events through. An information event is an
informational message.
Off Does not allow any events through.
Verbose Allows Critical, Error, Warning, Information, and Verbose events through. A Verbose event is a
debugging trace.
Warning Allows Critical, Error, and Warning events through. A Warning event is a non-critical problem.
11
Exception Handling
Exception Management
2 Contact Information Any problem using this guide (or) using Cello Framework. Please feel free to contact us, we will be happy to
assist you in getting started with Cello.
Email: [email protected]
Phone: +1(609)503-7163
Skype: techcello