Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Avatar for KuCalc : devops.
Download
50675 views
1
/*
2
* container.js: Inversion of control container for winston logger instances
3
*
4
* (C) 2010 Charlie Robbins
5
* MIT LICENCE
6
*
7
*/
8
9
var common = require('./common'),
10
winston = require('../winston');
11
12
//
13
// ### function Container (options)
14
// #### @options {Object} Default pass-thru options for Loggers
15
// Constructor function for the Container object responsible for managing
16
// a set of `winston.Logger` instances based on string ids.
17
//
18
var Container = exports.Container = function (options) {
19
this.loggers = {};
20
this.options = options || {};
21
this.default = {
22
transports: [
23
new winston.transports.Console({
24
level: 'silly',
25
colorize: false
26
})
27
]
28
}
29
};
30
31
//
32
// ### function get / add (id, options)
33
// #### @id {string} Id of the Logger to get
34
// #### @options {Object} **Optional** Options for the Logger instance
35
// Retreives a `winston.Logger` instance for the specified `id`. If
36
// an instance does not exist, one is created.
37
//
38
Container.prototype.get = Container.prototype.add = function (id, options) {
39
if (!this.loggers[id]) {
40
options = common.clone(options || this.options || this.default);
41
options.transports = options.transports || [];
42
43
if (options.transports.length === 0 && (!options || !options['console'])) {
44
options.transports.push(this.default.transports[0]);
45
}
46
47
Object.keys(options).forEach(function (key) {
48
if (key === 'transports') {
49
return;
50
}
51
52
var name = common.capitalize(key);
53
54
if (!winston.transports[name]) {
55
throw new Error('Cannot add unknown transport: ' + name);
56
}
57
58
var namedOptions = options[key];
59
namedOptions.id = id;
60
options.transports.push(new (winston.transports[name])(namedOptions));
61
});
62
63
this.loggers[id] = new winston.Logger(options);
64
}
65
66
return this.loggers[id];
67
};
68
69
//
70
// ### function close (id)
71
// #### @id {string} **Optional** Id of the Logger instance to find
72
// Returns a boolean value indicating if this instance
73
// has a logger with the specified `id`.
74
//
75
Container.prototype.has = function (id) {
76
return !!this.loggers[id];
77
};
78
79
//
80
// ### function close (id)
81
// #### @id {string} **Optional** Id of the Logger instance to close
82
// Closes a `Logger` instance with the specified `id` if it exists.
83
// If no `id` is supplied then all Loggers are closed.
84
//
85
Container.prototype.close = function (id) {
86
var self = this;
87
88
function _close (id) {
89
if (!self.loggers[id]) {
90
return;
91
}
92
93
self.loggers[id].close();
94
delete self.loggers[id];
95
}
96
97
return id ? _close(id) : Object.keys(this.loggers).forEach(function (id) {
98
_close(id);
99
});
100
};
101
102
103