Example #1
0
Sitespeed.prototype._setupLog = function(cb) {

  var logLevel = this.config.verbose ? 'verbose' : 'info';

  if (process.env.NODE_ENV === 'test') {
    logLevel = 'error';
  }

  winston.loggers.add('sitespeed.io', {
    file: {
      level: logLevel,
      json: false,
      label: 'sitespeed',
      filename: path.join(this.config.run.absResultDir, 'sitespeed.io.log')
    },
    console: {
      level: logLevel,
      colorize: !this.config.noColor,
      silent: (this.config.tap || this.config.junit || this.config.silent)
    }
  });

  this.log = winston.loggers.get('sitespeed.io');
  cb();
};
Example #2
0
/**
 * Helper method to retrive the correct logger and set the classname
 * as description.
 * @param  {String} classname
 * @param  {String} level
 * @return {Logger}
 */
function getLogger(classname, level) {
  var _level = level || config.logging;
  var _logger;
  if(env == 'production') {
    winston.loggers.add(classname, {
      console: {
        level: config.logging,
        colorize: 'true',
        label: classname
      },
      file: {
        filename: './src/logs/production.log'
      }
    });
    _logger = winston.loggers.get(classname);
  } else {
    winston.loggers.add(classname, {
      console: {
        level: config.logging,
        colorize: 'true',
        label: classname,
        timestamp: 'true'
      },
      file: {
        filename: './src/logs/development.log'
      }
    });
     _logger = winston.loggers.get(classname);
  }
  return _logger;
}
Example #3
0
log.init = function() {

	// category
	winston.loggers.add("db", config.log.db);
	winston.loggers.add("dao", config.log.dao);
	winston.loggers.add("app", config.log.app);
}
Example #4
0
 function getLogger(name) {
   if(!winston.loggers.has(name)) {
     var logger = winston.loggers.add(name, getLoggerSettings(name));
     logger.setLevels(config.winston.levels);
   }
   return winston.loggers.get(name);
 }
Example #5
0
    }).then(function () {
        if (self.config.httpsPort)
            winston.loggers.get("jsreport").info("jsreport server successfully started on https port: " + self.config.httpsPort);

        if (self.config.httpPort)
            winston.loggers.get("jsreport").info("jsreport server successfully started on http port: " + self.config.httpPort);
    });
