From d053799ba24109dbe98a435853c3ed0e6511e8a3 Mon Sep 17 00:00:00 2001 From: Hideki Sugimoto Date: Wed, 11 Sep 2024 02:58:46 +0900 Subject: [PATCH] Changed to use slf4j v2.0 API Also added suppressLogging API --- .../jp/co/future/uroborosql/SqlAgentImpl.java | 49 ++++++------- .../future/uroborosql/SqlEntityQueryImpl.java | 8 +-- .../jp/co/future/uroborosql/UroboroSQL.java | 10 +-- .../co/future/uroborosql/client/SqlREPL.java | 6 +- .../client/command/DescCommand.java | 2 +- .../client/command/GenerateCommand.java | 2 +- .../client/completer/TableNameCompleter.java | 2 +- .../context/ExecutionContextImpl.java | 4 +- .../context/ExecutionContextProviderImpl.java | 30 ++++---- .../coverage/CoberturaCoverageHandler.java | 6 +- .../uroborosql/coverage/CoverageData.java | 2 +- .../html/HtmlReportCoverageHandler.java | 4 +- .../reports/html/SqlCoverageReport.java | 2 +- .../AbstractSecretColumnEventSubscriber.java | 18 ++--- .../subscriber/AuditLogEventSubscriber.java | 8 +-- .../subscriber/DebugEventSubscriber.java | 24 +++---- .../subscriber/DumpResultEventSubscriber.java | 10 +-- .../expr/ognl/OgnlExpressionParser.java | 5 +- .../expr/spel/SpelExpressionParser.java | 2 +- .../co/future/uroborosql/log/LoggerBase.java | 70 ++++++++++++++++++- .../jp/co/future/uroborosql/node/IfNode.java | 2 +- .../uroborosql/parameter/Parameter.java | 8 +-- .../store/SqlResourceManagerImpl.java | 33 ++++----- .../tx/LocalTransactionContext.java | 2 +- .../tx/LocalTransactionManager.java | 2 +- .../jp/co/future/uroborosql/SqlQueryTest.java | 44 ++++++++++++ .../expr/AbstractExpressionParserTest.java | 4 +- 27 files changed, 236 insertions(+), 123 deletions(-) diff --git a/src/main/java/jp/co/future/uroborosql/SqlAgentImpl.java b/src/main/java/jp/co/future/uroborosql/SqlAgentImpl.java index 50d40e70..a553b0bb 100644 --- a/src/main/java/jp/co/future/uroborosql/SqlAgentImpl.java +++ b/src/main/java/jp/co/future/uroborosql/SqlAgentImpl.java @@ -1356,7 +1356,7 @@ public ResultSet query(final ExecutionContext executionContext) throws SQLExcept // REPLで実行するための文字列をREPLログに出力する outputReplLog(executionContext); - LOG.atDebug() + atDebug(LOG) .setMessage("Execute query sql. sqlName: {}") .addArgument(executionContext.getSqlName()) .log(); @@ -1401,7 +1401,7 @@ public ResultSet query(final ExecutionContext executionContext) throws SQLExcept var pessimisticLockingErrorCodes = dialect.getPessimisticLockingErrorCodes(); if (maxRetryCount > loopCount && (getSqlRetryCodes().contains(errorCode) || getSqlRetryCodes().contains(sqlState))) { - LOG.atDebug() + atDebug(LOG) .setMessage("Caught the error code to be retried.({} times). Retry after {} ms.") .addArgument(loopCount + 1) .addArgument(() -> String.format("%,3d", retryWaitTime)) @@ -1440,7 +1440,7 @@ public ResultSet query(final ExecutionContext executionContext) throws SQLExcept return null; } finally { // 後処理 - PERFORMANCE_LOG.atInfo() + atInfo(PERFORMANCE_LOG) .setMessage("SQL execution time [{}({})] : [{}]") .addArgument(() -> generateSqlName(executionContext)) .addArgument(executionContext.getSqlKind()) @@ -1498,7 +1498,7 @@ public int update(final ExecutionContext executionContext) throws SQLException { // 更新移譲処理の指定がある場合は移譲処理を実行し結果を返却 if (executionContext.getUpdateDelegate() != null) { - LOG.atInfo() + atInfo(LOG) .log("Performs update delegate of update process."); return executionContext.getUpdateDelegate().apply(executionContext); } @@ -1513,7 +1513,7 @@ public int update(final ExecutionContext executionContext) throws SQLException { // REPLで実行するための文字列をREPLログに出力する outputReplLog(executionContext); - LOG.atDebug() + atDebug(LOG) .setMessage("Execute update sql. sqlName: {}") .addArgument(executionContext.getSqlName()) .log(); @@ -1571,7 +1571,7 @@ public int update(final ExecutionContext executionContext) throws SQLException { var errorCode = String.valueOf(ex.getErrorCode()); var sqlState = ex.getSQLState(); if (getSqlRetryCodes().contains(errorCode) || getSqlRetryCodes().contains(sqlState)) { - LOG.atDebug() + atDebug(LOG) .setMessage("Caught the error code to be retried.({} times). Retry after {} ms.") .addArgument(loopCount + 1) .addArgument(() -> String.format("%,3d", retryWaitTime)) @@ -1603,7 +1603,7 @@ public int update(final ExecutionContext executionContext) throws SQLException { } finally { // 後処理 var curStartTime = startTime; - PERFORMANCE_LOG.atInfo() + atInfo(PERFORMANCE_LOG) .setMessage("SQL execution time [{}({})] : [{}]") .addArgument(() -> generateSqlName(executionContext)) .addArgument(executionContext.getSqlKind()) @@ -1630,7 +1630,7 @@ public int[] batch(final ExecutionContext executionContext) throws SQLException // 更新移譲処理の指定がある場合は移譲処理を実行し結果を返却 if (executionContext.getUpdateDelegate() != null) { releaseParameterLogging(); - LOG.atInfo() + atInfo(LOG) .log("Performs update delegate of batch process."); return new int[] { executionContext.getUpdateDelegate().apply(executionContext) }; } @@ -1642,7 +1642,7 @@ public int[] batch(final ExecutionContext executionContext) throws SQLException // INパラメータ設定 executionContext.bindBatchParams(stmt); - LOG.atDebug() + atDebug(LOG) .setMessage("Execute batch sql. sqlName: {}") .addArgument(executionContext.getSqlName()) .log(); @@ -1697,7 +1697,7 @@ public int[] batch(final ExecutionContext executionContext) throws SQLException var errorCode = String.valueOf(ex.getErrorCode()); var sqlState = ex.getSQLState(); if (getSqlRetryCodes().contains(errorCode) || getSqlRetryCodes().contains(sqlState)) { - LOG.atDebug() + atDebug(LOG) .setMessage("Caught the error code to be retried.({} times). Retry after {} ms.") .addArgument(loopCount + 1) .addArgument(() -> String.format("%,3d", retryWaitTime)) @@ -1730,7 +1730,7 @@ public int[] batch(final ExecutionContext executionContext) throws SQLException } finally { // 後処理 var curStartTime = startTime; - PERFORMANCE_LOG.atInfo() + atInfo(PERFORMANCE_LOG) .setMessage("SQL execution time [{}({})] : [{}]") .addArgument(() -> generateSqlName(executionContext)) .addArgument(executionContext.getSqlKind()) @@ -1764,7 +1764,7 @@ public Map procedure(final ExecutionContext executionContext) th // パラメータ設定 executionContext.bindParams(callableStatement); - LOG.atDebug() + atDebug(LOG) .setMessage("Execute stored procedure. sqlName: {}") .addArgument(executionContext.getSqlName()) .log(); @@ -1808,7 +1808,7 @@ public Map procedure(final ExecutionContext executionContext) th var errorCode = String.valueOf(ex.getErrorCode()); var sqlState = ex.getSQLState(); if (getSqlRetryCodes().contains(errorCode) || getSqlRetryCodes().contains(sqlState)) { - LOG.atDebug() + atDebug(LOG) .setMessage("Caught the error code to be retried.({} times). Retry after {} ms.") .addArgument(loopCount + 1) .addArgument(() -> String.format("%,3d", retryWaitTime)) @@ -1840,7 +1840,7 @@ public Map procedure(final ExecutionContext executionContext) th } finally { // 後処理 var curStartTime = startTime; - PERFORMANCE_LOG.atInfo() + atInfo(PERFORMANCE_LOG) .setMessage("Stored procedure execution time [{}({})] : [{}]") .addArgument(() -> generateSqlName(executionContext)) .addArgument(executionContext.getSqlKind()) @@ -1880,12 +1880,12 @@ private void transformContext(final ExecutionContext executionContext) { if (SQL_LOG.isInfoEnabled() && sqlName != null) { if (executionContext.getSqlKind().isEntityType()) { - SQL_LOG.atInfo() + atInfo(SQL_LOG) .setMessage("EntityClass : {}") .addArgument(sqlName) .log(); } else if (getSqlResourceManager().existSql(sqlName)) { - SQL_LOG.atInfo() + atInfo(SQL_LOG) .setMessage("SQLPath : {}") .addArgument(() -> getSqlResourceManager().getSqlPath(sqlName)) .log(); @@ -1912,7 +1912,7 @@ && getSqlConfig().getEventListenerHolder().hasBeforeParseSqlListener()) { .forEach(listener -> listener.accept(eventObj)); } - SQL_LOG.atDebug() + atDebug(SQL_LOG) .setMessage("Template SQL[{}{}{}]") .addArgument(System.lineSeparator()) .addArgument(originalSql) @@ -1932,7 +1932,7 @@ && getSqlConfig().getEventListenerHolder().hasBeforeParseSqlListener()) { // SQLカバレッジ用のログを出力する var coverageData = new CoverageData(sqlName, originalSql, contextTransformer.getPassedRoute()); - COVERAGE_LOG.atDebug() + atDebug(COVERAGE_LOG) .setMessage("coverage data: {}") .addArgument(coverageData) .log(); @@ -1941,7 +1941,7 @@ && getSqlConfig().getEventListenerHolder().hasBeforeParseSqlListener()) { } } - SQL_LOG.atInfo() + atInfo(SQL_LOG) .setMessage("Executed SQL[{}{}{}]") .addArgument(System.lineSeparator()) .addArgument(executionContext.getExecutableSql()) @@ -1977,7 +1977,7 @@ private void handleException(final ExecutionContext executionContext, final SQLE } if (outputExceptionLog) { - LOG.atError() + atError(LOG) .setMessage(() -> { var builder = new StringBuilder(); builder.append(System.lineSeparator()).append("Exception occurred in SQL execution.") @@ -2034,7 +2034,7 @@ private void outputReplLog(final ExecutionContext executionContext) { builder.append(" "); builder.append(SqlParamUtils.formatPrams(params)); } - REPL_LOG.atInfo() + atInfo(REPL_LOG) .setMessage("REPL command: {}") .addArgument(builder.toString()) .log(); @@ -2900,7 +2900,8 @@ private static String formatElapsedTime(final Instant start, final Instant end) * * @param ResultSetの1行を変換した型 */ - private static final class ResultSetSpliterator extends Spliterators.AbstractSpliterator { + private static final class ResultSetSpliterator extends Spliterators.AbstractSpliterator + implements ServiceLogger { private final ResultSetConverter converter; private final ResultSet rs; private boolean finished = false; @@ -2929,7 +2930,7 @@ public boolean tryAdvance(final Consumer action) { rs.close(); } } catch (SQLException ex2) { - LOG.atError() + atError(LOG) .setMessage(ex2.getMessage()) .setCause(ex2) .log(); @@ -2941,7 +2942,7 @@ public boolean tryAdvance(final Consumer action) { rs.close(); } } catch (SQLException ex2) { - LOG.atError() + atError(LOG) .setMessage(ex2.getMessage()) .setCause(ex2) .log(); diff --git a/src/main/java/jp/co/future/uroborosql/SqlEntityQueryImpl.java b/src/main/java/jp/co/future/uroborosql/SqlEntityQueryImpl.java index b64bbdf3..a9894632 100644 --- a/src/main/java/jp/co/future/uroborosql/SqlEntityQueryImpl.java +++ b/src/main/java/jp/co/future/uroborosql/SqlEntityQueryImpl.java @@ -581,7 +581,7 @@ public SqlEntityQuery forUpdateNoWait() { return this; } else if (!agent().getSqlConfig().getSqlAgentProvider().isStrictForUpdateType() && dialect.supportsForUpdate()) { - LOG.atWarn() + atWarn(LOG) .log("'FOR UPDATE NOWAIT' is not supported. Set 'FOR UPDATE' instead."); this.forUpdateType = ForUpdateType.NORMAL; return this; @@ -601,7 +601,7 @@ public SqlEntityQuery forUpdateWait() { return forUpdateWait(agent().getSqlConfig().getSqlAgentProvider().getDefaultForUpdateWaitSeconds()); } else if (!agent().getSqlConfig().getSqlAgentProvider().isStrictForUpdateType() && dialect.supportsForUpdate()) { - LOG.atWarn() + atWarn(LOG) .log("'FOR UPDATE WAIT' is not supported. Set 'FOR UPDATE' instead."); this.forUpdateType = ForUpdateType.NORMAL; return this; @@ -623,7 +623,7 @@ public SqlEntityQuery forUpdateWait(final int waitSeconds) { return this; } else if (!agent().getSqlConfig().getSqlAgentProvider().isStrictForUpdateType() && dialect.supportsForUpdate()) { - LOG.atWarn() + atWarn(LOG) .log("'FOR UPDATE WAIT' is not supported. Set 'FOR UPDATE' instead."); this.forUpdateType = ForUpdateType.NORMAL; return this; @@ -642,7 +642,7 @@ public SqlEntityQuery hint(final String hint) { if (dialect.supportsOptimizerHints()) { this.optimizerHints.add(hint); } else { - LOG.atWarn() + atWarn(LOG) .log("Optimizer Hints is not supported."); } return this; diff --git a/src/main/java/jp/co/future/uroborosql/UroboroSQL.java b/src/main/java/jp/co/future/uroborosql/UroboroSQL.java index e881b002..b6690e08 100644 --- a/src/main/java/jp/co/future/uroborosql/UroboroSQL.java +++ b/src/main/java/jp/co/future/uroborosql/UroboroSQL.java @@ -234,7 +234,7 @@ public SqlConfig build() { } - public static final class InternalConfig implements SqlConfig { + public static final class InternalConfig implements SqlConfig, SettingLogger { /** * コネクション提供クラス. */ @@ -296,12 +296,12 @@ public static final class InternalConfig implements SqlConfig { this.entityHandler = new DefaultEntityHandler(); if (clock == null) { this.clock = Clock.systemDefaultZone(); - SETTING_LOG.atWarn() + atWarn(SETTING_LOG) .log("SqlConfig - Clock was not set. Set SystemClock."); } else { this.clock = clock; } - SETTING_LOG.atInfo() + atInfo(SETTING_LOG) .setMessage("SqlConfig - Clock : {} has been selected.") .addArgument(this.clock) .log(); @@ -314,7 +314,7 @@ public static final class InternalConfig implements SqlConfig { } else { this.dialect = dialect; } - SETTING_LOG.atInfo() + atInfo(SETTING_LOG) .setMessage("SqlConfig - Dialect : {} has been selected.") .addArgument(() -> this.dialect.getClass().getSimpleName()) .log(); @@ -329,7 +329,7 @@ public static final class InternalConfig implements SqlConfig { } else { this.expressionParser = expressionParser; } - SETTING_LOG.atInfo() + atInfo(SETTING_LOG) .setMessage("SqlConfig - ExpressionParser : {} has been selected.") .addArgument(() -> this.expressionParser.getClass().getSimpleName()) .log(); diff --git a/src/main/java/jp/co/future/uroborosql/client/SqlREPL.java b/src/main/java/jp/co/future/uroborosql/client/SqlREPL.java index 7f7835e9..7242356c 100644 --- a/src/main/java/jp/co/future/uroborosql/client/SqlREPL.java +++ b/src/main/java/jp/co/future/uroborosql/client/SqlREPL.java @@ -199,7 +199,7 @@ private void initialize(final Terminal terminal) throws Exception { urls.add(Paths.get(sb.toString()).toUri().toURL()); } catch (Exception ex) { - REPL_LOG.atError() + atError(REPL_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); @@ -214,7 +214,7 @@ private void initialize(final Terminal terminal) throws Exception { try { DriverManager.registerDriver(new DriverShim(driver)); } catch (Exception ex) { - REPL_LOG.atError() + atError(REPL_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); @@ -311,7 +311,7 @@ private void listen(final Terminal terminal) throws IOException { } catch (UserInterruptException | EndOfFileException ex) { break; } catch (Exception ex) { - REPL_LOG.atError() + atError(REPL_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); diff --git a/src/main/java/jp/co/future/uroborosql/client/command/DescCommand.java b/src/main/java/jp/co/future/uroborosql/client/command/DescCommand.java index 4f08f854..2c93ed76 100644 --- a/src/main/java/jp/co/future/uroborosql/client/command/DescCommand.java +++ b/src/main/java/jp/co/future/uroborosql/client/command/DescCommand.java @@ -125,7 +125,7 @@ public boolean execute(final LineReader reader, final String[] parts, final SqlC } writer.println(); } catch (SQLException ex) { - REPL_LOG.atError() + atError(REPL_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); diff --git a/src/main/java/jp/co/future/uroborosql/client/command/GenerateCommand.java b/src/main/java/jp/co/future/uroborosql/client/command/GenerateCommand.java index 1d9ce7b6..28052641 100644 --- a/src/main/java/jp/co/future/uroborosql/client/command/GenerateCommand.java +++ b/src/main/java/jp/co/future/uroborosql/client/command/GenerateCommand.java @@ -74,7 +74,7 @@ public boolean execute(final LineReader reader, final String[] parts, final SqlC }).orElseGet(() -> sqlConfig.getEntityHandler().createSelectContext(agent, metadata, null, true)); writer.println(ctx.getSql()); } catch (SQLException ex) { - REPL_LOG.atError() + atError(REPL_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); diff --git a/src/main/java/jp/co/future/uroborosql/client/completer/TableNameCompleter.java b/src/main/java/jp/co/future/uroborosql/client/completer/TableNameCompleter.java index 0f481311..cbeca455 100644 --- a/src/main/java/jp/co/future/uroborosql/client/completer/TableNameCompleter.java +++ b/src/main/java/jp/co/future/uroborosql/client/completer/TableNameCompleter.java @@ -88,7 +88,7 @@ public void complete(final LineReader reader, final ParsedLine line, final List< } } } catch (SQLException ex) { - REPL_LOG.atError() + atError(REPL_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); diff --git a/src/main/java/jp/co/future/uroborosql/context/ExecutionContextImpl.java b/src/main/java/jp/co/future/uroborosql/context/ExecutionContextImpl.java index 3fb2bb4b..2a9f49d7 100644 --- a/src/main/java/jp/co/future/uroborosql/context/ExecutionContextImpl.java +++ b/src/main/java/jp/co/future/uroborosql/context/ExecutionContextImpl.java @@ -888,7 +888,7 @@ public ExecutionContext bindBatchParams(final PreparedStatement preparedStatemen preparedStatement.addBatch(); } if (!isSuppressLogging()) { - SQL_LOG.atDebug() + atDebug(SQL_LOG) .setMessage("{} items Added for batch process.") .addArgument(batchParameters.size()) .log(); @@ -923,7 +923,7 @@ public Map getOutParams(final CallableStatement callableStatemen parameterIndex++; } - SQL_LOG.atDebug() + atDebug(SQL_LOG) .setMessage("Stored procedure out parameter[{}]") .addArgument(out) .log(); diff --git a/src/main/java/jp/co/future/uroborosql/context/ExecutionContextProviderImpl.java b/src/main/java/jp/co/future/uroborosql/context/ExecutionContextProviderImpl.java index 2200becf..5529ff29 100644 --- a/src/main/java/jp/co/future/uroborosql/context/ExecutionContextProviderImpl.java +++ b/src/main/java/jp/co/future/uroborosql/context/ExecutionContextProviderImpl.java @@ -153,13 +153,13 @@ protected void makeConstParamMap(final Map paramMap, var newValue = new Parameter(fieldName, field.get(null)); var prevValue = paramMap.put(fieldName, newValue); if (prevValue != null) { - SETTING_LOG.atWarn() + atWarn(SETTING_LOG) .setMessage("Duplicate constant name. Constant name:{}, old value:{} destroy.") .addArgument(fieldName) .addArgument(prevValue.getValue()) .log(); } - SETTING_LOG.atInfo() + atInfo(SETTING_LOG) .setMessage("Constant [name:{}, value:{}] added to parameter.") .addArgument(fieldName) .addArgument(newValue.getValue()) @@ -177,7 +177,7 @@ protected void makeConstParamMap(final Map paramMap, } } } catch (IllegalArgumentException | IllegalAccessException | SecurityException ex) { - LOG.atError() + atError(LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); @@ -205,13 +205,13 @@ protected void makeEnumConstParamMap(final Map paramMap, var newValue = new Parameter(fieldName, value); var prevValue = paramMap.put(fieldName, newValue); if (prevValue != null) { - SETTING_LOG.atWarn() + atWarn(SETTING_LOG) .setMessage("Duplicate Enum name. Enum name:{}, old value:{} destroy.") .addArgument(fieldName) .addArgument(prevValue.getValue()) .log(); } - SETTING_LOG.atInfo() + atInfo(SETTING_LOG) .setMessage("Enum [name:{}, value:{}] added to parameter.") .addArgument(fieldName) .addArgument(newValue.getValue()) @@ -327,7 +327,7 @@ public ExecutionContextProvider removeBindParamMapper(final BindParameterMapper< var targetClass = Class.forName(className, true, Thread.currentThread().getContextClassLoader()); makeConstParamMap(paramMap, targetClass); } catch (ClassNotFoundException ex) { - LOG.atError() + atError(LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); @@ -361,14 +361,14 @@ public ExecutionContextProvider removeBindParamMapper(final BindParameterMapper< * @return クラスリスト */ @SuppressWarnings({ "unchecked", "rawtypes" }) - private static Set>> listUpEnumClasses(final String packageName) { + private Set>> listUpEnumClasses(final String packageName) { var resourceName = packageName.replace('.', '/'); var classLoader = Thread.currentThread().getContextClassLoader(); List roots; try { roots = Collections.list(classLoader.getResources(resourceName)); } catch (IOException ex) { - LOG.atError() + atError(LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); @@ -381,7 +381,7 @@ private static Set>> listUpEnumClasses(final String pack try { classes.addAll(findEnumClassesWithFile(packageName, Paths.get(root.toURI()))); } catch (URISyntaxException ex) { - LOG.atError() + atError(LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); @@ -391,7 +391,7 @@ private static Set>> listUpEnumClasses(final String pack try (var jarFile = ((JarURLConnection) root.openConnection()).getJarFile()) { classes.addAll(findEnumClassesWithJar(packageName, jarFile)); } catch (IOException ex) { - LOG.atError() + atError(LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); @@ -411,7 +411,7 @@ private static Set>> listUpEnumClasses(final String pack * @throws ClassNotFoundException エラー * @throws IOException */ - private static Set> findEnumClassesWithFile(final String packageName, final Path dir) { + private Set> findEnumClassesWithFile(final String packageName, final Path dir) { var prefix = packageName + "."; try (var stream = Files.walk(dir)) { return stream.filter(entry -> entry.getFileName().toString().endsWith(".class")) @@ -424,7 +424,7 @@ private static Set> findEnumClassesWithFile(final String packageName, f .filter(Objects::nonNull) .collect(Collectors.toSet()); } catch (IOException ex) { - LOG.atError() + atError(LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); @@ -441,7 +441,7 @@ private static Set> findEnumClassesWithFile(final String packageName, f * @throws ClassNotFoundException エラー * @throws IOException */ - private static Collection> findEnumClassesWithJar(final String packageName, + private Collection> findEnumClassesWithJar(final String packageName, final JarFile jarFile) { var resourceName = packageName.replace('.', '/'); return Collections.list(jarFile.entries()).stream() @@ -460,14 +460,14 @@ private static Collection> findEnumClassesWithJar(final Strin * @param className クラス名 * @return ロードしたEnumクラス */ - private static Optional> loadEnum(final String className) { + private Optional> loadEnum(final String className) { try { var type = Class.forName(className, true, Thread.currentThread().getContextClassLoader()); if (type.isEnum()) { return Optional.of(type); } } catch (ClassNotFoundException ex) { - LOG.atError() + atError(LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); diff --git a/src/main/java/jp/co/future/uroborosql/coverage/CoberturaCoverageHandler.java b/src/main/java/jp/co/future/uroborosql/coverage/CoberturaCoverageHandler.java index 7ad8459e..296f84cc 100644 --- a/src/main/java/jp/co/future/uroborosql/coverage/CoberturaCoverageHandler.java +++ b/src/main/java/jp/co/future/uroborosql/coverage/CoberturaCoverageHandler.java @@ -254,7 +254,7 @@ public synchronized void accept(final CoverageData coverageData) { sqlCoverage = new SqlCoverage(coverageData.getSqlName(), coverageData.getSql(), coverageData.getMd5(), sourcesDirPath, map.size()); } catch (IOException ex) { - COVERAGE_LOG.atError() + atError(COVERAGE_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); @@ -272,7 +272,7 @@ public synchronized void onSqlAgentClose() { try { write(); } catch (Exception ex) { - COVERAGE_LOG.atError() + atError(COVERAGE_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); @@ -285,7 +285,7 @@ private void init() { try { write(); } catch (Exception ex) { - COVERAGE_LOG.atError() + atError(COVERAGE_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); diff --git a/src/main/java/jp/co/future/uroborosql/coverage/CoverageData.java b/src/main/java/jp/co/future/uroborosql/coverage/CoverageData.java index faddc4d7..183dc809 100644 --- a/src/main/java/jp/co/future/uroborosql/coverage/CoverageData.java +++ b/src/main/java/jp/co/future/uroborosql/coverage/CoverageData.java @@ -62,7 +62,7 @@ private String makeMd5(final String original) { } return builder.toString(); } catch (Exception ex) { - COVERAGE_LOG.atError() + atError(COVERAGE_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); diff --git a/src/main/java/jp/co/future/uroborosql/coverage/reports/html/HtmlReportCoverageHandler.java b/src/main/java/jp/co/future/uroborosql/coverage/reports/html/HtmlReportCoverageHandler.java index b24995ff..901c48dd 100644 --- a/src/main/java/jp/co/future/uroborosql/coverage/reports/html/HtmlReportCoverageHandler.java +++ b/src/main/java/jp/co/future/uroborosql/coverage/reports/html/HtmlReportCoverageHandler.java @@ -110,7 +110,7 @@ private void writeHtml() { Files.copy(src, Paths.get(this.reportDirPath + "/" + filename), StandardCopyOption.REPLACE_EXISTING); } catch (IOException ex) { - COVERAGE_LOG.atError() + atError(COVERAGE_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); @@ -130,7 +130,7 @@ private void writeHtml() { writeSuffix(writer); } } catch (IOException ex) { - COVERAGE_LOG.atError() + atError(COVERAGE_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); diff --git a/src/main/java/jp/co/future/uroborosql/coverage/reports/html/SqlCoverageReport.java b/src/main/java/jp/co/future/uroborosql/coverage/reports/html/SqlCoverageReport.java index def96683..9e847f01 100644 --- a/src/main/java/jp/co/future/uroborosql/coverage/reports/html/SqlCoverageReport.java +++ b/src/main/java/jp/co/future/uroborosql/coverage/reports/html/SqlCoverageReport.java @@ -124,7 +124,7 @@ void writeHtml() { writeSuffix(writer); } } catch (IOException ex) { - COVERAGE_LOG.atError() + atError(COVERAGE_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); diff --git a/src/main/java/jp/co/future/uroborosql/event/subscriber/AbstractSecretColumnEventSubscriber.java b/src/main/java/jp/co/future/uroborosql/event/subscriber/AbstractSecretColumnEventSubscriber.java index e428f033..d026a6b9 100644 --- a/src/main/java/jp/co/future/uroborosql/event/subscriber/AbstractSecretColumnEventSubscriber.java +++ b/src/main/java/jp/co/future/uroborosql/event/subscriber/AbstractSecretColumnEventSubscriber.java @@ -114,7 +114,7 @@ public void initialize() { KeyStore store; try { if (ObjectUtils.isBlank(getKeyStoreFilePath())) { - SETTING_LOG.atError() + atError(SETTING_LOG) .setMessage("Invalid KeyStore file path. Path:{}") .addArgument(getKeyStoreFilePath()) .log(); @@ -123,7 +123,7 @@ public void initialize() { } var storeFile = toPath(getKeyStoreFilePath()); if (!Files.exists(storeFile)) { - SETTING_LOG.atError() + atError(SETTING_LOG) .setMessage("Not found KeyStore file path. Path:{}") .addArgument(getKeyStoreFilePath()) .log(); @@ -131,7 +131,7 @@ public void initialize() { return; } if (Files.isDirectory(storeFile)) { - SETTING_LOG.atError() + atError(SETTING_LOG) .setMessage("Invalid KeyStore file path. Path:{}") .addArgument(getKeyStoreFilePath()) .log(); @@ -139,14 +139,14 @@ public void initialize() { return; } if (ObjectUtils.isBlank(getStorePassword())) { - SETTING_LOG.atError() + atError(SETTING_LOG) .setMessage("Invalid password for access KeyStore.") .log(); setSkip(true); return; } if (ObjectUtils.isBlank(getAlias())) { - SETTING_LOG.atError() + atError(SETTING_LOG) .setMessage("No alias for access KeyStore.") .log(); setSkip(true); @@ -170,7 +170,7 @@ public void initialize() { encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey); useIV = encryptCipher.getIV() != null; } catch (Exception ex) { - SETTING_LOG.atError() + atError(SETTING_LOG) .setMessage("Failed to acquire secret key.") .setCause(ex) .log(); @@ -209,7 +209,7 @@ void beforeSetParameter(final BeforeSetParameterEvent evt) { new Parameter(key, encrypt(encryptCipher, secretKey, objStr))); } } catch (Exception ex) { - EVENT_LOG.atWarn() + atWarn(EVENT_LOG) .setMessage("Encrypt Exception key:{}") .addArgument(key) .log(); @@ -231,7 +231,7 @@ void afterSqlQuery(final AfterSqlQueryEvent evt) { evt.setResultSet(new SecretResultSet(evt.getResultSet(), this.createDecryptor(), getCryptColumnNames(), getCharset())); } catch (Exception ex) { - EVENT_LOG.atError() + atError(EVENT_LOG) .setMessage("Failed to create SecretResultSet.") .setCause(ex) .log(); @@ -391,7 +391,7 @@ public T setCharset(final String charset) { this.charset = Charset.forName(charset); } catch (UnsupportedCharsetException ex) { this.charset = StandardCharsets.UTF_8; - SETTING_LOG.atError() + atError(SETTING_LOG) .setMessage( "The specified character set could not be converted to {}. Set the default character set({}).") .addArgument(charset) diff --git a/src/main/java/jp/co/future/uroborosql/event/subscriber/AuditLogEventSubscriber.java b/src/main/java/jp/co/future/uroborosql/event/subscriber/AuditLogEventSubscriber.java index d16df0ae..6e8c11db 100644 --- a/src/main/java/jp/co/future/uroborosql/event/subscriber/AuditLogEventSubscriber.java +++ b/src/main/java/jp/co/future/uroborosql/event/subscriber/AuditLogEventSubscriber.java @@ -24,7 +24,7 @@ * @since v1.0.0 * */ -public class AuditLogEventSubscriber extends EventSubscriber { +public class AuditLogEventSubscriber extends EventSubscriber implements EventLogger { /** イベントロガー */ private static final Logger EVENT_LOG = EventLogger.getEventLogger("auditlog"); @@ -79,7 +79,7 @@ void afterSqlQuery(final AfterSqlQueryEvent evt) { var userName = getParam(evt.getExecutionContext(), userNameKey, DEFAULT_USER_NAME); var funcId = getParam(evt.getExecutionContext(), funcIdKey, DEFAULT_FUNC_ID); var reportRowCount = rowCount; - EVENT_LOG.atDebug() + atDebug(EVENT_LOG) .setMessage("AuditData: {}") .addArgument(() -> new AuditData(userName, funcId, @@ -93,7 +93,7 @@ void afterSqlQuery(final AfterSqlQueryEvent evt) { void afterSqlUpdate(final AfterSqlUpdateEvent evt) { var userName = getParam(evt.getExecutionContext(), userNameKey, DEFAULT_USER_NAME); var funcId = getParam(evt.getExecutionContext(), funcIdKey, DEFAULT_FUNC_ID); - EVENT_LOG.atDebug() + atDebug(EVENT_LOG) .setMessage("AuditData: {}") .addArgument(() -> new AuditData(userName, funcId, @@ -107,7 +107,7 @@ void afterSqlUpdate(final AfterSqlUpdateEvent evt) { void afterSqlBatch(final AfterSqlBatchEvent evt) { var userName = getParam(evt.getExecutionContext(), userNameKey, DEFAULT_USER_NAME); var funcId = getParam(evt.getExecutionContext(), funcIdKey, DEFAULT_FUNC_ID); - EVENT_LOG.atDebug() + atDebug(EVENT_LOG) .setMessage("AuditData: {}") .addArgument(() -> { var rowCount = -1; diff --git a/src/main/java/jp/co/future/uroborosql/event/subscriber/DebugEventSubscriber.java b/src/main/java/jp/co/future/uroborosql/event/subscriber/DebugEventSubscriber.java index c11d86ba..ba75e323 100644 --- a/src/main/java/jp/co/future/uroborosql/event/subscriber/DebugEventSubscriber.java +++ b/src/main/java/jp/co/future/uroborosql/event/subscriber/DebugEventSubscriber.java @@ -25,7 +25,7 @@ * @author H.Sugimoto * @since v1.0.0 */ -public class DebugEventSubscriber extends EventSubscriber { +public class DebugEventSubscriber extends EventSubscriber implements EventLogger { /** ロガー */ private static final Logger EVENT_LOG = EventLogger.getEventLogger("debug"); @@ -42,7 +42,7 @@ public void initialize() { void afterBeginTransaction(final AfterBeginTransactionEvent evt) { try { - EVENT_LOG.atDebug() + atDebug(EVENT_LOG) .setMessage("Begin Transaction - connection:{}, requiredNew:{}, transactionLevel:{}, occurredOn:{}") .addArgument(evt.getTransactionContext().getConnection()) .addArgument(evt.isRequiredNew()) @@ -50,7 +50,7 @@ void afterBeginTransaction(final AfterBeginTransactionEvent evt) { .addArgument(evt.occurredOn()) .log(); } catch (SQLException ex) { - EVENT_LOG.atError() + atError(EVENT_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); @@ -59,7 +59,7 @@ void afterBeginTransaction(final AfterBeginTransactionEvent evt) { void beforeEndTransaction(final BeforeEndTransactionEvent evt) { try { - EVENT_LOG.atDebug() + atDebug(EVENT_LOG) .setMessage( "End Transaction - connection:{}, requiredNew:{}, transactionLevel:{}, result:{}, occurredOn:{}") .addArgument(evt.getTransactionContext().getConnection()) @@ -69,7 +69,7 @@ void beforeEndTransaction(final BeforeEndTransactionEvent evt) { .addArgument(evt.occurredOn()) .log(); } catch (SQLException ex) { - EVENT_LOG.atError() + atError(EVENT_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); @@ -77,14 +77,14 @@ void beforeEndTransaction(final BeforeEndTransactionEvent evt) { } void beforeSetParameter(final BeforeSetParameterEvent evt) { - EVENT_LOG.atDebug() + atDebug(EVENT_LOG) .setMessage("Before Set Parameter - Parameter:{}") .addArgument(evt.getParameter()) .log(); } void afterGetOutParameter(final AfterGetOutParameterEvent evt) { - EVENT_LOG.atDebug() + atDebug(EVENT_LOG) .setMessage("After Get OutParameter - key:{}, value:{}. parameterIndex:{}") .addArgument(evt.getKey()) .addArgument(evt.getValue()) @@ -93,18 +93,18 @@ void afterGetOutParameter(final AfterGetOutParameterEvent evt) { } void afterSqlQuery(final AfterSqlQueryEvent evt) { - EVENT_LOG.atDebug() + atDebug(EVENT_LOG) .setMessage("Execute Query - sqlName:{} executed.") .addArgument(evt.getExecutionContext().getSqlName()) .log(); - EVENT_LOG.atTrace() + atTrace(EVENT_LOG) .setMessage("Execute Query sql:{}") .addArgument(evt.getPreparedStatement()) .log(); } void afterSqlUpdate(final AfterSqlUpdateEvent evt) { - EVENT_LOG.atDebug() + atDebug(EVENT_LOG) .setMessage("Execute Update - sqlName:{} executed. Count:{} items.") .addArgument(evt.getExecutionContext().getSqlName()) .addArgument(evt.getCount()) @@ -112,14 +112,14 @@ void afterSqlUpdate(final AfterSqlUpdateEvent evt) { } void afterSqlBatch(final AfterSqlBatchEvent evt) { - EVENT_LOG.atDebug() + atDebug(EVENT_LOG) .setMessage("Execute Update - sqlName:{} executed. Results:{}") .addArgument(evt.getExecutionContext().getSqlName()) .addArgument(() -> { try { return new int[] { evt.getPreparedStatement().getUpdateCount() }; } catch (SQLException ex) { - EVENT_LOG.atError() + atError(EVENT_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); diff --git a/src/main/java/jp/co/future/uroborosql/event/subscriber/DumpResultEventSubscriber.java b/src/main/java/jp/co/future/uroborosql/event/subscriber/DumpResultEventSubscriber.java index c9541711..dd577841 100644 --- a/src/main/java/jp/co/future/uroborosql/event/subscriber/DumpResultEventSubscriber.java +++ b/src/main/java/jp/co/future/uroborosql/event/subscriber/DumpResultEventSubscriber.java @@ -36,7 +36,7 @@ * @since v1.0.0 * */ -public class DumpResultEventSubscriber extends EventSubscriber { +public class DumpResultEventSubscriber extends EventSubscriber implements EventLogger { /** 改行文字 */ private static final String LINE_SEPARATOR = System.lineSeparator(); @@ -60,13 +60,13 @@ public void initialize() { void afterSqlQuery(final AfterSqlQueryEvent evt) { try { if (evt.getResultSet().getType() == ResultSet.TYPE_FORWARD_ONLY) { - EVENT_LOG.atWarn() + atWarn(EVENT_LOG) .log("ResultSet type is TYPE_FORWARD_ONLY. DumpResultEventSubscriber use ResultSet#beforeFirst(). Please Set TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE."); } - EVENT_LOG.atDebug() + atDebug(EVENT_LOG) .log(() -> displayResult(evt.getResultSet()).toString()); } catch (SQLException ex) { - EVENT_LOG.atWarn() + atWarn(EVENT_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); @@ -156,7 +156,7 @@ private StringBuilder displayResult(final ResultSet rs) { return builder; } catch (Exception ex) { - EVENT_LOG.atError() + atError(EVENT_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); diff --git a/src/main/java/jp/co/future/uroborosql/expr/ognl/OgnlExpressionParser.java b/src/main/java/jp/co/future/uroborosql/expr/ognl/OgnlExpressionParser.java index f79688b3..62caa194 100644 --- a/src/main/java/jp/co/future/uroborosql/expr/ognl/OgnlExpressionParser.java +++ b/src/main/java/jp/co/future/uroborosql/expr/ognl/OgnlExpressionParser.java @@ -13,6 +13,7 @@ import jp.co.future.uroborosql.exception.ExpressionRuntimeException; import jp.co.future.uroborosql.expr.AbstractExpressionParser; import jp.co.future.uroborosql.expr.Expression; +import jp.co.future.uroborosql.log.ParserLogger; import jp.co.future.uroborosql.parser.TransformContext; import jp.co.future.uroborosql.utils.SqlFunction; import ognl.ASTProperty; @@ -64,7 +65,7 @@ public Expression parse(final String expression) { * * @author H.Sugimoto */ - private static class OgnlExpression implements Expression { + private static class OgnlExpression implements Expression, ParserLogger { private final Object expression; /** @@ -112,7 +113,7 @@ public StringBuilder dumpNode(final Object context) { .append("],"); } catch (OgnlException ex) { // ダンプ処理でシステムが止まっては困るのでログ出力して握りつぶす - PARSER_LOG.atWarn() + atWarn(PARSER_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); diff --git a/src/main/java/jp/co/future/uroborosql/expr/spel/SpelExpressionParser.java b/src/main/java/jp/co/future/uroborosql/expr/spel/SpelExpressionParser.java index c0a6fee8..820cfb62 100644 --- a/src/main/java/jp/co/future/uroborosql/expr/spel/SpelExpressionParser.java +++ b/src/main/java/jp/co/future/uroborosql/expr/spel/SpelExpressionParser.java @@ -135,7 +135,7 @@ public StringBuilder dumpNode(final Object context) { .append("],"); } catch (EvaluationException ex) { // ダンプ処理でシステムが止まっては困るのでログ出力して握りつぶす - PARSER_LOG.atWarn() + atWarn(PARSER_LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); diff --git a/src/main/java/jp/co/future/uroborosql/log/LoggerBase.java b/src/main/java/jp/co/future/uroborosql/log/LoggerBase.java index 85f8fedf..4b663290 100644 --- a/src/main/java/jp/co/future/uroborosql/log/LoggerBase.java +++ b/src/main/java/jp/co/future/uroborosql/log/LoggerBase.java @@ -6,36 +6,102 @@ */ package jp.co.future.uroborosql.log; +import org.slf4j.Logger; import org.slf4j.MDC; +import org.slf4j.spi.LoggingEventBuilder; +import org.slf4j.spi.NOPLoggingEventBuilder; +/** + * ログ出力する際の共通親インタフェース + */ public interface LoggerBase { /** すべてのログ出力を抑止するためのMDCキー */ - String SUPPRESS_LOG_OUTPUT = "SuppressLogOutput"; + String SUPPRESS_LOG_OUTPUT = "UroboroSQL_SuppressLogOutput"; /** パラメータログ出力を抑止するためのMDCキー */ - String SUPPRESS_PARAMETER_LOG_OUTPUT = "SuppressParameterLogOutput"; + String SUPPRESS_PARAMETER_LOG_OUTPUT = "UroboroSQL_SuppressParameterLogOutput"; + /** + * Uroborosqlが出力するログを抑止する. + */ default void suppressLogging() { MDC.put(SUPPRESS_LOG_OUTPUT, SUPPRESS_LOG_OUTPUT); } + /** + * Uroborosqlが出力するログが抑止されているかを返す. + * @return ログが抑止されている場合true + */ default boolean isSuppressLogging() { return MDC.get(SUPPRESS_LOG_OUTPUT) != null; } + /** + * Uroborosqlが出力するログが抑止されている場合、抑止を終了する. + */ default void releaseLogging() { MDC.remove(SUPPRESS_LOG_OUTPUT); } + /** + * Uroborosqlが出力するパラメータログを抑止する. + */ default void suppressParameterLogging() { MDC.put(SUPPRESS_PARAMETER_LOG_OUTPUT, SUPPRESS_PARAMETER_LOG_OUTPUT); } + /** + * Uroborosqlが出力するパラメータログが抑止されているかを返す. + * @return パラメータログが抑止されている場合true + */ default boolean isSuppressParameterLogging() { return MDC.get(SUPPRESS_PARAMETER_LOG_OUTPUT) != null; } + /** + * Uroborosqlが出力するパラメータログが抑止されている場合、抑止を終了する. + */ default void releaseParameterLogging() { MDC.remove(SUPPRESS_PARAMETER_LOG_OUTPUT); } + + default LoggingEventBuilder atError(final Logger logger) { + if (!isSuppressLogging()) { + return logger.atError(); + } else { + return NOPLoggingEventBuilder.singleton(); + } + } + + default LoggingEventBuilder atWarn(final Logger logger) { + if (!isSuppressLogging()) { + return logger.atWarn(); + } else { + return NOPLoggingEventBuilder.singleton(); + } + } + + default LoggingEventBuilder atInfo(final Logger logger) { + if (!isSuppressLogging()) { + return logger.atInfo(); + } else { + return NOPLoggingEventBuilder.singleton(); + } + } + + default LoggingEventBuilder atDebug(final Logger logger) { + if (!isSuppressLogging()) { + return logger.atDebug(); + } else { + return NOPLoggingEventBuilder.singleton(); + } + } + + default LoggingEventBuilder atTrace(final Logger logger) { + if (!isSuppressLogging()) { + return logger.atTrace(); + } else { + return NOPLoggingEventBuilder.singleton(); + } + } } diff --git a/src/main/java/jp/co/future/uroborosql/node/IfNode.java b/src/main/java/jp/co/future/uroborosql/node/IfNode.java index d75980ae..9a3b4011 100644 --- a/src/main/java/jp/co/future/uroborosql/node/IfNode.java +++ b/src/main/java/jp/co/future/uroborosql/node/IfNode.java @@ -97,7 +97,7 @@ public void accept(final TransformContext transformContext) { || Boolean.FALSE.toString().equalsIgnoreCase(expression)) { // 単純なBoolean評価の場合はログを出力しない } else { - PARSER_LOG.atInfo() + atInfo(PARSER_LOG) .setMessage("Evaluation Expression:[{}], Result:[{}], Parameter:[{}]") .addArgument(expression) .addArgument(resultValue) diff --git a/src/main/java/jp/co/future/uroborosql/parameter/Parameter.java b/src/main/java/jp/co/future/uroborosql/parameter/Parameter.java index 1db839fc..180afc29 100644 --- a/src/main/java/jp/co/future/uroborosql/parameter/Parameter.java +++ b/src/main/java/jp/co/future/uroborosql/parameter/Parameter.java @@ -93,7 +93,7 @@ public Parameter createSubParameter(final String propertyName) { if (value instanceof Map) { subValue = ((Map) value).get(propertyName); if (subValue == null) { - LOG.atWarn() + atWarn(LOG) .setMessage("Set subparameter value to NULL because property can not be accessed.[{}]") .addArgument(subParameterName) .log(); @@ -112,14 +112,14 @@ public Parameter createSubParameter(final String propertyName) { .getMethod(prefix + ObjectUtils.capitalize(propertyName)); subValue = method.invoke(value); } catch (Exception ex2) { - LOG.atWarn() + atWarn(LOG) .setMessage("Set subparameter value to NULL because property can not be accessed.[{}]") .addArgument(subParameterName) .setCause(ex2) .log(); } } catch (Exception ex) { - LOG.atWarn() + atWarn(LOG) .setMessage("Set subparameter value to NULL because property can not be accessed.[{}]") .addArgument(subParameterName) .setCause(ex) @@ -182,7 +182,7 @@ protected int setInParameter(final PreparedStatement preparedStatement, final in */ protected void parameterLog(final int index) { if (SQL_LOG.isInfoEnabled() && !isSuppressParameterLogging()) { - SQL_LOG.atInfo() + atInfo(SQL_LOG) .setMessage("Set the parameter.[INDEX[{}], {}]") .addArgument(index) .addArgument(this) diff --git a/src/main/java/jp/co/future/uroborosql/store/SqlResourceManagerImpl.java b/src/main/java/jp/co/future/uroborosql/store/SqlResourceManagerImpl.java index d16a6f61..ab2f86bb 100644 --- a/src/main/java/jp/co/future/uroborosql/store/SqlResourceManagerImpl.java +++ b/src/main/java/jp/co/future/uroborosql/store/SqlResourceManagerImpl.java @@ -44,6 +44,7 @@ import jp.co.future.uroborosql.dialect.Dialect; import jp.co.future.uroborosql.exception.UroborosqlRuntimeException; +import jp.co.future.uroborosql.log.ServiceLogger; import jp.co.future.uroborosql.utils.ObjectUtils; /** @@ -228,7 +229,7 @@ public void initialize() { try { watcher = FileSystems.getDefault().newWatchService(); } catch (IOException ex) { - LOG.atError() + atError(LOG) .setMessage("Can't start watcher service.") .setCause(ex) .log(); @@ -274,11 +275,11 @@ private void watchPath() { try { key = watcher.take(); } catch (InterruptedException ex) { - LOG.atDebug() + atDebug(LOG) .log("WatchService caught InterruptedException."); break; } catch (Throwable ex) { - LOG.atError() + atError(LOG) .setMessage("Unexpected exception occurred.") .setCause(ex) .log(); @@ -298,7 +299,7 @@ private void watchPath() { var dir = watchDirs.get(key); var path = dir.resolve(evt.context()); - LOG.atDebug() + atDebug(LOG) .setMessage("file changed.({}). path={}") .addArgument(kind.name()) .addArgument(path) @@ -413,7 +414,7 @@ protected void generateSqlInfos() { } else if (SCHEME_JAR.equalsIgnoreCase(scheme)) { traverseJar(url, loadPathSlash); } else { - LOG.atWarn() + atWarn(LOG) .setMessage("Unsupported scheme. scheme : {}, url : {}") .addArgument(scheme) .addArgument(url) @@ -422,7 +423,7 @@ protected void generateSqlInfos() { } } } catch (IOException | URISyntaxException ex) { - LOG.atError() + atError(LOG) .setMessage("Can't load sql files.") .setCause(ex) .log(); @@ -538,7 +539,7 @@ private boolean validPath(final Path path) { * @param remove 削除指定。trueの場合、指定のPathを除外する。falseの場合は格納する */ private void traverseFile(final Path path, final boolean watch, final boolean remove) { - LOG.atTrace() + atTrace(LOG) .setMessage("traverseFile start. path : {}, watch : {}, remove : {}.") .addArgument(path) .addArgument(watch) @@ -576,7 +577,7 @@ private void traverseFile(final Path path, final boolean watch, final boolean re */ @SuppressWarnings("resource") private void traverseJar(final URL url, final String loadPath) { - LOG.atTrace() + atTrace(LOG) .setMessage("traverseJar start. url : {}, loadPath : {}.") .addArgument(url) .addArgument(loadPath) @@ -621,7 +622,7 @@ private void traverseJar(final URL url, final String loadPath) { /** * SQLファイルの情報を保持するオブジェクト */ - public static class SqlInfo { + public static class SqlInfo implements ServiceLogger { /** キーとなるsqlName */ private final String sqlName; /** 対象のDialect */ @@ -649,7 +650,7 @@ public static class SqlInfo { final List loadPaths, final Dialect dialect, final Charset charset) { - LOG.atTrace() + atTrace(LOG) .setMessage("SqlInfo - sqlName : {}, path : {}, dialect : {}, charset : {}.") .addArgument(sqlName) .addArgument(path) @@ -670,12 +671,12 @@ public static class SqlInfo { * @param path 対象のPath * @return 最終更新日時 */ - private static FileTime getLastModifiedTime(final Path path) { + private FileTime getLastModifiedTime(final Path path) { if (SCHEME_FILE.equalsIgnoreCase(path.toUri().getScheme())) { try { return Files.getLastModifiedTime(path); } catch (IOException ex) { - LOG.atWarn() + atWarn(LOG) .setMessage("Can't get lastModifiedTime. path:{}") .addArgument(path) .setCause(ex) @@ -738,7 +739,7 @@ private String getSqlBody() { try { var body = new String(Files.readAllBytes(path), charset); sqlBody = formatSqlBody(body); - LOG.atDebug() + atDebug(LOG) .setMessage("Loaded SQL template.[{}]") .addArgument(path) .log(); @@ -762,7 +763,7 @@ private String getSqlBody() { var body = reader.lines() .collect(Collectors.joining(System.lineSeparator())); sqlBody = formatSqlBody(body); - LOG.atDebug() + atDebug(LOG) .setMessage("Loaded SQL template.[{}]") .addArgument(path) .log(); @@ -896,7 +897,7 @@ private SqlInfo computePath(final Path newPath, final boolean remove) { var currentTimeStamp = getLastModifiedTime(currentPath); if (!oldPath.equals(currentPath)) { replaceFlag = true; - LOG.atDebug() + atDebug(LOG) .setMessage("sql file switched. sqlName={}, oldPath={}, newPath={}, lastModified={}") .addArgument(sqlName) .addArgument(oldPath) @@ -906,7 +907,7 @@ private SqlInfo computePath(final Path newPath, final boolean remove) { } else { if (!this.lastModified.equals(currentTimeStamp)) { replaceFlag = true; - LOG.atDebug() + atDebug(LOG) .setMessage("sql file changed. sqlName={}, path={}, lastModified={}") .addArgument(sqlName) .addArgument(currentPath) diff --git a/src/main/java/jp/co/future/uroborosql/tx/LocalTransactionContext.java b/src/main/java/jp/co/future/uroborosql/tx/LocalTransactionContext.java index 53666554..9c3f8ff8 100644 --- a/src/main/java/jp/co/future/uroborosql/tx/LocalTransactionContext.java +++ b/src/main/java/jp/co/future/uroborosql/tx/LocalTransactionContext.java @@ -360,7 +360,7 @@ public void close() { if (connection != null && !connection.isClosed()) { connection.close(); } else { - LOG.atWarn() + atWarn(LOG) .log("Connection close was skipped because the connection was already closed."); } } catch (SQLException ex) { diff --git a/src/main/java/jp/co/future/uroborosql/tx/LocalTransactionManager.java b/src/main/java/jp/co/future/uroborosql/tx/LocalTransactionManager.java index 664b4279..b2a387e0 100644 --- a/src/main/java/jp/co/future/uroborosql/tx/LocalTransactionManager.java +++ b/src/main/java/jp/co/future/uroborosql/tx/LocalTransactionManager.java @@ -183,7 +183,7 @@ public Connection getConnection() { try { return currentTxContext(true).orElseThrow().getConnection(); } catch (SQLException ex) { - LOG.atError() + atError(LOG) .setMessage(ex.getMessage()) .setCause(ex) .log(); diff --git a/src/test/java/jp/co/future/uroborosql/SqlQueryTest.java b/src/test/java/jp/co/future/uroborosql/SqlQueryTest.java index d02253ed..4ff14697 100644 --- a/src/test/java/jp/co/future/uroborosql/SqlQueryTest.java +++ b/src/test/java/jp/co/future/uroborosql/SqlQueryTest.java @@ -17,6 +17,7 @@ import java.sql.Blob; import java.sql.Clob; import java.sql.NClob; +import java.sql.SQLException; import java.sql.Time; import java.sql.Timestamp; import java.time.DayOfWeek; @@ -94,6 +95,49 @@ void testQuery() throws Exception { assertFalse(rs.next(), "結果が複数件です。"); } + /** + * クエリ実行処理のテストケース。(ログ抑止 + */ + @Test + void testQueryWithSuppressLog() throws Exception { + // 事前条件 + cleanInsert(Paths.get("src/test/resources/data/setup", "testExecuteQuery.ltsv")); + + agent.required(() -> { + agent.suppressLogging(); + try (var rs = agent.query("example/select_product") + .param("product_id", List.of(new BigDecimal("0"), new BigDecimal("2"))) + .resultSet()) { + assertNotNull(rs, "ResultSetが取得できませんでした。"); + assertTrue(rs.next(), "結果が0件です。"); + assertEquals("0", rs.getString("PRODUCT_ID")); + assertEquals("商品名0", rs.getString("PRODUCT_NAME")); + assertEquals("ショウヒンメイゼロ", rs.getString("PRODUCT_KANA_NAME")); + assertEquals("1234567890123", rs.getString("JAN_CODE")); + assertEquals("0番目の商品", rs.getString("PRODUCT_DESCRIPTION")); + assertFalse(rs.next(), "結果が複数件です。"); + } catch (SQLException ex) { + fail(ex); + } + + agent.releaseLogging(); + try (var rs = agent.query("example/select_product") + .param("product_id", List.of(new BigDecimal("0"), new BigDecimal("2"))) + .resultSet()) { + assertNotNull(rs, "ResultSetが取得できませんでした。"); + assertTrue(rs.next(), "結果が0件です。"); + assertEquals("0", rs.getString("PRODUCT_ID")); + assertEquals("商品名0", rs.getString("PRODUCT_NAME")); + assertEquals("ショウヒンメイゼロ", rs.getString("PRODUCT_KANA_NAME")); + assertEquals("1234567890123", rs.getString("JAN_CODE")); + assertEquals("0番目の商品", rs.getString("PRODUCT_DESCRIPTION")); + assertFalse(rs.next(), "結果が複数件です。"); + } catch (SQLException ex) { + fail(ex); + } + }); + } + /** * クエリ実行処理のテストケース。 */ diff --git a/src/test/java/jp/co/future/uroborosql/expr/AbstractExpressionParserTest.java b/src/test/java/jp/co/future/uroborosql/expr/AbstractExpressionParserTest.java index 4cb394ac..b327fda7 100644 --- a/src/test/java/jp/co/future/uroborosql/expr/AbstractExpressionParserTest.java +++ b/src/test/java/jp/co/future/uroborosql/expr/AbstractExpressionParserTest.java @@ -197,7 +197,7 @@ void testCollectParams() { @Test void testPerformance() { if (PERFORMANCE_LOG.isDebugEnabled()) { - PERFORMANCE_LOG.atDebug() + atDebug(PERFORMANCE_LOG) .setMessage("\r\n{}") .addArgument(this::getPerformanceHeader) .log(); @@ -213,7 +213,7 @@ void testPerformance() { var expr = parser.parse("param" + j + " == null"); expr.getValue(context); } - PERFORMANCE_LOG.atDebug() + atDebug(PERFORMANCE_LOG) .setMessage("No{}:{}") .addArgument(i) .addArgument(