Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kylejeske/630ee2df190d4b8a52731f2ef1e40358 to your computer and use it in GitHub Desktop.
Save kylejeske/630ee2df190d4b8a52731f2ef1e40358 to your computer and use it in GitHub Desktop.
Overrides the console.log (specifically this is for node.js) with an ISO timestamp prefix and still handles string interpolation formats.
import { debuglog, format } from "util";
import { Console } from "console";
type LoggerOverrideFunction = (...args: any) => void;
type InjectedConsole = {
info: LoggerOverrideFunction;
log: LoggerOverrideFunction;
warn: LoggerOverrideFunction;
};
const LoggerOverride: LoggerOverrideFunction = function (this: InjectedConsole, ...args: any): void {
process.env.NODE_DEBUG ??= "false";
if (process.env.NODE_DEBUG !== "false") {
const debuglogger = debuglog(process.env.NODE_DEBUG);
debuglogger("[LOG]", format.apply(format.prototype, args));
return void 0;
}
process.stdout.write(
format("%s\n", args),
(err) => {
if (err) {
process.stderr.write(`Error occurred during stdout::write. Error: ${err?.message}`)
}
}
);
return void 0;
}
Object.assign<Console, InjectedConsole>(Console.prototype, {
info: LoggerOverride,
log: LoggerOverride,
warn: LoggerOverride
})
globalThis.console = (new Console({ stdout: process.stdout, stderr: process.stderr }));
export default globalThis.console;
// usage: import * as console from "./console-log-format-timestamp"
// NODE_DEBUG node ./this-file.js
// console.log("...anything...")
//
var util_1 = require("util");
var console_1 = require("console");
var LoggerOverride = function () {
var _a;
var _b;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
(_a = (_b = process.env).NODE_DEBUG) !== null && _a !== void 0 ? _a : (_b.NODE_DEBUG = "false");
if (process.env.NODE_DEBUG !== "false") {
var debuglogger = (0, util_1.debuglog)(process.env.NODE_DEBUG);
debuglogger("[LOG]", util_1.format.apply(util_1.format.prototype, args));
return void 0;
}
process.stdout.write((0, util_1.format)("%s\n", args), function (err) {
if (err) {
process.stderr.write("Error occurred during stdout::write. Error: ".concat(err === null || err === void 0 ? void 0 : err.message));
}
});
return void 0;
};
Object.assign(console_1.Console.prototype, {
info: LoggerOverride,
log: LoggerOverride,
warn: LoggerOverride
});
globalThis.console = (new console_1.Console({ stdout: process.stdout }));
exports.default = globalThis.console;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment