The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util.logging  [20 examples]

e387. Logging a Method Call

The logger provides convenience methods Logger.entering() and Logger.exiting() for logging method calls. This example implements a method that logs the parameters upon entry and the result when returning.

See also e388 Logging an Exception.

    package com.mycompany;
    class MyClass {
        public boolean myMethod(int p1, Object p2) {
            // Log entry
            Logger logger = Logger.getLogger("com.mycompany.MyClass");
            if (logger.isLoggable(Level.FINER)) {
                logger.entering(this.getClass().getName(), "myMethod",
                                new Object[]{new Integer(p1), p2});
            }
    
            // Method body
    
            // Log exit
            boolean result = true;
            if (logger.isLoggable(Level.FINER)) {
                logger.exiting(this.getClass().getName(), "myMethod", new Boolean(result));
    
                // Use the following if the method does not return a value
                logger.exiting(this.getClass().getName(), "myMethod");
            }
            return result;
         }
    }
Here is a sample of the output using a simple formatter and the following call:
    new com.mycompany.MyClass().myMethod(123, "hello");
    
    Jan 10, 2002 7:59:48 PM com.mycompany.MyClass myMethod
    FINER: ENTRY 123 hello
    Jan 10, 2002 7:59:49 PM com.mycompany.MyClass myMethod
    FINER: RETURN true
    Jan 10, 2002 7:59:49 PM com.mycompany.MyClass myMethod
    FINER: RETURN

 Related Examples
e385. The Quintessential Logging Program
e386. Determining If a Message Will Be Logged
e388. Logging an Exception
e389. Minimizing the Impact of Logging Code
e390. Preventing a Logger from Forwarding Log Records to Its Parent
e391. Writing Log Records to a Log File
e392. Writing Log Records to Standard Error
e393. Writing Log Records Only After a Condition Occurs
e394. Setting a Filter on a Logger Handler

See also: Configuration    File Size    Formatters    Levels   


© 2002 Addison-Wesley.