Preventing Logged Secrets in JavaScript

When I started working in the "real world" with sensitive credentials and data, I was very worried about logging that data. How do we avoid accidentally logging those secrets? The answers I've received have been "don't log them." This answer is unsatisfactory. It's the same type of advice as "drive safely," but any poorly designed street will have accidents given enough time. "Drive safe" asks for a system problem to be solved by individuals, which rarely works. "Don't log secrets" fails because of the same individual imperfections.

I wanted better guarantees that secrets weren't being logged, and I recently came across some code that does just that. Here is the snippet:

const databaseConnection = {
  user: "database",
};

Object.defineProperty(databaseConnection, 'password', {
  enumerable: false,
  value: mySecretPassword
});


// Doesn't show password!
console.log({databaseConnection}); // { user: "database" }

Setting enumerable to false ensures that if the databaseConnection is "console.log"-ed or "JSON.stringify"-ed the property won't be displayed or serialized. In fact, the default setting of Object.defineProperty is enumerable: false. However, it isn't the usual way of defining properties (at least in the code I've worked on), and so until today I didn't know about this nice trick to get a bit more safety for sensitive properties in our code.