smartxml: raise an Error on invalid XML
[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({
41                         message: message,
42                         level: level,
43                         loggerName: this.name,
44                         data: data
45                     });
46                 }
47             }.bind(this));
48         }
49         if(this.config.propagate && this.name) {
50             var logger = new Logger(this.name.split('.').slice(0, -1).join('.'));
51             logger.log(level, message, data);
52         }
53     },
54     exception: function(e) {
55         this.log('error', e.toString(), {exception: e});
56     }
57 });
58
59 levels.forEach(function(level) {
60     Logger.prototype[level] = function(message, data) {
61         return this.log(level, message, data);
62     };
63 });
64
65
66 var api = {
67     getLogger: function(name) {
68         return new Logger(name);
69     },
70     setConfig: function(_config) {
71         config = _.extend({
72             handlers: [],
73             loggers: []
74         } ,_config);
75     },
76     clearConfig: function() {
77         this.setConfig({});
78     }
79 };
80
81 api.clearConfig();
82
83
84 return api;
85
86 });