Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Avatar for KuCalc : devops.
Download
50675 views
1
/*
2
* common.js: Internal helper and utility functions for winston
3
*
4
* (C) 2010 Charlie Robbins
5
* MIT LICENCE
6
*
7
*/
8
9
var util = require('util'),
10
crypto = require('crypto'),
11
cycle = require('cycle'),
12
config = require('./config');
13
14
//
15
// ### function setLevels (target, past, current)
16
// #### @target {Object} Object on which to set levels.
17
// #### @past {Object} Previous levels set on target.
18
// #### @current {Object} Current levels to set on target.
19
// Create functions on the target objects for each level
20
// in current.levels. If past is defined, remove functions
21
// for each of those levels.
22
//
23
exports.setLevels = function (target, past, current, isDefault) {
24
if (past) {
25
Object.keys(past).forEach(function (level) {
26
delete target[level];
27
});
28
}
29
30
target.levels = current || config.npm.levels;
31
if (target.padLevels) {
32
target.levelLength = exports.longestElement(Object.keys(target.levels));
33
}
34
35
//
36
// Define prototype methods for each log level
37
// e.g. target.log('info', msg) <=> target.info(msg)
38
//
39
Object.keys(target.levels).forEach(function (level) {
40
target[level] = function (msg) {
41
var args = Array.prototype.slice.call(arguments),
42
callback = typeof args[args.length - 1] === 'function' || !args[args.length - 1] ? args.pop() : null,
43
meta = args.length === 2 ? args.pop() : null;
44
45
return target.log(level, msg, meta, callback);
46
};
47
});
48
49
return target;
50
};
51
52
//
53
// ### function longestElement
54
// #### @xs {Array} Array to calculate against
55
// Returns the longest element in the `xs` array.
56
//
57
exports.longestElement = function (xs) {
58
return Math.max.apply(
59
null,
60
xs.map(function (x) { return x.length; })
61
);
62
};
63
64
//
65
// ### function clone (obj)
66
// #### @obj {Object} Object to clone.
67
// Helper method for deep cloning pure JSON objects
68
// i.e. JSON objects that are either literals or objects (no Arrays, etc)
69
//
70
exports.clone = function (obj) {
71
// we only need to clone refrence types (Object)
72
if (!(obj instanceof Object)) {
73
return obj;
74
}
75
else if (obj instanceof Date) {
76
return obj;
77
}
78
79
var copy = {};
80
for (var i in obj) {
81
if (Array.isArray(obj[i])) {
82
copy[i] = obj[i].slice(0);
83
}
84
else if (obj[i] instanceof Buffer) {
85
copy[i] = obj[i].slice(0);
86
}
87
else if (typeof obj[i] != 'function') {
88
copy[i] = obj[i] instanceof Object ? exports.clone(obj[i]) : obj[i];
89
}
90
}
91
92
return copy;
93
};
94
95
//
96
// ### function log (options)
97
// #### @options {Object} All information about the log serialization.
98
// Generic logging function for returning timestamped strings
99
// with the following options:
100
//
101
// {
102
// level: 'level to add to serialized message',
103
// message: 'message to serialize',
104
// meta: 'additional logging metadata to serialize',
105
// colorize: false, // Colorizes output (only if `.json` is false)
106
// timestamp: true // Adds a timestamp to the serialized message
107
// }
108
//
109
exports.log = function (options) {
110
var timestampFn = typeof options.timestamp === 'function'
111
? options.timestamp
112
: exports.timestamp,
113
timestamp = options.timestamp ? timestampFn() : null,
114
meta = options.meta ? exports.clone(cycle.decycle(options.meta)) : null,
115
output;
116
117
//
118
// raw mode is intended for outputing winston as streaming JSON to STDOUT
119
//
120
if (options.raw) {
121
if (typeof meta !== 'object' && meta != null) {
122
meta = { meta: meta };
123
}
124
output = exports.clone(meta) || {};
125
output.level = options.level;
126
output.message = options.message.stripColors;
127
return JSON.stringify(output);
128
}
129
130
//
131
// json mode is intended for pretty printing multi-line json to the terminal
132
//
133
if (options.json) {
134
if (typeof meta !== 'object' && meta != null) {
135
meta = { meta: meta };
136
}
137
138
output = exports.clone(meta) || {};
139
output.level = options.level;
140
output.message = options.message;
141
142
if (timestamp) {
143
output.timestamp = timestamp;
144
}
145
146
if (typeof options.stringify === 'function') {
147
return options.stringify(output);
148
}
149
150
return JSON.stringify(output, function (key, value) {
151
return value instanceof Buffer
152
? value.toString('base64')
153
: value;
154
});
155
}
156
157
output = timestamp ? timestamp + ' - ' : '';
158
output += options.colorize ? config.colorize(options.level) : options.level;
159
output += (': ' + options.message);
160
161
if (meta) {
162
if (typeof meta !== 'object') {
163
output += ' ' + meta;
164
}
165
else if (Object.keys(meta).length > 0) {
166
output += ' ' + (options.prettyPrint ? ('\n' + util.inspect(meta, false, null, options.colorize)) : exports.serialize(meta));
167
}
168
}
169
170
return output;
171
};
172
173
exports.capitalize = function (str) {
174
return str && str[0].toUpperCase() + str.slice(1);
175
};
176
177
//
178
// ### function hash (str)
179
// #### @str {string} String to hash.
180
// Utility function for creating unique ids
181
// e.g. Profiling incoming HTTP requests on the same tick
182
//
183
exports.hash = function (str) {
184
return crypto.createHash('sha1').update(str).digest('hex');
185
};
186
187
//
188
// ### function pad (n)
189
// Returns a padded string if `n < 10`.
190
//
191
exports.pad = function (n) {
192
return n < 10 ? '0' + n.toString(10) : n.toString(10);
193
};
194
195
//
196
// ### function timestamp ()
197
// Returns a timestamp string for the current time.
198
//
199
exports.timestamp = function () {
200
return new Date().toISOString();
201
};
202
203
//
204
// ### function serialize (obj, key)
205
// #### @obj {Object|literal} Object to serialize
206
// #### @key {string} **Optional** Optional key represented by obj in a larger object
207
// Performs simple comma-separated, `key=value` serialization for Loggly when
208
// logging to non-JSON inputs.
209
//
210
exports.serialize = function (obj, key) {
211
if (obj === null) {
212
obj = 'null';
213
}
214
else if (obj === undefined) {
215
obj = 'undefined';
216
}
217
else if (obj === false) {
218
obj = 'false';
219
}
220
221
if (typeof obj !== 'object') {
222
return key ? key + '=' + obj : obj;
223
}
224
225
if (obj instanceof Buffer) {
226
return key ? key + '=' + obj.toString('base64') : obj.toString('base64');
227
}
228
229
var msg = '',
230
keys = Object.keys(obj),
231
length = keys.length;
232
233
for (var i = 0; i < length; i++) {
234
if (Array.isArray(obj[keys[i]])) {
235
msg += keys[i] + '=[';
236
237
for (var j = 0, l = obj[keys[i]].length; j < l; j++) {
238
msg += exports.serialize(obj[keys[i]][j]);
239
if (j < l - 1) {
240
msg += ', ';
241
}
242
}
243
244
msg += ']';
245
}
246
else if (obj[keys[i]] instanceof Date) {
247
msg += keys[i] + '=' + obj[keys[i]];
248
}
249
else {
250
msg += exports.serialize(obj[keys[i]], keys[i]);
251
}
252
253
if (i < length - 1) {
254
msg += ', ';
255
}
256
}
257
258
return msg;
259
};
260
261