I have a (Node)JS class:
class PayloadContainingError extends Error {
constructor(msg, payload) {
super(msg);
this.payload = payload;
}
}
payload
field may contain long strings, even in MB range.
If I console.log
this class at some point, I get the full payload
in the log.
Instead, I want it to log a truncated portion (like the Linux head
command).
E.g. if I console.error("Bad payload", instance_of_PayloadContainingError)
, instead of getting
Bad payload { Error: BAD
at foo.bar
payload:
'a possibly million-character long line that pollutes my log'
}
I want console
to log
Bad payload { Error: BAD
at foo.bar
payload:
'first 100 chars...'
}
Is this possible via some magic on the class/field level - without having to refactor any (existing and future) console.log
calls?
[Edit]
For those voting to close this question in favor of "JavaScript toString() override": per my understanding, toString()
is not the question here - console
seems to do beyond what toString()
usually does, when logging an error object (e.g. adding the stacktrace - which I don't want to reimplement anyway). (As mentioned in one of my comments, overriding toString()
does not change the output anyway.)