0

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?

Girolamo
  • 326
  • 3
  • 11

1 Answers1

1

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.

Mazlum Tosun
  • 5,761
  • 1
  • 9
  • 23
  • Hi and thanks, I've already tried that but searching for the lenght of the list, seems to actually make an API call. Because calling entries = logging_client.list_entries(filter_=filter) does not store the entries in memory. If you first perform a len(list(entries)) and then try to do something with entries, you'll find an empty variable. – Girolamo Nov 15 '22 at 08:16