Example #6
0
Bootstrapper.prototype._createLoggerWinston = function () {
    if (!winston.loggers.has("jsreport")) {
        var transportSettings = {
            timestamp: true,
            colorize: true,
            level: this.config.mode === "production" ? "info" : "debug"
        };

        var logDirectory = this.config.logger.logDirectory || path.join(this.config.rootDirectory, "logs");

        if (!fs.existsSync(logDirectory)) {
            fs.mkdir(logDirectory);
        }

        var consoleTransport = new (winston.transports.Console)(transportSettings);
        var fileTransport = new (winston.transports.File)({ name: "main", filename: path.join(logDirectory, 'reporter.log'), maxsize: 10485760, json: false, level: transportSettings.level });
        var errorFileTransport = new (winston.transports.File)({ name: "error", level: 'error', filename: path.join(logDirectory, 'error.log'), handleExceptions: true, json: false });

        winston.loggers.add('jsreport', {
            transports: [consoleTransport, fileTransport, errorFileTransport]
        });
    }

    return winston.loggers.get("jsreport");
};
Example #7
0
exports.get = function () {
  if (!logger) {
    winston.loggers.add('dispatch', config.logger);
    logger = winston.loggers.get('dispatch');
  }
  return logger;
};
Example #8
0
module.exports.setup = function () {
  // set syslog levels
  winston.setLevels(winston.config.syslog.levels)
  var standardLogger = {
    transports: []
  }

  switch (process.env.NODE_ENV) {
    case 'test':
      standardLogger.transports.push(new (winston.transports.Console)({
        timestamp: true,
        level: 'error',
        colorize: true,
        prettyPrint: true,
        humanReadableUnhandledException: true,
        formatter: function (options) {
          return options.message
        }
      }))
      break
    case 'production':
      standardLogger.transports.push(new (winston.transports.Console)({
        timestamp: true,
        level: 'crit',
        colorize: false,
        prettyPrint: true,
        humanReadableUnhandledException: true
      }))
      standardLogger.transports.push(new (DailyRotateFile)({
        timestamp: true,
        level: 'info',
        filename: 'logs/app.log',
        datePattern: '-yyyy-MM-dd',
        logstash: true, // json
        humanReadableUnhandledException: false
      }))
      break
    case 'development':
    default:
      standardLogger.transports.push(new (winston.transports.Console)({
        timestamp: true,
        level: 'debug',
        colorize: true,
        prettyPrint: true,
        humanReadableUnhandledException: true
      }))
  }

  winston.loggers.add('standard', standardLogger)
  winston.loggers.get('standard').exitOnError = true
  winston.handleExceptions(new (DailyRotateFile)({
    timestamp: true,
    level: 'debug',
    filename: 'logs/exception.log',
    datePattern: '-yyyy-MM-dd',
    logstash: true, // json
    humanReadableUnhandledException: true,
    handleExceptions: true
  }))
}
Example #9
0
module.exports.init = function (args) {
  var options = _.extend(defaults, {
    colorize: !args.logNoColors
  , timestamp: args.logTimestamp
  });

  var winstonOptions = {
    console:
      _.extend({
        handleExceptions: true
      , json: false
      , level: 'debug'
      , exitOnError: false
      }, options)
    };

  if (args.log) {
    winstonOptions.file = {
      filename: args.log
    , colorize: false
    , level: 'debug'
    , maxsize: 10000000
    , maxFiles: 1
    , json: false
    };
  }

  winston.addColors(colors);
  winston.loggers.add('appium', winstonOptions);
  logger = winston.loggers.get('appium');
  logger.setLevels(levels);


  if (args.quiet) {
    logger.transports.console.level = 'warn';
  }

  if (args.webhook) {
    var host = args.webhook;
    var port = 9003;
    if (host.indexOf(':') > -1) {
      try {
        host = host.substring(0, host.indexOf(':'));
        port = args.webhook.substring(args.webhook.indexOf(':') + 1);
        port = parseInt(port, 10);
      } catch (e) {
      }
    }
    host = host || '127.0.0.1';
    port = port || 9003;
    try {
      logger.add(winston.transports.Webhook, { 'host': host, 'port': port,
        'path': '/' });
    } catch (e) {
      logger.info("Tried to attach logging to webhook at " + host +
                  " but an error occurred");
    }
  }
};
Example #10
0
logger.label = function (label) {
  if (!existLoggers[label]) {
    winston.loggers.add(label, {
      transports: getTransports(label),
    });
    existLoggers[label] = true;
  }
  return winston.loggers.get(label);
};
Example #11
0
module.exports = function (o, done) {


    var logger = winston.loggers.get("server"),
        mailerConfig = _.extend({}, mail_config, o.hasOwnProperty("mailer") ? o.mailer : {}),
        mailer = new Mailer(mailerConfig),
        options = _.extend({}, {mailer:mailer}, defaultOptions, o),
        assetToken = (new Date()).getTime(),
        staticRoot = path.join(path.join(__dirname, ".."), "public");

    winston.loggers.add("server", {console:{colorize:true}, file:{filename:"server.log", timestamp:true}});

    providers(o, function (err, database, providers) {
        var userchecker = function (email, password, done) {
                return providers.userProvider.retrieve(email, password, function (err, user) {
                    if (user && !err && user.failedLogins < 5) {
                        providers.userProvider.resetFailedLogins(user.email, function () {
                            done(null, user);
                        });
                    }
                    //so we do not reset if locked. bit of a workaround
                    else if (user) {
                        done(null, user);
                    }
                    else {
                        providers.userProvider.incFailedLogins(email, function (err, user) {
                            done(null, false);
                        });
                    }
                });
            },
            router = restrictedServer.server(_.extend({}, {userchecker:userchecker}, options));

        if (err) {
            console.log("Error creating database: " + err);
            process.exit(1);
            return;
        }


        // add the admin routes
        admin.on(providers, options.roles, assetToken)(router);

        //user routes
        users.on(providers, options.mailer)(router);

        vehicles.on(database, providers)(router);
        calculators.on(database, providers)(router);

        done(router, database, providers, {
            mailer:options.mailer,
            options:o
        });
    });

}
Example #12
0
module.exports.prepareFilter = function (appName) {
  var sanitizeAppName = lodash.snakeCase(appName)
  winston.loggers.get('standard').rewriters.push(function (level, msg, meta) {
    meta.timestamp = new Date().toISOString()
    return meta
  })
  winston.loggers.get('standard').filters.push(function (level, msg, meta) {
    return `[${sanitizeAppName}] ${meta.timestamp} [${level}] ${msg}`
  })
}
Example #13
0
File: app.js Project: paigu06/taxi
server.on( 'uncaughtException', function( req, res, route, error ){
    winston.loggers.get( 'error' ).log( 'critical', moment().format( 'YYYY-MM-DD HH:mm:ss' ) + ' ' + error.stack );
    winston.loggers.get( 'error' ).log( 'critical', moment().format( 'YYYY-MM-DD HH:mm:ss' ) + ' ' + req );
    winston.loggers.get( 'error' ).log( 'critical', moment().format( 'YYYY-MM-DD HH:mm:ss' ) + ' ' + route );
    winston.loggers.get( 'error' ).log( 'critical', moment().format( 'YYYY-MM-DD HH:mm:ss' ) + ' ' + res );
    winston.loggers.get( 'error' ).log( 'critical', moment().format( 'YYYY-MM-DD HH:mm:ss' ) + ' ' + error );

    console.log( error );
    console.log( error.stack );
} );
Example #14
0
	it('should support silencing a logger', function() {
		configure({
			loggers: {
				myLogger: []
			}
		});

		Object.keys(winston.loggers.get('myLogger').transports).should.have.lengthOf(1);
		winston.loggers.get('myLogger').transports.should.have.property('console').with.property('silent', true);
	});
