All files / platform/packages/http-request-logger/src Logger.js

0% Statements 0/0
0% Branches 0/0
0% Functions 0/0
0% Lines 0/0

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213                                                                                                                                                                                                                                                                                                                                                                                                                                         
/* istanbul ignore file */
'use strict';
/*
 * Logger
 *
 * (c) Duy Nguyen <duynv@c2c-techhub.io>
 *
 */
const _ = require('lodash');
const onFinished = require('on-finished');
const Route = use('Route');
const Config = use('Config');
const { constants } = require('../config');
const { sizeOf } = use('C2C/Helpers');
 
/**
 * Defined paths that should be ignored to write logs
 */
const ignorePaths = [
  // Health check path
  '/greeting',
  // metrics path
  Config.get('addons.prometheus.endpoint'),
  // Bull board resources
  '/queues-board',
  '/admin-queues-board',
  // Swagger resources
  '/api-docs',
  '/swagger',
  // Static path
  '/image',
  '/favicon',
  '/static',
];
const ignorePathRegExp = new RegExp(`(${ignorePaths.join('|')})`, 'i');
 
/**
 * Logs http request using AdonisJs in built logger
 */
class Logger {
  constructor({ request, response }, Logger) {
    this.request = request;
    this.response = response;
    this.Logger = Logger;
 
    /**
     * Should capture original url before replacing since the bull board static path will be replaced
     * Ex: /queues-board/static/main.f3e8101b6b9d92501ad2.css -> /main.f3e8101b6b9d92501ad2.css
     */
    this._originalUrl = request.url();
  }
 
  /**
   * Whether config is set to use JSON
   *
   * @method isJson
   *
   * @return {Boolean}
   */
  get isJson() {
    return this.Logger.driver.config && this.Logger.driver.config.json;
  }
 
  /**
   * Returns the diff in milliseconds using process.hrtime.bigint().
   * Started at time is required.
   *
   * @param  {BigInt} startTime
   * @return {Number}
   * @private
   */
  _diffHrTime(startTime) {
    const diff = process.hrtime.bigint() - startTime;
    return Number(diff) / 1e6;
  }
 
  /**
   * Returns the log level based on the status code
   *
   * @method _getLogLevel
   *
   * @param  {Number}     statusCode
   *
   * @return {String}
   *
   * @private
   */
  _getLogLevel(statusCode) {
    if (statusCode < 400) {
      return 'info';
    }
 
    // if (statusCode >= 400 && statusCode < 500) {
    //   return 'error';
    // }
 
    return 'error';
  }
 
  /**
   * Logs http request using the Adonis inbuilt logger
   *
   * @typedef {import('@adonisjs/framework/src/Request')} Request
   * @typedef {import('@adonisjs/framework/src/Response')} Response
   * @param {{ request: Request, response: Response, error: Error | null }} ctx
   * @returns
   */
  log({ request, response, error }) {
    // Do not log OPTIONS method
    if (this._shouldIgnoreLogging({ request })) return;
 
    const method = request.method();
    const url = this._originalUrl;
    const statusCode = response.response.statusCode;
    const duration = Number.parseInt(this._diffHrTime(request.startTime));
    const logLevel = this._getLogLevel(statusCode);
 
    /**
     * Log normally when json is not set to true
     */
    if (!this.isJson) {
      this.Logger[logLevel]('%s %s %s %s', method, statusCode, url, duration);
      return;
    }
 
    /**
     * LOG_SIZE
     *  MINIMUM: Not log the response data excepts request with method PUT, POST, DELETE OR Request error
     *  FULL: Log all request/response data
     */
    const logSize = _.get(request.httpRequestLogOption, 'logSize', constants.LOG_SIZE.FULL);
    const isLogFullData =
      statusCode !== 200 || method !== 'GET' || logSize === constants.LOG_SIZE.FULL;
 
    // Prepare the request's log data
    const logRequest = {
      method,
      path: url,
      data: request.all(),
      headers: request.headers(),
    };
    // Get the request length in bytes (url + headers + body).
    // Calculate request length from content-Length and parsed headers
    // since can not get the correct read/written bytes of 1 request in case of HTTP pipelining
    logRequest.size =
      Number.parseInt(request.header('Content-Length', sizeOf(request.body || {}))) +
      sizeOf([request.originalUrl(), request.headers() || {}]);
    // Get the route pattern from request url
    logRequest.route = _.get(Route.match(url, method, request.hostname()), 'route._route');
 
    // Prepare response's log data
    const logResponse = isLogFullData
      ? { ...(response.lazyBody || {}) }
      : { content: { statusCode, data: '[LOG_MINIMIZED]' } };
    // Get the response length in bytes (headers + body).
    // Content-Length only body length in bytes.
    logResponse.size =
      Number.parseInt(response.getHeader('Content-Length', 0)) +
      sizeOf(response.response.getHeaders() || {});
 
    // Prepare the log data to output
    const payload = {
      level: logLevel,
      duration,
      statusCode,
      requestInfo: logRequest,
      response: logResponse,
    };
    if (error && error.code) {
      payload.code = error.code;
    }
 
    this.Logger[logLevel]('http request', payload);
  }
 
  /**
   * Binds the hook to listen for finish event
   *
   * @method hook
   *
   * @return {void}
   */
  hook() {
    this.request.startTime = process.hrtime.bigint();
 
    // Listen the response finished
    onFinished(this.response.response, (error) => {
      this.log({
        request: this.request,
        response: this.response,
        error,
      });
    });
  }
 
  /**
   * @typedef {import('@adonisjs/framework/src/Request')} Request
   * @param {{ request: Request }} ctx
   * @returns {boolean} true: should ignore logging
   */
  _shouldIgnoreLogging({ request }) {
    // Do not log the request that not is CRUD method
    if (['OPTIONS', 'HEAD', 'TRACE', 'CONNECT'].includes(request.method())) return true;
 
    // Do not log any request from healthcheck, swagger, bull-board or static files
    if (ignorePathRegExp.test(this._originalUrl)) return true;
 
    return false;
  }
}
 
module.exports = Logger;