[Dev Infrastructure] Docker-compose logging in CircleCi

I'm running docker-compose services as daemons in my CircleCI configuration. It looks a bit like this:

# circle.yml
version: 2  
jobs:  
  build:
    ...
    steps:
      ...
      - run:
          name: Start docker resources
          command: |
            set -e
            docker-compose -f circleci-docker-compose.yml up -d (service)
            ...
      - run:
          name: run test
          ...

Here's the problem though: there was a problem happening in one of the services I'm running, but there's no way to debug it the way it is written because I can't see the console output of the docker containers run with the -d option.

At first, I tried creating a log artifact by piping the docker-compose log output to a file, then using - store_artifacts to save those files as CircleCI artifacts. I could see the logs, but it turned out to be a huge pain in the ass to actually view the log files...

To view them, you have to click on the artifacts section in the build summary window and then download the file. This is pretty obscure, and it is also not apparent to someone viewing the output, trying to understand why a test failed.

I fixed this by writing the output of the container log to the console! A much better solution, but I found out about it in a really roundabout way. It turns out that - run steps have an optional field called when, which default to on_success, ensuring that the step is only run if the previous steps succeed. Setting the value to on_fail or always tells Circle to run the step even if previous steps failed. You can use this to output the Docker container logs if the build/test fails:

# circle.yml
version: 2  
jobs:  
  build:
    ...
    steps:
      ...
      - run:
          name: Start docker resources
          command: |
            set -e
            docker-compose -f circleci-docker-compose.yml up -d (service)
            ...
      - run:
          name: run test
          ...
      - run:
          name: "Failure: output container logs to console"
          command: |
            docker-compose -f circleci-docker-compose.yml logs (service)
          when: on_fail

Viola. You can now view the Docker logs in the regular view, making it much simpler to debug.