11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javaでメソッド毎のロギング

Posted at

javaでメソッド毎に、引数にわたされた値や処理時間をログに出そうとした場合、AOPを使うのがよくあるようです。メソッド毎にloggerの記述を書くのは読みづらくもなってげんなりなので、どこかにまとめて書ける仕組みはありがたいです。

あたりみたいです。この記事 がかなり参考になります。

AspectJ

あるパッケージのpublicメソッドをロギングしたい場合は次のような感じです。

    @Around("execution(public * hoge.*.*(..))")
    public Object logging(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
          String method = proceedingJoinPoint.getSignature().toShortString(); 
          try {
              logger.info("START {}", method);
              return proceedingJoinPoint.proceed();
          } catch (Throwable t) {
              logger.warn("{} failed.", method);
              throw t;
          } finally {
              stopWatch.stop();
              logger.info("END {}", method);
          }
        }
    }

jcabi-aspects

これは簡単で、ログをとりたいメソッドに@Loggable をつけるだけです

  @Loggable
  public int doSomething(int a) {
       ...
  }

これで次のように出力されます。

[INFO] com.example.Foo #doSomething(10): 200 in 12μs

フレームワークなどで用意されていなかったら、こういうので補うと良さそうです。

参考サイト

11
11
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?