Logging is very important part of application development process, Backend frameworks have got this thing sorted, but in frontend we still struggles with console.log and when something unexpected happens it becomes very confusing to check logs.

Given above problem i decide to write my own logger strategy using react hooks, and created my own useLogger React Hook

Following are the libraries used:

utils/log.js:

import {useMemo} from 'react';
import log from 'loglevel';
import prefix from 'loglevel-plugin-prefix';
import chalk from 'chalk';
const colors = new chalk.Instance({level: 3});

const levelColors = {
    TRACE: colors.magenta,
    DEBUG: colors.cyan,
    INFO: colors.blue,
    WARN: colors.yellow,
    ERROR: colors.red,
};
prefix.reg(log);
log.enableAll();

prefix.apply(log, {
    format(level, name, timestamp) {
        return `${chalk.gray(`[${timestamp}]`)} ${levelColors[level.toUpperCase()](level)} ${colors.green.bold(`${name}:`)}`;
    },
});

prefix.apply(log.getLogger('critical'), {
    format(level, name, timestamp) {
        return colors.red.bold(`[${timestamp}] ${level} ${name}:`);
    },
});

export const useLogger = (name) => {
    let logger = useMemo(()=> {
        return log.getLogger(name);
    }, [name]);
    return logger;
}


In above `utils/log.js` file we are configuring loglevel with its prefix plugin, you can change the colors and format as per your need. Lastly we are defining a hook called useLogger that takes name (Component name) as input and returns the logger  with this name as prefix. Here we are using useMemo to not cache the loggers for same name.

Usages:

import {useLogger} from '../utils/log.js';


const ReactComp = (props) => {
  const log = useLogger('ReactComp');
  log.info('Inside');
  log.debug('Some debug message');
  return <p>Logging Example</p>;
}

This will print logs with some informative info and colors, so that you can easily find whats happening inside.

You can extend this further and can connect with any remote logger like loggly for your react-native app.