At 15:39 14.01.2002 -0500, you wrote:
>That all worked fine, except that developers would make the mistake of
>putting the wrong class name inside the getInstance() method.  This would
>usually happen when they would cut and paste code.  

The idea of automatically discovering the caller class name has been
suggested before, I believe by Anders Kristensen along similar lines.
It would be nice to have a reliable method to retrieve the caller
class name. However, I am not aware of any such method.

>So, one of our developers came up with a clever solution to cut down on the
>mistakes.  He created a logging utility that could automatically read the
>stack frames, discover which class logged the message, and invoke logging
>from the proper Category.
>
>Here is how he did it:
>
>public class LogUtil {    
>    /**
>     * Extends <code>java.lang.SecurityManager</code> to provide the
><code>getClassName()</code>
>     * method.
>     */
>    private static class ClassGetter extends SecurityManager {
>        // Inner class necessary because getClassContext() is protected
>        
>        /**
>         * Returns the name of the calling class.
>         * @return  the name of the calling class
>         */
>        public String getClassName() {
>            // getClassContext() returns the current execution stack trace
>            // as an array of classes -- the element at index 0 is the class
>            // of the currently executing method, the element at index 1 is
>            // the class of that method's caller, and so on. So, 0 is going
>            // to be this class (ClassGetter), 1 will be LogUtil, and 2 will
>            // be the magic number we are after.
>            return getClassContext()[2].getName();
>        }
>    }

This is pretty smart. However, is it guaranteed to work? How long do
you think it will take you to debug a problem with
getClassContext()[2].getName() compared to a typo? The goal was to
avoid errors, remember? Can it be that you are trading one evil with
even a worse one? 

If getClassContext()[2].getName() is guaranteed to work, then it is a
useful feature, otherwise it is evil. I would not take any chances...


>    public static boolean DEBUG() {
>        Category cat = Category.getInstance(classGetter.getClassName());
>        return cat.isDebugEnabled();
>    }            

The DEBUG method calls Category.getInstance method which is
not particularly fast. As such, this DEBUG method will incur
a constant penalty. I suspect this is not what you want.


--
Ceki Gülcü - http://qos.ch



--
To unsubscribe, e-mail:   <mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>

Reply via email to