# P2JQueryLogger.java

    /*
    ** Module   : P2JQueryLogger.java
    ** Abstract : Logger for P2J queries
    **
    ** Copyright (c) 2023-2024, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------------Description---------------------------------------
    ** 001 RAA 20230522 First revision with basic usage.
    ** 002 RAA 20230607 If logging is not intended, queries are now executed in P2JQueryExecutor. Otherwise,
    **                  the execution and logging jobs are done here.
    **     RAA 20230609 Replaced exception on directory bind with a warning log with CentralLogger.
    ** 003 DDF 20230627 Replaced static initialization of values from the directory configuration with
    **                  a method called at server bootstrap.
    **     DDF 20230627 Used a standard handling for directory binding.
    **     RAA 20230628 Removed loggingEnabled field since it was redundant.
    ** 004 RAA 20230802 Removed logging configuration and refactored the log method.
    ** 005 ICP 20240419 Refactored log method to support logging in a h2 database as well as a file.
    **     ICP 20240813 printResult is modified to 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.persist.*;
    import com.goldencode.p2j.util.logging.CentralLoggerFile;

    /**
     * A logger object that is used to log messages about P2J queries.
     * It supports some form of customization such as: displaying the parent method from the stack trace,
     * the x-th processed component, the use count of a query.
     */
    public class P2JQueryLogger
    extends PersistenceLogger
    {
       /** The static singleton instance. */
       private static final P2JQueryLogger logger = new P2JQueryLogger();

       /**
        * Private default constructor.
        */
       private P2JQueryLogger()
       {

       }

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

       /**
        * Function responsible with logging details about P2J queries.
        *
        * If logging is disabled, then this method will never be reached.
        *
        * @param   query
        *          The query that was executed.
        * @param   databaseName
        *          The name of the database in use.
        * @param   fql
        *          The FQL of the query.
        * @param   config
        *          The per-database configuration used for logging.
        * @param   profilingTime
        *          The execution time of the query.
        */
       protected void log(P2JQuery query,
                          String databaseName,
                          String fql,
                          P2JQueryStatisticsConfiguration config,
                          Double profilingTime)
       throws QueryOffEndException
       {
          if (query == null)
          {
             printResult(config, "Cannot log a null query");
          }

          if (fql == null)
          {
             if (query instanceof CompoundQuery)
             {
                // Need to wait for all components to have a valid fql
                // Also, time will be computed as the addition of the component's times
                fql = ((CompoundQuery) query).getCombinedFqls();
                if (fql == null)
                {
                   return;
                }

                profilingTime = ((CompoundQuery) query).getCombinedExecutionTime();
             }
             else if (query instanceof RandomAccessQuery)
             {
                fql = ((RandomAccessQuery) query).getBundleFql();
                if (fql == null)
                {
                   // Something happened this time so the logging will be skipped
                   return;
                }
             }
             else
             {
                printResult(config, "Could not log query: " + query.getClass().getSimpleName());
                return;
             }
          }

          P2JQueryStatistics statistics = P2JQueryStatistics.getStatistics(query, fql);
          // Determine if the profiling time should be updated
          boolean updateProfiling = profilingTime != null;
          statistics.incrementUseCount();
          if (updateProfiling)
          {
             statistics.increaseTime(profilingTime);
          }

          if (statistics.getUseCount() % config.getProcessedComponents() != 0)
          {
             return;
          }

          if (updateProfiling && profilingTime < config.getMinTimeThreshold())
          {
             return;
          }

          String queryType = query.getClass().getSimpleName();
          StringBuilder sb = new StringBuilder();

          sb.append("Database: ").append(databaseName).append("; ");
          sb.append("Query type: ").append(queryType).append("; ");
          sb.append("FQL: ").append(fql).append("; ");
          sb.append("Use count: ").append(statistics.getUseCount()).append("; ");

          Double processingTime = -1.0;
          if (updateProfiling)
          {
             processingTime = statistics.getTime();
             sb.append("Processing time until now: " + processingTime + " ms; ");
          }

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

          printResult(config, sb.toString());

          P2JLoggingDatabaseHelper dbHelper = config.getDbHelper();
          if (dbHelper != null)
          {
             dbHelper.insertP2JQueryProfiling(databaseName,
                                              queryType,
                                              fql,
                                              statistics.getUseCount(),
                                              processingTime,
                                              location,
                                              stackTrace);
          }
       }

       /**
        * Method used for printing a string to a file specified in the per-database logging configuration.
        *
        * @param   config
        *          The per-database configuration used.
        * @param   result
        *          The string to be printed to the file.
        */
       private void printResult(P2JQueryStatisticsConfiguration config, String result)
       {
          CentralLoggerFile fileLogger = config.getFileLogger();
          if (fileLogger != null)
          {
             fileLogger.warning(result);
          }
       }
    }