Logging and Exception


Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Clean Code
  • OutOfMemoryException
  • UncaughtExceptions
  • Logging and Exception

    1. 1. Exception & LoggingAzeem MumtazSoftware Engineer
    2. 2. Introduction• Why Exceptions? ▫ To describe exceptional circumstances ▫ To interrupt the current flow• In Java ▫ Exception are thrown and caught
    3. 3. Exception Class Hierarchy Throwable Error Exception RuntimeException IOException ArithmeticException FileNotFoundException
    4. 4. Types of Exception• Within JVM there are 2 types of exceptions ▫ Checked  Enforced by methods ▫ Unchecked  May lead to thread unraveling and poor visibility
    5. 5. Catching Exceptions• Try ▫ Tells that the enclosed code segment could raise a potential exception• Catch ▫ What exceptions to handle ▫ If no catch for a checked exception, the compiler will generate an error.
    6. 6. Guaranteed Execution of Cleanup Code• To write code that executes when control leaves a code segment ▫ Finally
    7. 7. Throwing Exceptions• Making account for an exceptional problem by throwing an exception• The execution will not continue on current code path
    8. 8. Catching Multiple Exceptions• Using different catch clauses ▫ Most-Specific to Most-General• A new Java construct ▫ “|” operator ▫ Java 7 Feature• Pokemon® Exception ▫ catch (Exception e) ▫ Catches every exception type and treat them same ▫ May catch unwanted exceptions (i.e. OutOfMemoryException)
    9. 9. Catching the Uncaught Exceptions• How to know when a thread is being terminated because of an uncaught exception? ▫ Register an ExceptionHandler  Per thread  Thread.currentThread().setUncaughtExceptionHandler  Globally  Thread.setDefaultUncaughtExceptionHandler
    10. 10. Managing Resource with try/catch• Why? ▫ Managing resources problematic ▫ Should properly dispose once used ▫ Limited and cause performance degradation• ARM ▫ Automatic Resource Management ▫ Java 7 ▫ Try-with-resource block ▫ java.lang.AutoClosable
    11. 11. Creating an Exception Class• extend RuntimeException ▫ Unchecked exceptions ▫ But,  Leads to poor exception handling• extend Exceptions• Rule of Thumb: ▫ If it’s possible to recover from an exception, extend the Exception class. ▫ Else, if it is not reasonable to expect to be recovered from the exception (i.e. NullPointerException), extend RuntimeException.
    12. 12. Re-throwing the Caught Exception• With Java 7, JVM will bubble the exception to the appropriate type• Checked exceptions have to be defined in the method declaration
    13. 13. Logging Events• SLF4J ▫ A Simple Logging Facade for Java ▫ An abstraction for various logging frameworks  Java Logging API  Log4j  Jakarta Commons Logging
    14. 14. log4j• Enabling logging at runtime• Fully Configurable at runtime via external configuration file• Gentle learning curve• 3 Main Parts ▫ Loggers ▫ Appenders ▫ Layouts
    15. 15. log4j• Logger ▫ Named entities ▫ Has a naming hierarchy ▫ Provides run-time control on which statements are printed or not ▫ Root logger  It always exists  It cannot be retrieved by name  Logger.getRootLogger ();
    16. 16. log4j• Log Levels - http://goo.gl/jOWg8 ▫ TRACE ▫ DEBUG  Messages in this level contain extensive contextual information. They are mostly used for problem diagnosis. ▫ INFO  contain some contextual information ▫ WARN  a potential problem in the system – i.e. a security valnarability ▫ ERROR ▫ FATAL• Level inheritance• A logging request is said to be enabled, ▫ If the level of the logging request >= logger’s log level
    17. 17. log4j• Basic Selection Rule ▫ A log request of level p in a logger with (either assigned or inherited, whichever is appropriate) level q, is enabled if p >= q.• TRACE < DEBUG < INFO < WARN < ERROR < FATAL
    18. 18. log4j• .getLogger(…) ▫ Will always return a reference to the exact same object• Log4j makes it easy to name loggers by software component ▫ statically instantiating a logger in each class ▫ Logger name as the class name ▫ A way to define loggers  The origin of the log message is easily identified
    19. 19. log4j• Loggers• Appenders ▫ log4j allows logging requests to print to multiple destinations ▫ An output destination is called appender. Currently appenders exists for;  Console  Files  GUI Components  Remote Sockets, Servers, JMS, NT Event Loggers, Syslog Daemons  Logging Asynchronously
    20. 20. log4j• Appenders ▫ Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy• Appender Additivly ▫ The output of a log statement of logger C will go to all the appenders in C and its ancestors. ▫ Additivity flag
    21. 21. Conslog4j ole root S X File X.Y X.Y. Z
    22. 22. Conslog4j ole root S X File Aditivity = false X.Y X.Y. Z
    23. 23. log4j• Loggers• Appenders• Layout ▫ Customizes log output format ▫ Conversion pattern like C languages printf ▫ http://logging.apache.org/log4j/1.2/apidocs/org/ apache/log4j/PatternLayout.html ▫ Ex:  conversion pattern “%r [%t] %-5p %c - %m%n [%x]”  176 [main] INFO org.foo.Bar - Hello World [1581616 4464 116416 1161]
    24. 24. log4j• Nested Diagnostic Contexts (NDC)• Performance and Best Practices ▫ Log message parameter construction ▫ logger.isDebugEnabled ▫ Choose appropriate logging level ▫ Log message format ▫ Logging in a production environment  Logging sensitive data  Log file management  Correlating specific execution order
    25. 25. Thank You