Amazingly useful python dev code for mongodb

def log_call(serialize=True):
  bf = inspect.currentframe().f_back
  l=inspect.getargvalues(bf).locals
  if 'self' in l:
    l.pop('self')
  m={"message": bf.f_code.co_name, 'counter' : inc_counter()['counter'], 'timestamp' : 
    timestamp()}
  dct = {**m, **l}
  #msgs.append(dct)
  if serialize:
      print("jsons - ", jsons.dumps(dct))
      db.messages.insert_one(jsons.loads(jsons.dumps(dct)))
  else:
      print("call - ", dct)

customize to taste!

timestamp() returns epoch miliseconds. inc_counter() just increments a counter variable.

eg:

def test(p1,p2,p3, p4):
  custom = "Other"
  log_call()

test(1,2,3,{'z':1, 'y':{'v':4}})

jsons -  {"message": "test", "counter": 7283, "timestamp": 1603312127015.92, "custom" : "Other", "a": 1, "b": 2, "c": 3, "d": {"z": 1, "y": {"v": 4}}}

jsons does a pretty good job of dumping objects to json, even those that don’t support json serialization.

Would be curious if anyone knows any other code base that uses this approach . Would love to check out what they’re doing with it

My general experience is that API calls frequently translate to transactions, so this saves a lot of programming.

I’m trying to come up with useful query apis for this, but so far haven’t figured out anything that clever.

2 Likes