var colors   = require('colors')
const util   = require('util')

//-- Flatten  global.config.log.{ns}.{feature}
//-- to       flattened[`{ns}.{feature}`]
//-- to pass into colors.setTheme()
function setColorThemes(cfg) {

  var flattened = {}
  for (var namespace in cfg)
    Object.keys(cfg[namespace]).forEach(feature =>
      flattened[namespace+'.'+feature] = cfg[namespace][feature])

  colors.setTheme(flattened)

}


function fixed(input, width) {
  var padding = ''
  while (padding.length+input.length < width-1)
    padding+=' '
  return (input+padding).slice(0,width-1)+' '
}


function colored(input, key, defalt) {
  if (!input.constructor || input.constructor !== String)
    input = input.toString()

  return colors[key] ? input[key]
                     : (defalt ? input[defalt] : input)
}


function error(e, maxLines) {
  return _.take(
            e.stack.split('\n')
                   .filter(ln => ln.match('node_modules') && !ln.match('meanair'))
           , maxLines||20)
          .map(str => str.replace("  at ", ''))
          .map(str => str.replace("(",'').replace(")",'').split(' '))
          .map(words => words[0].red + ' ' + _.rest(words,1).join(' ').white)
          .join('\n  ')
}


function request(req, {body,bot}) {
  var str = util.format('%s %s\n%s\n%s\n\n',
    req.method, `${req.originalUrl} << ${req.header('Referer')}`,
    req.headers['x-forwarded-for'] || req.connection.remoteAddress,
    req.user ? `${req.user.name} ${req.user._id}` : req.sessionID)

  if (bot) {
    var ua = req.header('user-agent')
    // var isBot = (util.isBot(req.header('user-agent'))) ? 'true' : 'false'
    output += `\n bot:${ua?'maybe':'yes'}`
  }
  if (body && !req.method.match(/get/i))
    str += `\n\n ${JSON.stringify(req.body)}`

  return str
}


module.exports = function(config) {

  setColorThemes(config.log)

  return {
    colors,
    colored,
    error,
    fixed,
    format: (input, width, colorKey, colorDefault) =>
      colored(fixed(input, width), colorKey, colorDefault),
    request
  }

}

@@ -849,29 +849,16 @@
  _.take(
-%0A            
 e.stack.
@@ -869,29 +869,16 @@
 t('%5Cn')%0A
-             
       .f
@@ -889,16 +889,17 @@
 r(ln =%3E 
+!
 ln.match
@@ -916,15 +916,21 @@
 ules
-') && !
+%7Cnative') %7C%7C 
 ln.m
@@ -952,21 +952,16 @@
 )%0A      
-    
- 
 , maxLin
@@ -968,22 +968,16 @@
 es%7C%7C20)%0A
-      
     .map
@@ -1006,30 +1006,24 @@
  at %22, ''))%0A
-      
     .map(str
@@ -1074,22 +1074,16 @@
 t(' '))%0A
-      
     .map
@@ -1146,22 +1146,16 @@
 .white)%0A
-      
     .joi

Fix pretty debugging error output