# SQLStatementLogger.java

    /*
    ** Module   : SQLStatementLogger.java
    ** Abstract : Logs information about SQL statements
    **
    ** Copyright (c) 2020-2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------------Description---------------------------------------
    ** 001 OM  20200616 First revision with basic usage.
    ** 002 OM  20200929 Added flag for globally enabling the logger. Default is disabled.
    ** 003 RAA 20221221 Added option for measuring the time of execution and stack trace for a SQL query.
    **     RFB 20221223 Minor javadoc repair.
    ** 004 OM  20230323 Replaced + concatenation with append().
    ** 005 RAA 20230518 Replaced lambdas with functional interfaces when logging a SQL query.
    **                  Added option to ignore logging that comes from the meta database.
    **                  Logging will now display the batch size as well.
    ** 006 RAA 20230522 This class now extends PersistenceLogger.
    ** 007 RAA 20230607 SQLs are now executed through SQLExecutor instead of SQLStatementLogger if logging
    **                  is not intended.
    **     RAA 20230608 Integrated configuration for each database.
    **     RAA 20230609 Replaced Configuration with SQLStatementLoggerConfiguration.
    ** 008 RAA 20230615 Logging a statement takes into consideration if sensible data is allowed to be printed.
    **     RAA 20230615 Replaced SENSIBLE keyword with SENSITIVE.
    **     RAA 20230615 log function now receives the SQL as a parameter.
    ** 009 RAA 20230724 The statements are no longer executed here, they are only logged.
    ** 010 ICP 20240419 Refactored log method to support logging in a h2 database as well as a file.
    **     ICP 20240813 log method now uses CentralLoggerFile to write the logs.
    */

    /*
    ** This program is free software: you can redistribute it and/or modify
    ** it under the terms of the GNU Affero General Public License as
    ** published by the Free Software Foundation, either version 3 of the
    ** License, or (at your option) any later version.
    **
    ** This program is distributed in the hope that it will be useful,
    ** but WITHOUT ANY WARRANTY; without even the implied warranty of
    ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    ** GNU Affero General Public License for more details.
    **
    ** You may find a copy of the GNU Affero GPL version 3 at the following
    ** location: https://www.gnu.org/licenses/agpl-3.0.en.html
    **
    ** Additional terms under GNU Affero GPL version 3 section 7:
    **
    **   Under Section 7 of the GNU Affero GPL version 3, the following additional
    **   terms apply to the works covered under the License.  These additional terms
    **   are non-permissive additional terms allowed under Section 7 of the GNU
    **   Affero GPL version 3 and may not be removed by you.
    **
    **   0. Attribution Requirement.
    **
    **     You must preserve all legal notices or author attributions in the covered
    **     work or Appropriate Legal Notices displayed by works containing the covered
    **     work.  You may not remove from the covered work any author or developer
    **     credit already included within the covered work.
    **
    **   1. No License To Use Trademarks.
    **
    **     This license does not grant any license or rights to use the trademarks
    **     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
    **     of Golden Code Development Corporation. You are not authorized to use the
    **     name Golden Code, FWD, or the names of any author or contributor, for
    **     publicity purposes without written authorization.
    **
    **   2. No Misrepresentation of Affiliation.
    **
    **     You may not represent yourself as Golden Code Development Corporation or FWD.
    **
    **     You may not represent yourself for publicity purposes as associated with
    **     Golden Code Development Corporation, FWD, or any author or contributor to
    **     the covered work, without written authorization.
    **
    **   3. No Misrepresentation of Source or Origin.
    **
    **     You may not represent the covered work as solely your work.  All modified
    **     versions of the covered work must be marked in a reasonable way to make it
    **     clear that the modified work is not originating from Golden Code Development
    **     Corporation or FWD.  All modified versions must contain the notices of
    **     attribution required in this license.
    */

    package com.goldencode.p2j.persist.orm;

    import com.goldencode.p2j.util.logging.CentralLoggerFile;

    import java.sql.*;
    import java.util.StringTokenizer;

    /**
     * A logger object is used to log messages for a database events. Primarily, the SQL commands are targeted,
     * but any other event can be logged as well.
     * The object will log each event/statement to a stream using its database as reference. The databases can be
     * configured independently, as result all events for a specific database will go to the associates stream.
     * Alternatively, a database can be disabled, leading to all its events being muted. To be able to log data
     * for any database, the logger must be activated in {@code directory.xml} at {@code DIR_PATH} location
     * because, by default, global logging is disabled.
     * The object itself allows a bit of configuration: with or without a timestamp and the specific one, using
     * the simple date format.
     */
    public class SQLStatementLogger
    extends PersistenceLogger
    {
       /** The static singleton instance. */
       private static final SQLStatementLogger logger = new SQLStatementLogger();

       /**
        * The private default constructor.
        */
       private SQLStatementLogger()
       {
       }

       /**
        * Static accessor to singleton.
        *
        * @return  The {@code SQLStatementLogger} singleton instance.
        */
       public static SQLStatementLogger getLogger()
       {
          return logger;
       }

       /**
        * Log something using a {@code Database} as reference. The method use the settings specific to this
        * database, as previously set. If the {@code LOGGING_ENABLED} is not active, this method will not be
        * called at all. <p>
        * When called the first time for a specific database, it will query the registry to see whether that
        * database has the logging logic enabled. This flag will be saved for further calls. It can be
        * programmatically altered by using {@code setEnabled()} API.
        *
        * @param   <T>
        *          The statement type.
        * @param   <U>
        *          Either the argument type or the result type.
        * @param   databaseName
        *          The name of the {@code Database}.
        * @param   statement
        *          The statement used.
        * @param   isFullStatement
        *          Flag that denotes whether the statement contains parameter values or not.
        * @param   config
        *          The logging configuration for this database.
        * @param   batchSize
        *          How many SQLs are in this batch.
        * @param   profilingTime
        *          The execution time of the SQL query.
        */
       protected <T, U> void log(String databaseName,
                                 String statement,
                                 boolean isFullStatement,
                                 SQLStatementLoggerConfiguration config,
                                 int batchSize,
                                 Double profilingTime)
       throws SQLException
       {
          if (profilingTime != null && profilingTime < config.getMinTimeThreshold())
          {
             return;
          }

          if (config.isIgnoreMetaLogging() && databaseName.contains("meta"))
          {
             return;
          }

          StringBuilder sb = new StringBuilder();
          sb.append(databaseName).append(": ");

          sb.append("Statement: ");
          String stmt = statement;
          if (isFullStatement && !config.isAllowSensitive())
          {
             int statementLength = stmt.length();
             if (statementLength >= 100)
             {
                stmt = stmt.substring(0, 100) + "... (length: " + statementLength + ")";
             }
          }

          simplify(stmt, sb);

          if (profilingTime != null)
          {
             sb.append(" Execution time: ").append(profilingTime).append(" ms;");
          }

          sb.append(" Batch size: " + batchSize + ";");

          String stackTrace = null;
          if (config.isStackTracingEnabled())
          {
             StackTraceElement[] ste = Thread.currentThread().getStackTrace();
             stackTrace = getStackMethodParent(ste);
             if (stackTrace != null)
             {
                sb.append(" Stack tracing: ").append(stackTrace);
             }
          }

          CentralLoggerFile fileLogger = config.getFileLogger();
          if (fileLogger != null)
          {
             fileLogger.warning(sb.toString());
          }

          SQLLoggingDatabaseHelper dbHelper = config.getDbHelper();
          if (dbHelper != null)
          {
             dbHelper.insertSQLQueryProfiling(databaseName,
                                              statement,
                                              profilingTime,
                                              batchSize,
                                              stackTrace);
          }
       }

       /**
        * Simplifies a statement in order to fit on a single line. New-lines are dropped and replaced with simple
        * spaces.
        *
        * @param   statement
        *          The statement to be printed. It eventually takes multiple lines.
        * @param   sb
        *          The {@code StringBuilder} to append the result to.
        */
       private void simplify(String statement, StringBuilder sb)
       {
          StringTokenizer st = new StringTokenizer(statement, "\n\r", false);
          while (st.hasMoreTokens())
          {
             if (sb.length() != 0)
             {
                sb.append(" ");
             }
             sb.append(st.nextToken().trim());
          }
       }
    }