Skip to content

Instantly share code, notes, and snippets.

@ryasmi
Last active December 10, 2020 18:13
Show Gist options
  • Save ryasmi/8190b3490b69b6a9b54e45265b2a3521 to your computer and use it in GitHub Desktop.
Save ryasmi/8190b3490b69b6a9b54e45265b2a3521 to your computer and use it in GitHub Desktop.
A function to set the global log level in Node/Browser.

In PM2 you can use the PM2 time option to add timestamps to logs. In a Lambda, it automatically adds the timestamp to CloudWatch. I think the log level is also shown in CloudWatch. Ideally PM2 would output the level of the log too.

function getLogLevelValue(desiredLogLevel) {
switch (desiredLogLevel) {
case 'silly': return 0;
case 'debug': return 1;
case 'info': return 2;
case 'error': return 3;
default: return 2;
}
}
function createProtectedLog(minLogLevel, logFunction, logLevel) {
const logLevelValue = getLogLevelValue(logLevel);
if (logLevelValue >= minLogLevel) {
return (...args) => logFunction(...args);
}
return () => { return; };
};
export function setGlobalLogLevel(global, desiredLogLevel) {
const minLogLevel = getLogLevelValue(desiredLogLevel);
global.console.log = createProtectedLog(minLogLevel, global.console.log, 'silly');
global.console.debug = createProtectedLog(minLogLevel, global.console.debug, 'debug');
global.console.info = createProtectedLog(minLogLevel, global.console.info, 'info');
global.console.error = createProtectedLog(minLogLevel, global.console.error, 'error');
}
import { setGlobalLogLevel } from './setGlobalLogLevel';
setGlobalLogLevel(window, 'info');
console.log('log');
console.debug('debug');
console.info('info');
console.error('error');
import { setGlobalLogLevel } from './setGlobalLogLevel';
setGlobalLogLevel(global, process.env.LOG_LEVEL);
console.log('log');
console.debug('debug');
console.info('info');
console.error('error');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment