gplayer
gplayer

Reputation: 1811

Logging from python in cloudbuild doesn't work

I'm running a cloudbuild with one of the steps:

- name: "gcr.io/something"
id: DO-STUFF
entrypoint: python
args: ['some_script.py']
waitFor:
  - WHATEVER

Inside my some_script.py I have some log statements:

...
LOGGER = logging.getLogger(__name__)
...
LOGGER.info('Did work.')
...

Running the cloudbuild runs the script successfully, but I see no logs in the cloudbuild logs. How can I get them to be added there?

Upvotes: 1

Views: 530

Answers (1)

guillaume blaquiere
guillaume blaquiere

Reputation: 75705

You have to configure your logger to print the logs in the stdout stream. Update your code like this:

...
LOGGER = logging.getLogger(__name__)
...
import sys
out_hdlr = logging.StreamHandler(sys.stdout)
# Format the output as you want. Let only the message if you don't care about other fields
out_hdlr.setFormatter(logging.Formatter('%(asctime)s %(message)s'))
out_hdlr.setLevel(logging.INFO)
LOGGER.addHandler(out_hdlr)
...
LOGGER.info('Did work.')
...

UPDATE

Here my exact test process

Script to execute script_log.py

import logging
import sys
print("line0")
log = logging.getLogger()
out_hdlr = logging.StreamHandler(sys.stdout)
out_hdlr.setFormatter(logging.Formatter('%(message)s'))
out_hdlr.setLevel(logging.INFO)
log.addHandler(out_hdlr)
log.setLevel(logging.INFO)

log.info("THIS IS AN ERROR")

Cloud Build file definition (cloudbuild.yaml file)

steps:
        - name: gcr.io/cloud-builders/gcloud
          entrypoint: "bash"
          args:
                  - "-c"
                  - |
                          python3 script_log.py

Here the result of the command gcloud builds submit

Operation completed over 1 objects/415.0 B.
BUILD
Already have image (with digest): gcr.io/cloud-builders/gcloud
line0
THIS IS AN ERROR
PUSH
DONE

And the log in the stackdriver logging

enter image description here

The only difference is that I don't have the __name__ in the getLogger()

Upvotes: 1

Related Questions