LoginSignup
2
2

More than 1 year has passed since last update.

JavaでSLF4Jを使用する際のLoggerFactory.getLoggerの引数のクラス名取得方法

Last updated at Posted at 2020-01-12

一般的な取得方法

private static final Logger logger = LoggerFactory.getLogger(TestSub1.class);

この場合、クラスファイル毎に記述が異なり、コピーする場合注意する必要がある。

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

thisを使って取得

private final Logger logger = LoggerFactory.getLogger(this.getClass());

thisを使用する場合、staticにすることができないが、どのクラスファイルでも記述が同じため、コピーすることができる。

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

Util#getClassNameメソッドを使用することで、どのクラスファイルでも記述が同じため、コピーすることができる。また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();
	}
}

CDIの場合

@Produces@Injectを使用して、Loggerにインスタンスを注入することが可能。
どのクラスファイルでも記述が同じため、コピーすることができる。

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

以上

2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2