import fs from 'fs' ; import path from 'path' ; import bunyan from 'bunyan' ; import * as ts from '@terascope/utils' ; import * as i from '../interfaces' ; type LogLevelObj = { [ type in i . LogType ] : i . LogLevelType ; } ; function getLogLevel ( level ) { if ( typeof level === 'string' ) { return { console : level as i . LogLevelType , file : level as i . LogLevelType } ; } return level . reduce ( ( prev , curr ) => { Object . assign ( prev , curr ) ; return prev ; } , { } as LogLevelObj ) ; } export function createRootLogger ( context ) { const useDebugLogger = ts . toBoolean ( process . env . USE_DEBUG_LOGGER || ts . isTest ) ; const filename = context . name ; const name = context . assignment || filename ; const foundationConfig = context . sysconfig . terafoundation ; const logLevel = getLogLevel ( foundationConfig . log_level ) ; if ( useDebugLogger ) { return ts . debugLogger ( `${ filename }:${ name }` ) ; } const streamConfig = [ ] ; const { environment = 'development' } = foundationConfig ; if ( environment === 'development' || ts . includes ( foundationConfig . logging , 'console' ) ) { const level = logLevel . console ? logLevel . console : 'info' ; streamConfig . push ( { stream : process . stdout , level } ) ; } if ( ts . includes ( foundationConfig . logging , 'file' ) ) { const configPath = foundationConfig . log_path || './logs' ; const logfile = filename . trim ( ) ; try { const pathCheck = fs . lstatSync ( fs . realpathSync ( configPath ) ) ; if ( pathCheck . isDirectory ( ) ) { const level = logLevel . file ? logLevel . file : 'info' ; streamConfig . push ( { path : path . join ( configPath , `${ logfile }.log` ) , level } ) ; } else { throw new Error ( `${ configPath } is not a directory` ) ; } } catch ( e ) { throw new Error ( `Could not write to log_path: ${ configPath }` ) ; } } const loggerConfig = { name : filename , streams : streamConfig , assignment : context . assignment , } ; const logger = bunyan . createLogger ( loggerConfig ) as ts . Logger ; logger . flush = async ( ) => true ; return logger ; }