Added logging, improved error handling, and added a `query` keyword argument.