Code coverage report for beefy/lib/handlers/log.js

Statements: 100% (23 / 23)      Branches: 100% (9 / 9)      Functions: 100% (4 / 4)      Lines: 100% (23 / 23)      Ignored: none     

All files » beefy/lib/handlers/ » log.js
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 721   1                     1 9 6     3   3     3                 3   1 2         2 2   1 2 2     1 2       2                 2 1     2 2        
module.exports = handleLog
 
var responsify = require('response-stream')
  , ansicolors = require('ansicolors')
  , bytesize = require('pretty-bytes')
  , through = require('through')
  , pad = require('leftpad')
  , fs = require('fs')
 
// to authors of other handlers:
// if you want to add a special path to be
// logged, attach `loggedPathname` to the `parsed`
// url object.
function handleLog(opts, io, nextHandler) {
  if(!opts.log) {
    return nextHandler
  }
 
  opts = opts.log
 
  var colorEnabled =
    (opts.color === undefined || opts.color) && io.isTTY
 
  var statusDigitToColor = [
      'brightBlack'
    , 'brightBlack'
    , 'green'
    , 'magenta'
    , 'yellow'
    , 'red'
  ]
 
  return handle
 
  function handle(server, req, resp, parsed) {
    var stream = through(write, end)
      , outer = responsify(stream)
      , start = Date.now()
      , size = 0
 
    outer.pipe(resp)
    nextHandler(server, req, outer, parsed)
 
    function write(buf) {
      size += buf.length
      stream.queue(buf)
    }
 
    function end() {
      var code = resp.statusCode + ''
        , time = (Date.now() - start)
        , output
 
      output = [
          ansicolors[statusDigitToColor[code[0]]](code)
        , pad(time + 'ms', 6, ' ') + ' '
        , ansicolors.brightBlack(
              pad(bytesize(size).replace(' ', '').toUpperCase(), 9, ' ')
          ) + ' '
        , parsed.loggedPathname || parsed.pathname
      ].join(' ')
 
      if(!colorEnabled) {
        output = output.replace(/\x1B\[([\d;]+?)m/g, '')
      }
 
      io.log(output)
      stream.queue(null)
    }
  }
}