Search code examples
pythonflaskgoogle-cloud-platformgunicornstackdriver

Flask logs not showing up in GCP log viewer


I've developed a simple flask web app and deployed it to a GCP compute engine. Using gunicorn I can run the program and it works. I followed this guide https://cloud.google.com/logging/docs/setup/python to set up logging.

import google.cloud.logging
import logging

client = google.cloud.logging.Client()

client.setup_logging()

logging.info('PROGRAM STARTED') 

This code snippet from my app appears to be working. I see the "program started" log in the log viewer. My problem is I cannot find any logs from flask such as the http requests or errors. I'm trying to understand how this works, as I'm new to both GCP and logging practices. Any tips or hints? Thanks in advance!


Solution

  • Are you doing both of these at the same time? If you wish to use python's built-in logging, then just have

    import logging
    

    create a logger, named for each python module it is deployed into, with

    logger = logging.getLogger(__name__)
    

    and use it (minimally) with

    logger.info('my log entry')
    

    There's lots of configuration, filtering, etc on this through the documentation. I cannot comment on the Google logger, but they do say to use either it or the regular python logger.

    The following is an example of how to capture all or (more likely a selection) of flask's http interations (although maybe more complex than you need):

    @app.before_request
    def log_request_info():
        if current_user.is_authenticated:
            if not current_user.is_superuser and \
                    not any([(term in str(request)) for term in ['static', 'favicon', 'images']]):
                app.logger.info('%s, %s' % (
                    str(current_user), request.url[len(request.url_root):][:50]))
        else:
            if not any([(term in str(request)) for term in ['api', 'static', 'favicon']]):
                app.logger.info('unauthorised: %s' % (request.url[len(request.url_root):]))
    

    Note: there is a more powerful alternative to this: the filtering option to the logger construction.