log icon indicating copy to clipboard operation
log copied to clipboard

Class Name as Default Tag: Support Inheritance

Open commonsguy opened this issue 10 years ago • 2 comments

Not sure if this is practical, but...

class Foo {
    public void foo() {
        Log.d("Hello"); // prints 'D/Foo: Hello'
    }
}

As your docs show, this uses Foo as the tag, if somebody calls foo() on an instance of Foo.

class Foo {
    public void foo() {
        Log.d("Hello"); // prints 'D/Foo: Hello'
    }
}

class Bar extends Foo {
    public void baz() {
        foo();
    }
}

Calling baz() on an instance of Bar also logs Foo as the tag, rather than Bar. IOW, the class name used for the tag is the class containing the method doing the logging, not the class whose instance is the one calling that method.

IMHO, ideally, Bar would be logged in this case. If you disagree and feel that Foo is the right answer, that's cool, but you might want to mention this in the docs, as it caught me by surprise.

commonsguy avatar Jan 09 '16 17:01 commonsguy

I see your point and it probably makes certain sense. However I wonder if there is a technical possibility to achieve this?

Currently, the default tag is extracted from the stack trace (from the caller class name) and that's why the class actually calling the log is used as a tag.

For the behaviour you describe it will require to scan the stack trace upwards while the caller is an ancestor of the given class. But this assumption is still weak, for example:

class Foo {
  public void foo() { Log.d("Hello"); }
}
class Bar extends Foo {
  private Foo mFoo = new Foo();
  public void baz() { foo(); } // Ok, this should print "D/Bar: Hello"
  public void qux() { mFoo.foo(); } // But this should still be "D/Foo: Hello", isn't it?
}

How to tell these two cases? I don't think it's possible to tell one from another using the information from the StackTraceElement...

zserge avatar Jan 10 '16 10:01 zserge

Yeah, that's why I started off with "Not sure if this is practical"... :-)

You have infinitely more experience with StackTraceElement than I do, so you'll know far better than I what is and is not possible here.

commonsguy avatar Jan 10 '16 12:01 commonsguy