DEV Community

Marjori Pomarole
Marjori Pomarole

Posted on

Google Cloud Log severity in Django deployed on Cloud Run

When deploying a Django/python application to Google Run, logs sent to console will automatically get picked up by Google's Ops agent (based on Fluent Bit).

Screen Shot 2021-08-28 at 10.31.47

The only problem is that log severity does not get picked up automatically if you are using python's logging library.

Even when logging like the following:

logging.warn('This should have WARNING level');
Enter fullscreen mode Exit fullscreen mode

Logs on Google's Log Explorer will all appear with level default.

To fix this, you will have to configure Django/python's LOGGING settings to use CloudLoggingHandler:

LOGGING = {
    'handlers':
        'console': {
            'level': get_env('LOG_LEVEL', 'WARNING'),
            'class': 'logging.StreamHandler'
        }
    },
    'root': {
        'handlers': ['console'],
        'level': get_env('LOG_LEVEL', 'WARNING'),
    }
}

// When running in an environemnt without gcloud auth credentials
if get_env('GOOGLE_LOGGING_ENABLED', False):
    try:
        import google.cloud.logging
        from google.auth.exceptions import GoogleAuthError

        client = google.cloud.logging.Client()
        client.setup_logging()

        LOGGING['handlers']['google_cloud_logging'] = {
            'level': get_env('LOG_LEVEL', 'WARNING'),
            'class': 'google.cloud.logging.handlers.CloudLoggingHandler',
            'client': client
        }

        LOGGING['root']['handlers'].append('google_cloud_logging')

    except GoogleAuthError as e:
        logger.exception('Google Cloud Logging handler could not be setup.')
Enter fullscreen mode Exit fullscreen mode

Now we successfully get to parse the severity metadata to create alarms and metrics dashboards.

Screen Shot 2021-08-28 at 10.49.55

Top comments (0)