cocalc/src / smc-project / node_modules / cliff / node_modules / winston / lib / winston / common.js
50675 views/*1* common.js: Internal helper and utility functions for winston2*3* (C) 2010 Charlie Robbins4* MIT LICENCE5*6*/78var util = require('util'),9crypto = require('crypto'),10cycle = require('cycle'),11config = require('./config');1213//14// ### function setLevels (target, past, current)15// #### @target {Object} Object on which to set levels.16// #### @past {Object} Previous levels set on target.17// #### @current {Object} Current levels to set on target.18// Create functions on the target objects for each level19// in current.levels. If past is defined, remove functions20// for each of those levels.21//22exports.setLevels = function (target, past, current, isDefault) {23if (past) {24Object.keys(past).forEach(function (level) {25delete target[level];26});27}2829target.levels = current || config.npm.levels;30if (target.padLevels) {31target.levelLength = exports.longestElement(Object.keys(target.levels));32}3334//35// Define prototype methods for each log level36// e.g. target.log('info', msg) <=> target.info(msg)37//38Object.keys(target.levels).forEach(function (level) {39target[level] = function (msg) {40var args = Array.prototype.slice.call(arguments),41callback = typeof args[args.length - 1] === 'function' || !args[args.length - 1] ? args.pop() : null,42meta = args.length === 2 ? args.pop() : null;4344return target.log(level, msg, meta, callback);45};46});4748return target;49};5051//52// ### function longestElement53// #### @xs {Array} Array to calculate against54// Returns the longest element in the `xs` array.55//56exports.longestElement = function (xs) {57return Math.max.apply(58null,59xs.map(function (x) { return x.length; })60);61};6263//64// ### function clone (obj)65// #### @obj {Object} Object to clone.66// Helper method for deep cloning pure JSON objects67// i.e. JSON objects that are either literals or objects (no Arrays, etc)68//69exports.clone = function (obj) {70// we only need to clone refrence types (Object)71if (!(obj instanceof Object)) {72return obj;73}74else if (obj instanceof Date) {75return obj;76}7778var copy = {};79for (var i in obj) {80if (Array.isArray(obj[i])) {81copy[i] = obj[i].slice(0);82}83else if (obj[i] instanceof Buffer) {84copy[i] = obj[i].slice(0);85}86else if (typeof obj[i] != 'function') {87copy[i] = obj[i] instanceof Object ? exports.clone(obj[i]) : obj[i];88}89}9091return copy;92};9394//95// ### function log (options)96// #### @options {Object} All information about the log serialization.97// Generic logging function for returning timestamped strings98// with the following options:99//100// {101// level: 'level to add to serialized message',102// message: 'message to serialize',103// meta: 'additional logging metadata to serialize',104// colorize: false, // Colorizes output (only if `.json` is false)105// timestamp: true // Adds a timestamp to the serialized message106// }107//108exports.log = function (options) {109var timestampFn = typeof options.timestamp === 'function'110? options.timestamp111: exports.timestamp,112timestamp = options.timestamp ? timestampFn() : null,113meta = options.meta ? exports.clone(cycle.decycle(options.meta)) : null,114output;115116//117// raw mode is intended for outputing winston as streaming JSON to STDOUT118//119if (options.raw) {120if (typeof meta !== 'object' && meta != null) {121meta = { meta: meta };122}123output = exports.clone(meta) || {};124output.level = options.level;125output.message = options.message.stripColors;126return JSON.stringify(output);127}128129//130// json mode is intended for pretty printing multi-line json to the terminal131//132if (options.json) {133if (typeof meta !== 'object' && meta != null) {134meta = { meta: meta };135}136137output = exports.clone(meta) || {};138output.level = options.level;139output.message = options.message;140141if (timestamp) {142output.timestamp = timestamp;143}144145if (typeof options.stringify === 'function') {146return options.stringify(output);147}148149return JSON.stringify(output, function (key, value) {150return value instanceof Buffer151? value.toString('base64')152: value;153});154}155156output = timestamp ? timestamp + ' - ' : '';157output += options.colorize ? config.colorize(options.level) : options.level;158output += (': ' + options.message);159160if (meta) {161if (typeof meta !== 'object') {162output += ' ' + meta;163}164else if (Object.keys(meta).length > 0) {165output += ' ' + (options.prettyPrint ? ('\n' + util.inspect(meta, false, null, options.colorize)) : exports.serialize(meta));166}167}168169return output;170};171172exports.capitalize = function (str) {173return str && str[0].toUpperCase() + str.slice(1);174};175176//177// ### function hash (str)178// #### @str {string} String to hash.179// Utility function for creating unique ids180// e.g. Profiling incoming HTTP requests on the same tick181//182exports.hash = function (str) {183return crypto.createHash('sha1').update(str).digest('hex');184};185186//187// ### function pad (n)188// Returns a padded string if `n < 10`.189//190exports.pad = function (n) {191return n < 10 ? '0' + n.toString(10) : n.toString(10);192};193194//195// ### function timestamp ()196// Returns a timestamp string for the current time.197//198exports.timestamp = function () {199return new Date().toISOString();200};201202//203// ### function serialize (obj, key)204// #### @obj {Object|literal} Object to serialize205// #### @key {string} **Optional** Optional key represented by obj in a larger object206// Performs simple comma-separated, `key=value` serialization for Loggly when207// logging to non-JSON inputs.208//209exports.serialize = function (obj, key) {210if (obj === null) {211obj = 'null';212}213else if (obj === undefined) {214obj = 'undefined';215}216else if (obj === false) {217obj = 'false';218}219220if (typeof obj !== 'object') {221return key ? key + '=' + obj : obj;222}223224if (obj instanceof Buffer) {225return key ? key + '=' + obj.toString('base64') : obj.toString('base64');226}227228var msg = '',229keys = Object.keys(obj),230length = keys.length;231232for (var i = 0; i < length; i++) {233if (Array.isArray(obj[keys[i]])) {234msg += keys[i] + '=[';235236for (var j = 0, l = obj[keys[i]].length; j < l; j++) {237msg += exports.serialize(obj[keys[i]][j]);238if (j < l - 1) {239msg += ', ';240}241}242243msg += ']';244}245else if (obj[keys[i]] instanceof Date) {246msg += keys[i] + '=' + obj[keys[i]];247}248else {249msg += exports.serialize(obj[keys[i]], keys[i]);250}251252if (i < length - 1) {253msg += ', ';254}255}256257return msg;258};259260261