Skip to content

Instantly share code, notes, and snippets.

@vzakharov
Created March 9, 2023 10:25
Show Gist options
  • Save vzakharov/2aea6dd3da28b10b26e5a33e07741023 to your computer and use it in GitHub Desktop.
Save vzakharov/2aea6dd3da28b10b26e5a33e07741023 to your computer and use it in GitHub Desktop.
Log in the moment
// The purpose of this util is to only prominently log the piece of code we're currently working on.
// This is done by keeping track of a "last log index" in a separate project file (json). Whenever we want to log something new, we first check the last log index and then create a new logging function with a higher index (the util automatically updates the json).
// So the common interface is to do:
// ```
// import { logger } from '~/utils/logger';
// const log = logger(1);
// // or logger(2), logger(3), etc. or logger('always') if we want to always log
// // or logger(1, 'green') if we want to log in green by default
// log('Hello world!');
// // or log.green('Hello world!'), where log modifiers are taken from the `ansi-colors` package
// ```
// The util will only log the message if the index is equal to the last log index. This way, we can easily switch between logging different contexts by changing the index, without cluttering the console with logs from other contexts which are no longer relevant.
import c from 'ansi-colors';
import fs from 'fs';
export type LoggerStyle = keyof typeof c;
import { lastLogIndex } from '~/logger.json';
// Note that this file should be created manually with the following content:
// {
// "lastLogIndex": 0
// }
// Your framework should also allow importing json files.
export const loggerInfo = {
lastLogIndex
};
export type LogFunction = (...args: any[]) => void;
export type StyledLog = {
[style in LoggerStyle]: LogFunction;
}
export type Log = LogFunction & StyledLog;
export function logger(index: number | 'always', defaultStyle?: LoggerStyle) {
if ( index !== 'always' && index > loggerInfo.lastLogIndex ) {
loggerInfo.lastLogIndex = index;
fs.writeFileSync('./logger.json', JSON.stringify({ lastLogIndex: index }, null, 2));
}
function logWithStyle(style: LoggerStyle | undefined, ...args: any[]) {
if ( index === 'always' || index === loggerInfo.lastLogIndex ) {
let formatFunction = (arg: any) => arg;
if ( style ) {
let func = c[style] as Function;
if ( typeof func !== 'function' ) throw new Error(`"${style}" is not a valid style function.`);
formatFunction = (arg: any) => func(arg);
}
console.log(...args.map(formatFunction));
}
}
const log = <Log>logWithStyle.bind(null, defaultStyle);
for ( const style of Object.keys(c) ) {
log[style as LoggerStyle] = (...args: any[]) => logWithStyle(style as LoggerStyle, ...args);
}
return log;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment