Vastly mprove logging.

Try and output meaningful, machine readable logs. Code is repetitive in
places, especially error handling. Could do with a clean-up.