import { cloneDeep } from 'lodash' ; import { Configuration } from './Configuration' ; import findRoot from 'find-root' ; import fs from 'fs' ; import { getLogEntryIdGenerator } from './getLogEntryIdGenerator' ; import { isLogLevel } from './isLogLevel' ; import { Logger } from './Logger' ; import os from 'os' ; import { PackageJson } from './PackageJson' ; import { processenv } from 'processenv' ; import { readPackageJson } from './readPackageJson' ; import stackTrace from 'stack-trace' ; import { asHumanReadable , asJson } from './formatters' ; class Flaschenpost { protected configuration : Configuration ; public constructor ( ) { const stringifiedDebugModuleFilter = processenv ( 'LOG_DEBUG_MODULE_FILTER' , '' ) ; if ( typeof stringifiedDebugModuleFilter !== 'string' ) { throw new Error ( 'Debug module filter invalid.' ) ; } const debugModuleFilter = stringifiedDebugModuleFilter . split ( ',' ) . filter ( ( item ) : boolean => Boolean ( item ) ) ; let formatter = process . stdout . isTTY ? asHumanReadable : asJson ; const formatterOverride = processenv ( 'LOG_FORMATTER' ) ; if ( formatterOverride ) { formatter = formatterOverride === 'human' ? asHumanReadable : asJson ; } const logLevel = processenv ( 'LOG_LEVEL' , 'info' ) ; if ( ! isLogLevel ( logLevel ) ) { throw new Error ( `Log level '${ logLevel }' unknown.` ) ; } const highestEnabledLogLevel = logLevel ; const hostname = os . hostname ( ) ; const logEntryIdGenerator = getLogEntryIdGenerator ( ) ; this . configuration = new Configuration ( debugModuleFilter , formatter , highestEnabledLogLevel , hostname , logEntryIdGenerator ) ; } public configure ( configuration ) { this . configuration = configuration ; } public getConfiguration ( ) { return cloneDeep ( this . configuration ) ; } public getLogger ( sourcePathOverride ? , packageJsonOverrideForVirtualSourcePaths ? ) { let sourcePath ; let packageJson ; if ( sourcePathOverride ) { if ( ! packageJsonOverrideForVirtualSourcePaths ) { fs . accessSync ( sourcePathOverride , fs . constants . R_OK ) ; } sourcePath = sourcePathOverride ; } else { sourcePath = stackTrace . get ( ) [ 1 ] . getFileName ( ) ; } if ( packageJsonOverrideForVirtualSourcePaths ) { packageJson = packageJsonOverrideForVirtualSourcePaths ; } else { const modulePath = findRoot ( sourcePath ) ; packageJson = readPackageJson ( modulePath ) ; } return new Logger ( this . configuration , sourcePath , packageJson ) ; } } const flaschenpost = new Flaschenpost ( ) ; export { flaschenpost , Flaschenpost } ;