user1787641
user1787641

Reputation: 331

How to get the current class name in Java with log4j

am using log4j for logging, in order to get the class name of the of the respective methods while executing, i got some common method which uses SecurityManager to get the class name, but i dont want to use SecurityManager, is their any other way to get the class name during runtime. Also i dont want to write the code(MyClass.getClassName) to get the classname in each and every class.

class log extends SecurityManager {

public String getClassName() {
        return getClassContext()[3].getName();
    }

}

Upvotes: 5

Views: 19717

Answers (6)

Matthias Meid
Matthias Meid

Reputation: 12513

Instead of receiving the class name, you can also receive a Logger with the class object itself:

public static Logger getLogger(Class clazz)

This is how it's used:

private static final Logger logger = Logger.getLogger(MyClass.class);

http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Logger.html#getLogger(java.lang.Class)

Upvotes: 3

Michal Krasny
Michal Krasny

Reputation: 5916

Solution for static logger:

private static final Logger LOG = Logger.getLogger(new Object() { }.getClass().getEnclosingClass());

Upvotes: 5

Simulant
Simulant

Reputation: 20112

you could add the %l to your PatternLayout in the appender configuration to get the calling class of your log statement.

Upvotes: 2

Markus Kreth
Markus Kreth

Reputation: 748

I guess you need the class name of the class that is calling your log class?

Try this:

StackTraceElement stackTraceElement = new Throwable().getStackTrace()[3];

Upvotes: 1

Shreyos Adikari
Shreyos Adikari

Reputation: 12744

You can do in this way too:

private static final String CLASS_NAME = MyClass.class.getName();

log.debug(new LogRecord(CLASS_NAME," Success = "+isSuccess));

Upvotes: 0

Cao Minh
Cao Minh

Reputation: 109

For the full name (with package):

this.getClass().getName();

For the name of the class (just class name and no more):

this.getClass().getSimpleName();

Upvotes: 4

Related Questions