Skip to content
Advertisement

Need help retrieving Google cloudSQL metadata and logs using Python

I am new to Google cloud and would like to know if there is a way to retrieve cloudSQL (MySQL) instance metadata and error logs using Python.

I installed the Google cloud SDK and ran the following commands to retrieve metadata and I got detailed metadata like IP, region, disk, etc.

gcloud sql instances describe my-instance-id

I need to check this data periodically for compliance. I have worked on AWS and I use boto3 Python package for these kind of tasks. I googled for boto3 equivalent in Google but the docs for Google API client are really confusing to me.

I also need to fetch MySQL error logs from cloudSQL instance (for alerting in case any errors are found).

Can anyone show me how to perform these operations using google API for python or point me in the right direction?

Advertisement

Answer

Here is a sample code on how to retrieve the Cloud SQL MySQL error logs using Cloud Logging API. For testing I logged in with a wrong password to generate error logs.

The filter used is a sample filter in the Cloud Logging docs.

from google.cloud.logging import Client

projectName = 'your-project-here'
myFilter = 'resource.type = "cloudsql_database" AND log_id("cloudsql.googleapis.com/mysql.err")'

client = Client(project = projectName)
entries = client.list_entries(filter_ = myFilter)
for entry in entries:
    print(entry)

Output snippet: enter image description here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement