LoginSignup
12
11

More than 5 years have passed since last update.

logger オブジェクト生成時にクラスを指定しない方法

Last updated at Posted at 2014-03-11

logger オブジェクトを生成する際、以下のように書くとします。

commons-loggingの場合
public class Hoge {
    private static Log LOGGER = LogFactory.getLog(Hoge.class); 
...

この引数のHoge.classを間違えて他のクラスを指定しまうことがないとは言えません。
(めったにないとは思いますけど、、)

間違いを防ぐためにクラスを指定しないで logger オブジェクトを生成する方法を 2 つ紹介します。
(インスタンスフィールドにするというのは今回はなしで)

ユーティリティーメソッドを作る

以下のようなメソッドを作成し、これを使用して logger オブジェクトを生成します。

ユーティリティ
public final class LogUtils {

    public static Log getLog() {
        StackTraceElement[] stackTraces = new Throwable().getStackTrace();
        String sourceClassName = stackTraces[1].getClassName();
        try {
            return LogFactory.getLog(Class.forName(sourceClassName));
        } catch (LogConfigurationException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
public class Hoge {
    private static Log LOGGER = LogUtils.getLog();
...

lombok を使う

lombok@Log系アノテーションを使用します。
commons-logging 以外にも様々な log ライブラリに対応しています。こちら を参照。
以下のように書くと自動的に Log オブジェクトが生成されて static フィールド log が初期化されます。

commons-loggingの場合
import lombok.extern.apachecommons.CommonsLog;

@CommonsLog
public class Hoge {
...

    log.error("error.");
...
12
11
10

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
12
11