Duplicated logs Flask - Google Cloud Logging

Viewed 380

I'm developing a web application in Flask, using GAE. My issue here is: Every time that my application tries to log, i got multiple entries on log file: log viewer . My dbconnection class only imports a default logger class that i created and calls unexpected_error_log() to write whenever it needed.

My logger class:

import logging
from google.cloud import logging as cloudlogging

class LoggerDB:
    def __init__(self):
        log_client = cloudlogging.Client()
        log_handler = log_client.get_default_handler()
        self.cloud_logger = logging.getLogger("cloudLogger")
        self.cloud_logger.setLevel(logging.INFO)
        self.cloud_logger.addHandler(log_handler)

    def unexpected_error_log(self, name, error="Unhandled Exception"):
        self.cloud_logger.error("Unexpected Error on %s: %s", name, error)

Code when executed:

def insertVenda(self, venda):
    try:
        query = "xxxxx"
        self.cursor.execute(query)
        self.connection.commit()
        return "Success"
    except Exception as error:
        self.logger.unexpected_error_log(__name__, error)
        self.connection.rollback()
        return "Error"

I suspect that gunicorn/app logging is duplicating my logs, but i don't know how to handle this case. Did someone had the same problem?

1 Answers

I am struggling with this at the moment, my suspicion at the moment if you include something like this:

# Imports Python standard library logging
import logging

import google.cloud.logging

# Instantiates a client
client = google.cloud.logging.Client()

# Retrieves a Cloud Logging handler based on the environment
# you're running in and integrates the handler with the
# Python logging module. By default this captures all logs
# at INFO level and higher
client.get_default_handler()
client.setup_logging()

I get logs OK, but multiple duplicates. If I omit I just get single stdout print statements going to the stackdriver logs.

Related