UNPKG

@augment-vir/common

Version:

A collection of augments, helpers types, functions, and classes for any JavaScript environment.

86 lines (85 loc) 2.6 kB
import { isRuntimeEnv, RuntimeEnv } from '@augment-vir/core'; import { addPrefix } from '../string/prefix.js'; import { LogOutputType } from './log-colors.js'; import { createLogger } from './logger.js'; /** * Default implementation of {@link LogWriters} that is dependent on the current runtime environment. * * @category Log : Util * @category Package : @augment-vir/common * @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) */ export const defaultLogWriters = /** We calculate coverage in web, so the node code will never run in coverage tests. */ /* node:coverage disable */ isRuntimeEnv(RuntimeEnv.Node) ? { [LogOutputType.Error]({ text }) { process.stderr.write(text + '\n'); }, [LogOutputType.Standard]({ text }) { process.stdout.write(text + '\n'); }, } : /* node:coverage enable */ { [LogOutputType.Error]({ text, css }) { console.error(addPrefix({ value: text, prefix: '%c' }), css); }, [LogOutputType.Standard]({ text, css }) { // eslint-disable-next-line no-console console.log(addPrefix({ value: text, prefix: '%c' }), css); }, }; /** * The default `log`. Use this in place of `console` methods for styled outputs in both Node.js and * the browser. * * @category Log * @category Package : @augment-vir/common * @example * * ```ts * import {log} from '@augment-vir/common'; * * log.info('hi'); * log.error('failure'); * ``` * * @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) */ export const log = createLogger(defaultLogWriters); /** * Creates a custom logger that doesn't actually log but stores the logs into a object for later * usage. This is particularly useful in tests. * * @category Log * @category Package : @augment-vir/common * @example * * ```ts * import {createArrayLogger} from '@augment-vir/common'; * * const {log, logs} = createArrayLogger(); * * log.info('hi'); * // `logs[LogOutputType.Standard]` is now `['hi']` * ``` * * @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common) */ export function createArrayLogger(options) { const logs = { [LogOutputType.Standard]: [], [LogOutputType.Error]: [], }; const log = createLogger({ stderr({ text }) { logs.stderr.push(text); }, stdout({ text }) { logs.stdout.push(text); }, }, options); return { log, logs }; }