private static final Logger logger = LoggerFactory.getLogger(TestSub1.class);
In this case, the description is different for each class file, and care must be taken when copying.
TestSample1.java
package test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestSample1 {
private static final Logger logger = LoggerFactory.getLogger(TestSub1.class);
public void exec() {
logger.debug("Exec method was executed.");
}
}
private final Logger logger = LoggerFactory.getLogger(this.getClass());
If you use this, you can't make it static
, but you can copy it because the description is the same in every class file.
TestSample2.java
package test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestSample2 {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public void exec() {
logger.debug("TestSample#Exec method was executed.");
}
}
private static final Logger logger = LoggerFactory.getLogger(Util.getClassName());
By using the ʻUtil # getClassNamemethod, all class files have the same description and can be copied. It can also be used with
static`.
TestSample3.java
package test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestSample3 {
private static final Logger logger = LoggerFactory.getLogger(Util.getClassName());
public void exec() {
logger.debug("TestSample3#exec method was executed.");
}
}
Util.java
package test;
public class Util {
public static String getClassName() {
return Thread.currentThread().getStackTrace()[2].getClassName();
}
}
You can use @Produces
and @Inject
to inject instances into Logger
.
All class files have the same description and can be copied.
SampleManagedBean.java
package test.mb;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.slf4j.Logger;
@Named
@SessionScoped
public class SampleManagedBean implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
private transient Logger logger;
public String execute() {
logger.info("SampleManagedBean#execute method was executed.");
return null;
}
}
LoggerFactoryProducer.java
package test.util;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Dependent
public class LoggerFactoryProducer {
@Produces
public Logger getLogger(InjectionPoint ip) {
return LoggerFactory.getLogger(ip.getMember().getDeclaringClass().getName());
}
}
that's all
Recommended Posts