Example #15
0
	getLogger: function(loggerName) {
		var _loggerName = loggerName || 'DEFAULT';

		if (winston.loggers.has(_loggerName)) {
			return winston.loggers.get(_loggerName);
		}

		winston.loggers.add(_loggerName, enrichCfg(config.logging, _loggerName));
		return winston.loggers.get(_loggerName);
	}
Example #16
0
module.exports = function (name, label) {
    winston.loggers.add(name, {
        console: {
            level: 'silly',
            colorize: true,
            label: label
        }
    });

    return winston.loggers.get(name);
};
Example #17
0
function getLogger(module) {
    var moduleName = module.filename.split(path.sep).slice(-2).join('/');
    if(!(module.filename in winston.loggers)) {
        winston.loggers.add(module.filename, {
            console: {
                colorize: true,
                level: config.get('log_level'),
                label: moduleName
            }
        });
    }
    return winston.loggers.get(module.filename);
}
Example #18
0
				data.budget.forEach(function(result) {
					if (result.skipped) {
						winston.loggers.get('sitespeed.io').info('Skipping ' + result.title + ' ' + result.url + ' ' + ' value [' +
							result.value + ']');
					} else if (result.isOk) {
						winston.loggers.get('sitespeed.io').info('The budget for ' + result.title + ' ' + result.url + ' passed [' +
							result.value +
							']');
					} else {
						isFailing = true;
						winston.loggers.get('sitespeed.io').error('The budget for ' + result.title + ' ' + result.url + ' failed. ' +
							result.description);
					}
				});
Example #19
0
  constructor(path, logLevel = 'info', ext = '') {
    this.path = path;
    this.fileExt = ext;
    winston.loggers.add('micro-cache', {
      console: {
        colorize:    true,
        label:       'micro-cache',
        level:       logLevel,
        prettyPrint: true
      }
    });

    this.log = winston.loggers.get('micro-cache');
  }
