import { LogLevelType } from '../constants' ; import { colorizeTimestamp , colorizeLevel , colorizeLabel , colorizeMessage } from './colorizers' ; import { padStart , padEnd } from '../format' ; const DELIMITERS = { date : '-' , time : ':' , logMessage : ' ' , fullMessage : ' :: ' , } ; export class MessageBuilder { private readonly colorizeMessages = process . env . LOGGER_COLORIZE_MESSAGES === 'true' ; constructor ( private readonly label ) { } public build ( level , args ) { const timestamp = this . getTimestamp ( ) ; const logMessage = this . prepareMessageFromArgs ( args ) ; if ( ! this . colorizeMessages ) { return [ timestamp , level , this . label , logMessage ] . join ( DELIMITERS . fullMessage ) ; } return [ colorizeTimestamp ( timestamp ) , colorizeLevel ( level ) , colorizeLabel ( this . label ) , colorizeMessage ( level , logMessage ) , ] . join ( DELIMITERS . fullMessage ) ; } private getTimestamp ( ) { const date = new Date ( ) ; const logDate = [ padStart ( date . getDate ( ) ) , padStart ( date . getMonth ( ) + 1 ) , date . getFullYear ( ) ] . join ( DELIMITERS . date ) ; const logTime = [ padStart ( date . getHours ( ) ) , padStart ( date . getMinutes ( ) ) , padEnd ( date . getMilliseconds ( ) ) ] . join ( DELIMITERS . time ) ; return `[${ logDate } ${ logTime }]` ; } private prepareMessageFromArgs ( args ) { return args . map ( it => { const type = typeof it ; if ( [ 'number' , 'string' , 'undefined' ] . includes ( type ) || it === null ) { return it ; } if ( it instanceof Error ) { return `${ it . stack || it . message || it }` ; } return `${ JSON . stringify ( it , null , 2 ) }` ; } ) . join ( DELIMITERS . logMessage ) ; } }