All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.java.ao.sql.LoggingInterceptor Maven / Gradle / Ivy

Go to download

This is the full Active Objects library, if you don't know which one to use, you probably want this one.

There is a newer version: 6.1.1
Show newest version
package net.java.ao.sql;

import org.slf4j.Logger;

import java.time.Clock;
import java.util.Collections;
import java.util.Map;

public class LoggingInterceptor {
    private final Logger logger;
    private final CallStackProvider callStackProvider;
    private final Clock clock;
    private final boolean callStackLogging;
    private long executionStartTime;

    public LoggingInterceptor(final Logger logger, final CallStackProvider callStackProvider, final Clock clock) {
        this(logger, callStackProvider, clock, false);
    }

    public LoggingInterceptor(final Logger logger, final CallStackProvider callStackProvider, final Clock clock, final boolean callStackLogging) {
        this.callStackProvider = callStackProvider;
        this.logger = logger;
        this.clock = clock;
        this.callStackLogging = callStackLogging;
    }

    public void beforeExecution() {
        executionStartTime = clock.millis();
    }

    public void afterSuccessfulExecution(String query) {
        afterSuccessfulExecution(query, Collections.emptyMap());
    }

    public void afterSuccessfulExecution(String query, final Map params) {
        query = getFullQuery(query, params);

        if (isCallStackLoggingEnabled()) {
            logger.debug(query + "\ncall stack\n\t...\n" + callStackProvider.getCallStack() + "\t...");
        } else {
            logger.debug(query);
        }
    }

    private boolean isCallStackLoggingEnabled() {
        return callStackLogging;
    }

    public void onException(final Exception exception) {
        logger.error(exception.getMessage(), exception);
    }

    public void onException(final String query, final Exception exception) {
        onException(query, Collections.emptyMap(), exception);
    }

    public void onException(final String query, final Map params, final Exception exception) {
        logger.error(getFullQuery(query, params), exception);
    }

    private String getFullQuery(final String query, final Map params) {
        return joinQueryAndParams(getQueryWithExecutionTime(query), params);
    }

    private String joinQueryAndParams(String query, final Map params) {
        if(params.isEmpty()) {
            return query;
        }

        return query + " " + params.toString();
    }

    private String getQueryWithExecutionTime(final String query) {
        return getExecutionTime() + " ms \"" + query + "\"";
    }

    private long getExecutionTime() {
        return clock.millis() - executionStartTime;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy