UNPKG

logpack

Version:

A lightweight and zero dependency logging package for React and Next.js.

70 lines (69 loc) 2.22 kB
import { isServer } from './shared/lib'; import { LogLevel } from './types'; class Logpack { constructor() { throw new Error('Logpack is a static class and cannot be instantiated.'); } static configure(config) { this.globalConfig = Object.assign(Object.assign({}, this.globalConfig), config); } static info(message, config) { this.dispatch(message, LogLevel.LOG, config); } static warn(message, config) { this.dispatch(message, LogLevel.WARN, config); } static error(message, config) { this.dispatch(message, LogLevel.ERROR, config); } static dispatch(message, level, config) { const mergedConfig = Object.assign(Object.assign({}, this.globalConfig), config); if (!mergedConfig.display) { return; } const formattedMessage = this.formatMessage(message); const time = this.getTime(mergedConfig.locale, mergedConfig.dateFormat); let constructedMessage = ''; if (mergedConfig.displayLevel) { const identifier = level === LogLevel.LOG ? 'INFO' : level; constructedMessage += `[${identifier.toUpperCase()}] `; } if (mergedConfig.displayDate) { constructedMessage += `[${time}] `; } constructedMessage += formattedMessage; if (mergedConfig.displayColor) { console[level](constructedMessage); } else { console.log(constructedMessage); } } static formatMessage(message) { if (isServer && typeof message === 'object') { return JSON.stringify(message, null, '\t'); } return message; } } Logpack.globalConfig = { locale: 'en-US', dateFormat: { second: '2-digit', hour: '2-digit', minute: '2-digit', day: '2-digit', month: '2-digit', year: 'numeric', }, display: true, displayColor: true, displayDate: true, displayLevel: true, }; Logpack.getTime = (locale, dateFormat) => { const now = new Date(); const formatted = now.toLocaleString(locale, dateFormat).replace(',', ''); return formatted; }; export default Logpack;