Skip to content

Commit

Permalink
feat: add optional delimiter and styles for createLogger
Browse files Browse the repository at this point in the history
  • Loading branch information
Dzianis Dashkevich committed Sep 20, 2023
1 parent 9e06919 commit cde0aca
Showing 1 changed file with 24 additions and 6 deletions.
30 changes: 24 additions & 6 deletions src/js/utils/create-logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,11 @@ let history = [];
*
* @param {Object} log
* The arguments to be passed to the matching console method.
*
* @param {string} [styles]
* styles for name
*/
const LogByTypeFactory = (name, log) => (type, level, args) => {
const LogByTypeFactory = (name, log, styles) => (type, level, args) => {
const lvl = log.levels[level];
const lvlRegExp = new RegExp(`^(${lvl})$`);

Expand All @@ -27,6 +30,11 @@ const LogByTypeFactory = (name, log) => (type, level, args) => {
args.unshift(type.toUpperCase() + ':');
}

if (styles) {
name = `%c${name}`;
args.unshift(styles);
}

// Add console prefix after adding to history.
args.unshift(name + ':');

Expand Down Expand Up @@ -66,7 +74,7 @@ const LogByTypeFactory = (name, log) => (type, level, args) => {
fn[Array.isArray(args) ? 'apply' : 'call'](window.console, args);
};

export default function createLogger(name) {
export default function createLogger(name, delimiter = ':', styles = '') {
// This is the private tracking variable for logging level.
let level = 'info';

Expand Down Expand Up @@ -99,22 +107,32 @@ export default function createLogger(name) {
};

// This is the logByType helper that the logging methods below use
logByType = LogByTypeFactory(name, log);
logByType = LogByTypeFactory(name, log, styles);

/**
* Create a new sublogger which chains the old name to the new name.
* Create a new subLogger which chains the old name to the new name.
*
* For example, doing `videojs.log.createLogger('player')` and then using that logger will log the following:
* ```js
* mylogger('foo');
* // > VIDEOJS: player: foo
* ```
*
* @param {string} name
* @param {string} subName
* The name to add call the new logger
* @param {string} [subDelimiter]
* Optional delimiter
* @param {string} [subStyles]
* Optional styles
* @return {Object}
*/
log.createLogger = (subname) => createLogger(name + ': ' + subname);
log.createLogger = (subName, subDelimiter, subStyles) => {
const resultDelimiter = subDelimiter || delimiter;
const resultStyles = subStyles || styles;
const resultName = `${name} ${resultDelimiter} ${subName}`;

return createLogger(resultName, resultDelimiter, resultStyles);
};

/**
* Enumeration of available logging levels, where the keys are the level names
Expand Down

0 comments on commit cde0aca

Please sign in to comment.