Skip to content

Instantly share code, notes, and snippets.

@oluwafenyi
Last active August 21, 2021 01:05
Show Gist options
  • Save oluwafenyi/8a41b64a7e0e797ed016387ef24b3abd to your computer and use it in GitHub Desktop.
Save oluwafenyi/8a41b64a7e0e797ed016387ef24b3abd to your computer and use it in GitHub Desktop.
Firesore Log Handler for Python
from logging import Handler
from firebase_admin import firestore
class FirestoreHandler(Handler):
def __init__(self, operation_id: str):
super().__init__()
self.db = firestore.client()
self.collection = self.db.collection("logs")
self.document = self.collection.document(operation_id)
self.document.create({"stream": []})
def mapLogRecord(self, record):
"""
Default implementation of mapping the log record into a dict
that is sent as the CGI data. Overwrite in your class.
Contributed by Franz Glasner.
"""
return record.__dict__
def emit(self, record):
"""
Emit a record.
Send the record to firestore
"""
try:
data = self.mapLogRecord(record)
self.document.update({"stream": firestore.ArrayUnion([data])})
except Exception:
self.handleError(record)
import logging
import firebase_admin
from firebase_admin import credentials
from handler import FirestoreHandler
cred = credentials.Certificate("firebase-credentials.json")
firebase_admin.initialize_app(credential=cred)
logger = logging.getLogger(__name__)
logger.addHandler(FirestoreHandler(operation_id="any-id"))
logger.info("Hello Firebase")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment