Willis V
Willis V

Reputation: 153

How to log overall class used by two classes

There is a class A and a class B. They both use class C with help of composition. Class A and class B need to generate own in different files, for example: class A generates log to file "log_A.log" and class B - in "log_B.log".

My question is - how to write log of a class C accoerding to a class that invokes class C's method? I mean: if method of a class C was invoked from class A, log of a class C should be generated to to log file for class A - "log_A.log". If method of a class C was invoked from class B, log of class C should be generated to file "log_B.log". And one thing else - logging level for class C should be the same as for logger of a class A or B.

For example, class A:

//loggerA - it's logger that writes to file "log_A.log"
private static final Logger log = Logger.getLogger("loggerA");
public void method(){
    log.debug("Write to log of class A");
    C c = new C();
    c.method(); //activity in class C should be written to "log_A.log" as well
}

In class B:

private static final Logger log = Logger.getLogger("loggerB");
public void method(){
    log.debug("Write to log of class B");
    C c = new C();
    c.method(); //activity in class C should be written to "log_B.log" as well
}

In class C:

private static final Logger log = Logger.getLogger(???);
public void method(){

    log.debug("Any log message");

}

P.S. I use log4j 1.2.16

I can try to do the following: In class C:

public void method(String logger){
    final Logger log = Logger.getLogger(logger); //Use the logger of calling class
    log.debug("Any log message");

}

But I think it's dirty decision

Upvotes: 0

Views: 60

Answers (1)

Raman Shrivastava
Raman Shrivastava

Reputation: 2953

Create a constructor of class C which takes logger as parameter. Now while instantiating C in any other class, pass that class's logger to C. Something like -

class C {
    public C(Logger log) {
        this.log = log;
    }
}

and then in A or B, use it like -

C c = new C(this.log);
c.method();

Upvotes: 2

Related Questions