Log in

No account? Create an account

Wed, Sep. 19th, 2007, 10:35 am
Can I have some remedy?

Because I'm weird and a bit of a misanthrope I've eschewed any of the more popular Java logging utils and rolled my own. Ornery is not just something that rhinos are and denial is not just a river in Egypt.

Anyway Java applications tend to end up many classes deep because, well, this is Java. And when I'm debugging my crack fuelled code it can be hard to follow what's going on. What would be nice would be to see how far down the call stack we are. What we need is something like Perl's caller function which, as far as I know, doesn't exist.

So I have committed this perversion of which I AM UNJUSTIFIABLY PROUD NAY AROUSED. It may actually be a common Java idiom. There may infact be a better way but this is the way my brain works and if it's wrong then I don't want to be right.
	int call_level = 0;
	try {
		throw new Exception();
	catch (Exception e) {
		call_level = e.getStackTrace().length - 2;

	log_message = String.format("%"+call_level+"s","")+log_message; 

except there's some improvements we can do to that. For example, throwing exceptions uses lngjmp which is expensive so we can actually do is something like this because Exception extends Throwable which means that fillInStackStrace() gets called for us on instantiation. Huzzah!

	StackTraceElement[] stack = (new Exception()).getStackTrace();
	int stack_offset          = 2; // how many classes of indirection before 
                                       // we get to this log class. Could be worked out
                                       // dynamically if needed
	int call_level            = stack.length - stack_offset;
	log_message               = stack[stack_offset+1].getClassName()+"."   +
                                    stack[stack_offset+1].getMethodName()+": " +

        log_message = String.format("%"+call_level+"s", "") + log_message;

and you end up with lovely indented log lines with the class and method (line number is available too if desired) at the start.

Wed, Sep. 19th, 2007 06:19 pm (UTC)
jtrevino: yep

AFAIK, that's the only way to do it. I went the opposite direction, java->perl, so discovering the perl 'caller' function was a pleasant surprise to me.

Thu, Sep. 20th, 2007 11:12 am (UTC)

I find your code to be pleasingly crack-addled.