Based on bitcoin/bitcoin#13021 but implemented from scratch. This introduces a cyclic dependency between `logging` and `util` that should be cleaned up in a future PR.