Simon Wistow (deflatermouse) wrote,
Simon Wistow
deflatermouse

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;	

        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.
Tags: crack, java, logging, longjmp, perversion
Subscribe
  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 2 comments