@@ -4,10 +4,12 @@ const config = require('../config');
44const continuationLocalStorage = require ( 'cls-hooked' ) ;
55const STACK_TRACE_LIMIT = 4000 ;
66const Timer = require ( '../timer/timer' ) ;
7+ const jsonFormatter = require ( '../formatter/json' ) ;
8+ const consoleOutput = require ( '../output/console' ) ;
9+ const allowedKeys = [ 'output' , 'formatter' ] ;
710
811const getContextStorage = function ( ) {
912 const contextNamespace = continuationLocalStorage . getNamespace ( 'session' ) ;
10-
1113 if ( contextNamespace && contextNamespace . active ) {
1214 const { id, _ns_name, ...contextData } = contextNamespace . active ;
1315 return contextData ;
@@ -16,31 +18,25 @@ const getContextStorage = function() {
1618 return { } ;
1719} ;
1820
19- const logMethodFactory = function ( level ) {
20- return function ( action , data ) {
21- if ( ! this . _enabled ) {
22- return ;
23- }
24-
25- console . log ( JSON . stringify ( Object . assign (
26- {
27- name : this . _namespace ,
28- action : action ,
29- level : config . levels [ level ] . number ,
30- time : new Date ( ) . toISOString ( )
31- } ,
32- getContextStorage ( ) ,
33- data
34- ) ) ) ;
35- }
36- } ;
37-
3821class Logger {
3922 constructor ( namespace , enabled ) {
4023 this . _namespace = namespace ;
4124 this . _enabled = enabled ;
4225 }
4326
27+ static configure ( options = { } ) {
28+ this . _validate ( options ) ;
29+ Object . assign ( Logger . config , options ) ;
30+ }
31+
32+ static _validate ( options ) {
33+ Object . keys ( options ) . forEach ( key => {
34+ if ( ! allowedKeys . includes ( key ) ) {
35+ throw new Error ( 'Only the following keys are allowed: formatter, output' )
36+ }
37+ } ) ;
38+ }
39+
4440 isEnabled ( ) {
4541 return this . _enabled ;
4642 }
@@ -64,6 +60,34 @@ class Logger {
6460 }
6561}
6662
63+ Logger . config = {
64+ formatter : jsonFormatter ,
65+ output : consoleOutput
66+ } ;
67+
68+ const logMethodFactory = function ( level ) {
69+ return function ( action , data ) {
70+ if ( ! this . _enabled ) {
71+ return ;
72+ }
73+
74+ const dataToLog = Object . assign (
75+ {
76+ name : this . _namespace ,
77+ action : action ,
78+ level : config . levels [ level ] . number ,
79+ time : new Date ( ) . toISOString ( )
80+ } ,
81+ getContextStorage ( ) ,
82+ data
83+ ) ;
84+
85+ Logger . config . output (
86+ Logger . config . formatter ( dataToLog )
87+ ) ;
88+ }
89+ } ;
90+
6791Logger . prototype . trace = logMethodFactory ( 'trace' ) ;
6892Logger . prototype . debug = logMethodFactory ( 'debug' ) ;
6993Logger . prototype . info = logMethodFactory ( 'info' ) ;
0 commit comments