e68302d56303ea03dc2ef71c79ed6c430a2d2855
[fnpeditor.git] / src / fnpjs / logging / logging.js
1 define(function(require) {
2     
3 'use strict';
4
5 var _ = require('libs/underscore'),
6     handlers = require('fnpjs/logging/handlers'),
7     config = {},
8     levels = ['debug', 'info', 'warning', 'error', 'critical'];
9
10
11 var Logger = function(name) {
12     this.name = name;
13     Object.defineProperty(this, 'config', {
14         get: function() {
15             return _.extend({
16                 propagate: true,
17                 level: 'warn',
18                 handlers: []
19             }, config.loggers[name] || {});
20         }
21     });
22 };
23
24 _.extend(Logger.prototype, {
25     log: function(level, message, data) {
26         if(levels.indexOf(level) !== -1 && levels.indexOf(level) >= levels.indexOf(this.config.level)) {
27             this.config.handlers.forEach(function(handlerName) {
28                 var handlerConfig = config.handlers[handlerName],
29                     handler = handlerConfig.handler,
30                     handlerLevel = handlerConfig.level || 'info';
31
32                 if(typeof handler === 'string') {
33                     handler = handlers[handlerConfig.handler];
34                 }
35                 if(!handler) {
36                     throw new Error('Unknown handler: ' + handlerName);
37                 }
38
39                 if(levels.indexOf(handlerLevel) !== -1 && levels.indexOf(level) >= levels.indexOf(handlerLevel)) {
40                     handler(message, level, data);
41                 }
42             });
43         }
44         if(this.config.propagate && this.name) {
45             var logger = new Logger(this.name.split('.').slice(0, -1).join('.'));
46             logger.log(level, message, data);
47         }
48     },
49     exception: function(e) {
50         this.log('error', e.toString(), {exception: e});
51     }
52 });
53
54 levels.forEach(function(level) {
55     Logger.prototype[level] = function(message, data) {
56         return this.log(level, message, data);
57     };
58 });
59
60
61 var api = {
62     getLogger: function(name) {
63         return new Logger(name);
64     },
65     setConfig: function(_config) {
66         config = _.extend({
67             handlers: [],
68             loggers: []
69         } ,_config);
70     },
71     clearConfig: function() {
72         this.setConfig({});
73     }
74 };
75
76 api.clearConfig();
77
78
79 return api;
80
81 });