Cello How-To Guide 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 2
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 3
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) <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" /> 1.1.1.2 Logging to Database Logging.Config 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. <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" /> To change the database, update databaseinstancename (highlighted above) in the config file. 4
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 /// 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); 1.1.3 Example Consumption try { // your code goes here } catch (DbException dbexception) { ExceptionService.HandleException(dbException, null); // uses default policy ExceptionService.HandleException(dbException, "EmployeeExceptionPolicy ); } 5
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 : <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> Step 2: Web.Config Add the below configuration in logging.config file found under Config Folder inside the web project. Refer Screenshot <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.formattedeventlogtracelist ener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" listenerdatatype="microsoft.practices.enterpriselibrary.logging.configuration.formattedeventl ogtracelistenerdata, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceoutputoptions="none" /> 6
<!--- 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> 7
Logging.Config Step4 : Finally add the below configurations in the ExceptionHandling.config file located in Config Folder inside the Web Project. <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 " formattertype="microsoft.practices.enterpriselibrary.exceptionhandling.xmlexceptionformat ter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" priority="0" type="microsoft.practices.enterpriselibrary.exceptionhandling.logging.loggingexceptionhan dler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="general Logging Handler" /> </exceptionhandlers> </add> </exceptiontypes> </add> </exceptionpolicies> </exceptionhandling> ExceptionHandling.config 8
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 All Critical Description Allows all events through Allows only Critical events through. A critical event is a fatal error or application crash 9
Error Information Off Verbose Warning Allows Critical and Error events through. An Error event is a recoverable error. Allows Critical, Error, Warning, and Information events through. An information event is an informational message. Does not allow any events through. Allows Critical, Error, Warning, Information, and Verbose events through. A Verbose event is a debugging trace. Allows Critical, Error, and Warning events through. A Warning event is a non-critical problem. 10
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: support@techcello.com Phone: +1(609)503-7163 Skype: techcello 11