debug() is a function that was created using util.debuglog(), which means that if you set the correct environment variable, the debug messages will be written to stderr, which you can then capture to a file (for instance):
env NODE_DEBUG=module node your-app.js 2> debug.log
EDIT: to capture these messages from within your own app, I think you have to resort to monkeypatching, for instance console.error()
let error = console.error.bind(console);
console.error = function() {
if (arguments[1] !== 'MODULE') {
return error.apply(this, arguments);
}
console.log('error log', arguments);
};
This code needs to run before any of the require() statements that you want to track, and it's not very robust (if the implementation of util.debuglog ever changes, it might break).