Reputation: 1433
I have log4j appenders (appendersB, appendersC) and a specific class like below
class A { A{Parent a}}
where Parent is an interface with two implementations as below
class B implements Parent {..}
class C implements Parent {..}
now I want to tell log4j that whenever class A is instantiated with paramater B it should use appendersB and if it receives C then it should use appendersC.
Is this possible?
Upvotes: 0
Views: 397
Reputation: 159124
Choice of appender is done in the Log4j configuration file, based on the logger name, so to be able to configure it so logging entries go to different appenders, your code should use different loggers.
Normally, the logger name is the fully qualified class name, and the logger is created as a static
field of the class. This is done for performance, low memory footprint, and convenience of naming.
You can however make the logger field non-static
, and assign it with a dynamically generated name.
As an example, your A
class would normally do this:
package org.example;
public class A {
private static final Logger log = LogManager.getLogger(A.class);
// rest of code
}
This will create a logger named org.example.A
, which can be configured to write any any appender(s) of choice.
To base logger, and hence potentially the appender, on the actual class of object given as parameter to constructor, you could do this:
package org.example;
public class A {
private final Logger log; // not static
public A(Parent p) {
this.log = LogManager.getLogger(getClass().getName() + "." +
p.getClass().getSimpleName());
}
}
This will create a logger for each instance of A
, and the name derives from constructor parameter, e.g.
new A(new B()) // Logger name: org.example.A.B
new A(new C()) // Logger name: org.example.A.C
You can now configure Log4j to direct logger org.example.A.B
to appenderB
, and logger org.example.A.C
to appenderC
.
You can of course build the dynamic logger name any way you want to. Logger names don't have to be based on class names, e.g. you could name them bravo.foo
and charlie.foo
.
Upvotes: 1