开发者

Java Logger in subclass

开发者 https://www.devze.com 2023-03-05 14:53 出处:网络
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 {

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 {
}


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;);  
}


You may use this in base class:

protected Logger logger = Logger.getLogger(this.getClass().getName());

this.getClass() will initialize the logger with subclass name.

0

精彩评论

暂无评论...
验证码 换一张
取 消