Use google cloud logging handler with a .conf file

Viewed 250

I would like to use the logging handler provided by the Python SDK for my application to write logs within google cloud infrastructure.

Going through the official documentation, (https://cloud.google.com/logging/docs/setup/python), it appears you need to configure the logger with the dedicated handler with the application code. However, I manage logging configuration with a .conf file like the following :

[loggers]
keys=root, gunicorn.error

[handlers]
keys=console

[formatters]
keys=standard

[logger_root]
level=INFO
handlers=console

[logger_gunicorn.error]
level=ERROR
handlers=console
propagate=0
qualname=gunicorn.error

[handler_console]
class=StreamHandler
formatter=standard
args=(sys.stdout, )

[formatter_standard]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s


The configuration is loaded within the application code (a flask API) at init using :

logging.config.fileConfig('./logging.conf')

I do so because it's easier to manage configuration variations across different environment. However I cannot find the way to use this method with the google logging infrastructure.

1 Answers

Well, the best approach you can follow is using a handler as mentioned in this doc:

It’s possible to tie the Python logging module directly into Google Cloud Logging. To use it, create a CloudLoggingHandler instance from your Logging client.

A good starting code will be as follows:

import logging
import google.cloud.logging
from google.cloud.logging.handlers import CloudLoggingHandler, setup_logging

client = google.cloud.logging.Client()
handler = CloudLoggingHandler(client)

logging.config.fileConfig('./logging.conf')

setup_logging(handler)

logging.info("i'm a log :D")

You can give it a try.

Related