суббота, октября 08, 2011

Java 'trace to log method call' Aspect

Tried to find that tiny java aspect somewhere in open source but failed. Wrote it myself and published here.  Might be will save a couple of hours for someone.

Short introductory example. Instead of such input args logging:
     @Override
    @Transactional(value = "incidents", readOnly = true)
    public CasesPage getHistoryFor(
        @NotNull ClientId clientId,
        @Nullable SubscriberId subscriberId,
        @Nullable Subject subject,
        @Nullable Category category,
        int offset, int limit
    ) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("getHistoryFor(");
            LOG.trace(" clientId={},", clientId);
            LOG.trace(" subscriberId={},", subscriberId);
            LOG.trace(" subject={}, ", subject);
            LOG.trace(" category={}, ", category);
            LOG.trace(" offset={}, ", offset);
            LOG.trace(" limit={}", limit);
            LOG.trace(")");
        }
        
        //method body (business logic)...
you could simply mark method with annotation:
    @Override
    @Transactional(value = "incidents", readOnly = true)
    @Trace(traceArgs = true, traceRetrunValue = true)
    public CasesPage getHistoryFor(
        @NotNull ClientId clientId,
        @Nullable SubscriberId subscriberId,
        @Nullable Subject subject,
        @Nullable Category category,
        int offset, int limit
    ) {
        
        //method body (business logic)...
and get this in your logs:

13:23:47,250 TRACE getHistoryFor(Client{1,22131},SubscriberId{2,1212121},Subject{id=12, name="12"}, INFORMATION, 1, 100)
...
13:23:47,274 TRACE getHistoryFor() => CasesPage{size=12}