1- import { format } from 'util' ;
2-
31export interface Logger {
42 error ( ...args : any [ ] ) : void ;
53 warn ( ...args : any [ ] ) : void ;
64 info ( ...args : any [ ] ) : void ;
75 debug ( ...args : any [ ] ) : void ;
86}
97
10- const DEBUG = 'debug' ;
11- const INFO = 'info' ;
12- const WARN = 'warn' ;
13- const ERROR = 'error' ;
14- const NONE = 'none' ;
8+ type ConsoleMethod = typeof console . error ;
159
16- const logLevels = [ DEBUG , INFO , WARN , ERROR , NONE ] ;
10+ const logLevelIndices : Record < string , number > = {
11+ debug : 0 ,
12+ info : 1 ,
13+ warn : 2 ,
14+ error : 3 ,
15+ none : 4 ,
16+ } ;
1717
1818/**
1919 * A default logger that writes to stderr.
2020 */
2121export class DefaultLogger implements Logger {
22- prefix : string ;
2322 minLevel : number ;
2423
2524 /**
@@ -30,36 +29,26 @@ export class DefaultLogger implements Logger {
3029 */
3130 constructor ( logLevel ?: string ) {
3231 this . minLevel = 1 ;
33- for ( let i = 0 ; i < logLevels . length ; i ++ ) {
34- if ( logLevels [ i ] === logLevel ) {
35- this . minLevel = i ;
36- break ;
37- }
32+ if ( logLevel && logLevel in logLevelIndices ) {
33+ this . minLevel = logLevelIndices [ logLevel ] ;
3834 }
39- this . prefix = logLevel + ': [Bucketeer] ' ;
35+ }
36+
37+ private log ( level : string , consoleFn : ConsoleMethod , ...args : any [ ] ) {
38+ if ( this . minLevel > logLevelIndices [ level ] ) return ;
39+ consoleFn ( `${ level } : [Bucketeer]` , ...args ) ;
4040 }
4141
4242 error ( ...args : any [ ] ) : void {
43- this . write ( args , ERROR ) ;
43+ this . log ( 'error' , console . error , ... args ) ;
4444 }
4545 warn ( ...args : any [ ] ) : void {
46- this . write ( args , WARN ) ;
46+ this . log ( 'warn' , console . warn , ... args ) ;
4747 }
4848 info ( ...args : any [ ] ) : void {
49- this . write ( args , INFO ) ;
49+ this . log ( 'info' , console . info , ... args ) ;
5050 }
5151 debug ( ...args : any [ ] ) : void {
52- this . write ( args , DEBUG ) ;
53- }
54-
55- write ( args : any [ ] , logLevel : ( typeof logLevels ) [ number ] ) : void {
56- if ( this . minLevel > logLevels . indexOf ( logLevel ) ) {
57- return ;
58- }
59- if ( args . length === 1 ) {
60- return ;
61- }
62- args [ 0 ] = this . prefix + args [ 0 ] ;
63- console . error ( format ( ...args ) ) ;
52+ this . log ( 'debug' , console . debug , ...args ) ;
6453 }
65- }
54+ }
0 commit comments