/ lib / logger.js
logger.js
 1  /*!
 2   * lib/logger.js
 3   * Copyright © 2019 – Katana Cryptographic Ltd. All Rights Reserved.
 4   */
 5  
 6  
 7  import util from './util.js'
 8  
 9  
10  /**
11   * Class providing static methods for logging
12   */
13  const Logger = {
14  
15      /**
16       * Log a message in the console
17       * @param {string/object} msg
18       * @param {boolean=} json - true if msg is a json object, false otherwise
19       */
20      info: (msg, json) => {
21          const logEntry = Logger._formatLog('INFO', msg, json)
22          console.log(logEntry)
23      },
24  
25      /**
26       * Log an error message
27       * @param {object} e - error
28       * @param {string} msg - message associated to the error
29       */
30      error: (e, msg) => {
31          const logEntry = Logger._formatLog('ERROR', msg)
32          console.error(logEntry)
33  
34          //const errorEntry = Logger._formatLog(e)
35          if (e) {
36              console.error(e)
37          }
38      },
39  
40  
41      /**
42       * Format log entry
43       * @param {string} level - log level label
44       * @param {string/object} msg
45       * @param {boolean} json - true if msg is a json object, false otherwise
46       */
47      _formatLog: (level, msg, json = false) => {
48          const data = json ? JSON.stringify(msg, null, 2) : msg
49  
50          const memUse = process.memoryUsage()
51          const mib = util.pad100(util.toMb(memUse.rss))
52  
53          const D = new Date()
54          const y = D.getUTCFullYear()
55          const m = util.pad10(D.getUTCMonth() + 1)
56          const d = util.pad10(D.getUTCDate())
57          const h = util.pad10(D.getUTCHours())
58          const mn = util.pad10(D.getUTCMinutes())
59          const s = util.pad10(D.getUTCSeconds())
60          const ms = util.pad100(D.getUTCMilliseconds())
61  
62          const parts = [y, '-', m, '-', d, 'T', h, ':', mn, ':', s, 'Z  ', level, '  ', data]
63          return parts.join('')
64      }
65  }
66  
67  export default Logger