2 * container.js: Inversion of control container for winston logger instances
4 * (C) 2010 Charlie Robbins
9 var common = require('./common'),
10 winston = require('../winston');
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.
18 var Container = exports.Container = function (options) {
20 this.options = options || {};
23 new winston.transports.Console({
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.
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 || [];
43 if (options.transports.length === 0 && (!options || !options['console'])) {
44 options.transports.push(this.default.transports[0]);
47 Object.keys(options).forEach(function (key) {
48 if (key === 'transports') {
52 var name = common.capitalize(key);
54 if (!winston.transports[name]) {
55 throw new Error('Cannot add unknown transport: ' + name);
58 var namedOptions = options[key];
60 options.transports.push(new (winston.transports[name])(namedOptions));
63 this.loggers[id] = new winston.Logger(options);
66 return this.loggers[id];
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`.
75 Container.prototype.has = function (id) {
76 return !!this.loggers[id];
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.
85 Container.prototype.close = function (id) {
88 function _close (id) {
89 if (!self.loggers[id]) {
93 self.loggers[id].close();
94 delete self.loggers[id];
97 return id ? _close(id) : Object.keys(this.loggers).forEach(function (id) {