@@ -55,6 +55,11 @@ class Logger {
5555 this . _getDate = ( ) => ( new Date ( ) ) . toISOString ( ) ;
5656
5757 this . _customizedConsole = console ;
58+
59+ this . _enableFileAndLine = {
60+ enable : false ,
61+ isShortFile : false ,
62+ } ;
5863 }
5964
6065 createNamedLogger ( name ) {
@@ -94,6 +99,15 @@ class Logger {
9499 return this . level ? LEVELS . indexOf ( this . level ) <= LEVELS . indexOf ( level ) : true
95100 }
96101
102+ enableFileAndLine ( enable , isShortFile = false ) {
103+ if ( typeof enable === 'boolean' ) {
104+ this . _enableFileAndLine . enable = enable ;
105+ this . _enableFileAndLine . isShortFile = isShortFile ;
106+ } else {
107+ console . error ( "node-color-log warning: enableFileAndLine should be a boolean value." ) ;
108+ }
109+ }
110+
97111 log ( ...args ) {
98112 this . append ( ...args ) ;
99113 if ( ! this . noColor ) {
@@ -134,11 +148,19 @@ class Logger {
134148 }
135149
136150 getPrefix ( ) {
151+ let prefix = `${ this . _getDate ( ) } ` ;
152+
137153 if ( this . name ) {
138- return `${ this . _getDate ( ) } [${ this . name } ]` ;
139- } else {
140- return this . _getDate ( ) ;
154+ prefix += ` [${ this . name } ]` ;
155+ }
156+ if ( this . _enableFileAndLine . enable ) {
157+ const fileAndLine = getFileAndLine ( this . _enableFileAndLine . isShortFile ) ;
158+ if ( fileAndLine ) {
159+ prefix += `[${ fileAndLine } ]` ;
160+ }
141161 }
162+
163+ return prefix ;
142164 }
143165
144166 color ( ticket ) {
@@ -376,5 +398,32 @@ class Logger {
376398 }
377399}
378400
401+ function getFileAndLine ( isShortFile = false ) {
402+ const e = new Error ( ) ;
403+ const line = e . stack . split ( '\n' ) [ 2 ] ; // 3rd line: caller
404+
405+ // find ( and ) in the line from the end
406+ let start = line . lastIndexOf ( '(' ) ;
407+ let end = line . lastIndexOf ( ')' ) ;
408+ if ( start === - 1 || end === - 1 || start >= end ) {
409+ return '' ;
410+ }
411+ // Extract the file and line number
412+ const fileAndLine = line . substring ( start + 1 , end ) ;
413+
414+ if ( isShortFile ) {
415+ const fileName = fileAndLine . split ( '/' ) . pop ( ) ; // Get the last part of the path
416+ return `${ fileName } :${ fileAndLine . split ( ':' ) [ 1 ] } ` ; // Return file name and line number
417+ }
418+
419+ // Split by : to get the file path and line number
420+ const parts = fileAndLine . split ( ':' ) ;
421+ if ( parts . length < 2 ) {
422+ return '' ;
423+ }
424+ // Return the file path and line number
425+ return `${ parts [ 0 ] } :${ parts [ 1 ] } ` ;
426+ }
427+
379428const logger = new Logger ( ) ;
380- module . exports = logger ;
429+ module . exports = logger ;
0 commit comments