UNPKG

@mobileaction/ui-modules

Version:

Mobile Action common modules for Vue projects

88 lines (80 loc) 2.78 kB
const LOGGER_CONFIG = { default: { style: { marginRight: '2px', padding: '1px 3px', borderRadius: '3px', }, type: 'log', }, log: { type: 'log', }, error: { style: { color: '#ffffff', backgroundColor: '#ff0000', }, type: 'error', }, info: { style: { color: '#ffffff', backgroundColor: '#00bfff', }, type: 'info', }, warn: { style: { color: '#ffffff', backgroundColor: '#ffa500', }, type: 'warn', }, debug: { style: { padding: '1px 3px 1px 0', borderRight: '2px solid #333333', }, type: 'verbose', }, }; Object.keys(LOGGER_CONFIG).forEach((key) => { LOGGER_CONFIG[key].style = Object.assign({}, LOGGER_CONFIG.default.style, LOGGER_CONFIG[key].style); }); const LOG_TYPES = ['log', 'info', 'warn', 'error', 'debug']; const toKebabCase = str => str.replace(/[A-Z\u00C0-\u00D6\u00D8-\u00DE]/g, match => '-' + match.toLowerCase()); const configToStyle = cfg => Object.keys(cfg).map(k => toKebabCase(k) + ': ' + cfg[k]).join(';'); const colorize = (cfg, str) => [`%c${ str }`, configToStyle(cfg)]; /** * logger that wrap around console ones * @param _vue_el {Vue} element identifier * @param name {string} alternative name of logger * @param isDebug {function|boolean} debug checking function/value * @returns {Object} * @private */ export function MaLogger(_vue_el, { name, isDebug }) { // install function let _name = typeof _vue_el === 'string' ? _vue_el : name; let _isDebug = typeof isDebug === 'boolean' ? () => isDebug : isDebug; const _loggerName = (_vue_el && _vue_el.$options && _vue_el.$options.__file || _name) .replace(/^\/?client\/src\//, '').replace(/\.(js|vue)$/, ''); const loggerNameByType = {}; LOG_TYPES.forEach((logType) => { // color logger names according to type if in debug otherwise color codes mess up logging loggerNameByType[logType] = _isDebug() ? colorize(LOGGER_CONFIG[logType].style, _loggerName) : [_loggerName]; this[logType] = (...args) => { // for webpack 5 and SSR compatibility if (typeof process !== 'undefined' && process && process.server) { return; } if (logType !== 'debug' || _isDebug()) { // make sure log type exists // eslint-disable-next-line no-console const logFunc = console[logType] || console.trace || console.log; logFunc(...loggerNameByType[logType], ...args); } }; }); } export default MaLogger;