Example #20
0
export function addGroup(groupName) {
  let level = winston.level;
  let transports =  generateTransports().concat(new (DailyRotateFile)({
    filename: groupName,
    dirname: currentLogsFolder,
    name: groupName,
    level: level
  }));

  winston.loggers.add(groupName, {
    transports: transports
  });
  return winston.loggers.get(groupName);
}
Example #21
0
exports.logger = function(x) {
  if (winston.loggers.has(x)) return winston.loggers.get(x);
  var logger = winston.loggers.add(x, logconfigs[x] || { console: { level: 'debug' } });
  logger.setLevels(winston.config.syslog.levels);
  if (!logger.fatal) logger.fatal = logger.emerg;

  logger.logaux = logger.log;
  logger.log = function(level, msg) {
    var callback, entity, meta;

    if (arguments.length === 3) {
      if (typeof arguments[2] === 'function') {
        meta = {};
        callback = arguments[2];
      }
      else if (typeof arguments[2] === 'object') meta = arguments[2];
    }
    else if (arguments.length === 4) {
      meta = arguments[2];
      callback = arguments[3];
    }

    if (msg.indexOf('device/') === 0) {
      if (!devices) devices = require('./device');
      entity = devices.id2device(msg.substr(7));
      if (!!entity) msg += ' ' + entity.name;
    } else if (msg.indexOf('place/') === 0) {
      if (!places) places = require('./steward').actors.place;
      if (!!places) entity = places.$lookup(msg.substr(6));
      if (!!entity) msg += ' ' + entity.name;
    }

    switch (level) {
      case 'debug':
        break;

      default:
        beacon_ingress(x, level, msg, meta);
        break;
    }

    this.logaux(level !== 'fatal' ? level : 'emerg', '[' + x + '] ' + msg, meta, callback);

    if ((level === 'emerg') || (level === 'fatal')) process.exit(1);
  };

  logger.debug('begin');
  return logger;
};
Example #22
0
    fineTuneUrls: function(okUrls, errorUrls, maxPagesToTest, absResultDir, callback) {
      var log = winston.loggers.get('sitespeed.io');
      var downloadErrors = {};

      Object.keys(errorUrls).forEach(function(errorUrl) {
        log.log('error', 'Failed to download ' + errorUrl);
        downloadErrors[errorUrl] = inspect(errorUrls[errorUrl]);
      });

      // limit
      if (maxPagesToTest) {
        if (okUrls.length > maxPagesToTest) {
          okUrls.length = maxPagesToTest;
        }
      }
      if (okUrls.length === 0) {
        log.log('info', 'Didn\'t get any URLs');
        callback(new Error('No URLs to analyze'), okUrls, downloadErrors);
      } else {
        fileHelper.save(path.join(absResultDir, 'data', 'urls.txt'),
          okUrls.join(EOL),
          function(err) {
            callback(err, okUrls, downloadErrors);
          });
      }
    },
Example #23
0
    return function (ctx) {
        let logger = ctx.logger || winston.loggers.get("system");
        let transFn = ctx.transFn || (obj => obj);

        if (Array.isArray(tasks)) {
    		let hkey = ctx.hkey.spawn();

            logger.info(hkey.key, `┏━━━━ Starting child processes`);

            let childCtx = _.assignIn({}, ctx, { hkey });
            let pChain = Q( childCtx );
            for (let task of tasks) {
                var fn = getPreparedExecSpawnFunction(task, transFn);
                pChain = pChain.then(fn);
            }
            return pChain.then(function() {
                logger.info(hkey.key, `┗━━━━ Finished running child processes`);
                return ctx;
            });
        }
        else {
            var fn = getPreparedExecSpawnFunction(tasks, transFn);
            return fn(ctx);
        }
    }
