Best Practice - Python Check if a GCP Log Exists

270 Views Asked by At

I'm in this situation where I need to verify, with python, if a certain GCP log exists. I've built a precise filter that, if the service works, return a single log. Else, doesn't return anything.

Here is my code, it works, but it doesn't seem a best practice at all.

from google.cloud import logging

logging_client = logging.Client.from_service_account_json(#service account here)
if len(list(logging_client.list_entries(filter_=filter) == 0:
    logger.warning('error')
else:
    entries = logging_client.list_entries(filter_=filter)
    for e in entries: 
        print(e)

It's heavy and calls the api twice, even if it's not necessary.

Do you have suggestions?

1

There are 1 best solutions below

1
Mazlum Tosun On

If I correctly understood your need, I think you can write your program with a single api call.

from google.cloud import logging

logging_client = logging.Client.from_service_account_json(#service account here)

# Your single api call here.
entries = logging_client.list_entries(filter_=filter)
if len(list(entries)) == 0:
    logger.warning('error')
else:
    for e in entries: 
        print(e)

Don't hesitate to correct me if I don't correctly understood your need.