Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Logger in subclass

Tags:

java

logging

To get C.run() to use its own class logger, should I add a public/protected method getLogger() in B?

public abstract class A extends Thread {
    @Override
    public abstract void run();
}

public class B extends A {

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

    @Override
    protected void run() {
        // do something

        logger.info("B");
    }
}

public class C extends B {
}
like image 959
Nicklas Avatar asked May 12 '11 10:05

Nicklas


People also ask

How can logger be used in multiple classes?

Your logger instances should typically be private , static and final . By doing so, each class will have it's own logger instance (that is created once the class is loaded), so that you could identify the class where the log record was created, and also you no longer need to pass logger instances across classes.

Can we add logger in abstract class?

If you create the logger in the abstract class, the logs will all come out tagged as originating from AbstractFoo. If you want/need to see logs tagged with the child class from which the log occurred, create loggers for the children classes.

Where do we use logger in Java?

A Logger object is used to log messages for a specific system or application component. Loggers are normally named, using a hierarchical dot-separated namespace. Logger names can be arbitrary strings, but they should normally be based on the package name or class name of the logged component, such as java.net or javax.

Is Java logger thread safe?

Yes, log4j is thread-safe. Log4j components are designed to be used in heavily multithreaded systems.


1 Answers

Well the Loggers are ideally set at Class level. So if C needs it own Logger then declare its own Logger in C e.g.

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

This way when C runs some code it logs to its own Logger and when B runs it logs to its own Logger. You'll be able to clearly see which Class logs what this way.

If this isn't what you're after please expand the question with what you're trying to achieve and why.

I'm not convinced if the following code is a good idea (I always want the Class which is physically running the code to be the Logger) but it should work:

public abstract class A extends Thread {
    @Override
    public abstract void run();
    protected abstract Logger getLogger();
}

public class B extends A {

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

    @Override
    public void run() {
        getLogger().info("B");
    }

    @Override
    protected Logger getLogger() {return logger;);  
}

public class C extends B {

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

    @Override
    protected Logger getLogger() {return logger;);  
}
like image 195
planetjones Avatar answered Oct 29 '22 06:10

planetjones