Example #24
0
function init(configFile, done) {
  try {
    var logConfig;
    if (_.isObject(configFile)) {
      logConfig = configFile;
    } else {
      if (!configFile) {
        configFile = CONFIG_FILE;
      }

      var configPath = path.join(__dirname, configFile);
      if (!fs.existsSync(configPath)) {
        configPath = path.join(process.cwd(), configFile);
      }

      logConfig = JSON.parse(fs.readFileSync(configPath));
    }

    // configure loggers
    Object.keys(logConfig).forEach(function (key) {
      winston.loggers.add(key, logConfig[key]);
    });
    var logger = winston.loggers.get('default');
    logger.info('logging initialized.');

    done(null);
  } catch (e) {
    done(new Error('unable to read the configuration: ' + e.message));
  }
}
Example #25
0
Logger = function (prefix, colorize) {
	var options, logger;

	if (colorize === undefined) {
		colorize = true;
	}
	prefix   = prefix || '';

	logger = loggers[prefix];
	if (!logger) {
		logger = {};
		loggers[prefix] = logger;
	}
	logger = logger[colorize];

	if (!logger) {
		options = {
			colorize: colorize,
			level: process.env.LOG_LVL || 'info',
			timestamp: true
		};
		if (prefix) {
			options.label = prefix;
		}
		logger = winston.loggers.add(prefix, { console: options });

		loggers[prefix] = logger;
	}

	return logger;
};
Example #26
0
exports.processPage = function(pageData) {
  var log = winston.loggers.get('sitespeed.io');
  if (pageData.har) {
    var pageURL = util.getURLFromPageData(pageData);
    pageData.har.forEach(function(har) {
      har.log.entries.forEach(function(entry) {

        var asset = assets[entry.request.url];
        var total;
        if (asset) {
          if (entry.timings) {
            total = entry.timings.blocked + entry.timings.dns + entry.timings.connect + entry.timings.ssl +
              entry.timings
              .send + entry.timings.wait + entry.timings.receive;
            asset.timing.add(total, entry.request.url, pageURL);
          } else {
            log.log('info', 'Missing timings in the HAR');
          }
        } else {
          if (entry.timings) {
            total = entry.timings.blocked + entry.timings.dns + entry.timings.connect + entry.timings.ssl +
              entry.timings
              .send + entry.timings.wait + entry.timings.receive;
            assets[entry.request.url] = {
              url: entry.request.url,
              timing: new RequestTiming(total, entry.request.url, pageURL),
              parent: util.getURLFromPageData(pageData)
            };
          }
        }
      });
    });
  }
};
Example #27
0
function Collector(config) {
  this.aggregators = [];
  this.collectors = [];
  this.log = winston.loggers.get('sitespeed.io');
  registerAggregators(config, this.aggregators);
  registerCollectors(config, this.collectors);
}
Example #28
0
exports.onSocketConnection = function(io, socket, connectionEasyRtcId) {
    var winston = require('winston');
    var logServer = winston.loggers.get('easyrtcServer');

    easyrtc.connections[connectionEasyRtcId]={
        easyrtcid: connectionEasyRtcId,
        applicationName: easyrtcCfg.defaultApplicationName,
        clientConnectTime: Date.now()
    };

    // Immediatly send the easyrtcid and application
    logServer.debug('easyRTC: Socket [' + socket.id + '] command sent', {
        label: 'easyrtc',
        easyrtcid:connectionEasyRtcId,
        data: {
            applicationName: easyrtc.connections[connectionEasyRtcId].applicationName,
            iceConfig: {"iceServers": easyrtcCfg.iceServers}
    }});
    socket.json.emit( easyrtcCfg.cmdPacketType, {
        msgType:easyrtcCfg.cmdMsgType.token,
        easyrtcid: connectionEasyRtcId,
        applicationName: easyrtc.connections[connectionEasyRtcId].applicationName,
        iceConfig: {"iceServers": easyrtcCfg.iceServers},
        serverTime: Date.now()
    });

    // Send the connection list to current connection, then broadcast to all others
    exports.broadcastList(io,easyrtc.connections[connectionEasyRtcId].applicationName);
}
Example #29
0
  analyze: function analyze (files, ruleset, cb) {
    this.log = winston.loggers.get('frontend');
    this.log.info('Running parker');

    var self = this,
        startTime = moment(),
        parkerObj = {},
        parker = new Parker(metrics);

    async.each(
      files,
      function iterator (file, callback) {
        fileHelpers.readFile(file, function (err, content) {
          parkerObj[file] = parker.run(content.toString());
          callback();
        });
      },
      function done (err) {
        self.log.info('Finished parker.');
        self.log.verbose(moment().diff(startTime, 'seconds') + ' seconds.');

        cb(err, parkerObj);
      }
    );
  }
Example #30
0
exports.task = function(result, config, cb) {

	if (config.postURL) {
		var log = winston.loggers.get('sitespeed.io');

		request({
			url: config.postURL,
			method: 'POST',
			gzip: true,
			json: result
		}, function(error, response, body) {
			if (error) {
				log.error('Couldn\'t send result to ' + config.postURL + ' got error ' + error);
			} else {
        if (response.statusCode >= 200 && response.statusCode < 207) {
				log.info('Succesfully sent result to ' + config.postURL + ' response code:' + response.statusCode + ' response:' + body);
        }
        else {
          log.error('Couldn\'t send result to ' + config.postURL + ' got ' + response.statusCode + ' ' + body);
        }
			}
			cb();
		});
	} else {
		cb();
	}
};