[tools] Safer handling of various encodings in OutputRedirect

This commit makes sure that no print would fail due to invalid encoding.

We try to encode anything to unicode before outputting to the log file,
and replace it with an escaped sequence on encoding/decoding errors.