22Python client API for cwlogs daemon
33"""
44
5- from __future__ import annotations
6-
5+ import json
76import socket
87import time
98
10- import orjson
11-
129
1310def _checktype (value , types , message ):
1411 if not isinstance (value , types ):
1512 raise TypeError (message )
1613
1714
18- def log_event (message : str | bytes , retries = 10 , wait = 0.1 ):
15+ def log_event (message , retries = 10 , wait = 0.1 ):
1916 """
2017 Log the @message string to cloudwatch logs, using the current time.
21- message: bytes (valid utf8 required) or str .
18+ message: bytes (valid utf8 required) or unicode .
2219 retries: number of retries to make on failed socket connection
2320 wait: number of seconds to wait between retries
2421 Raises: exception if the message is too long or invalid utf8
2522 Raises: exception if the daemon is down or too backlogged
2623 Returns when the message was queued to the daemon's memory queue.
2724 (Does not mean the message is safe in cloudwatch)
2825 """
29-
26+ # python3 json library can't handle bytes, so preemptively decode utf-8
3027 if isinstance (message , bytes ):
3128 message = message .decode ("utf-8" )
32- _checktype (message , str , "message type must be bytes or str " )
29+ _checktype (message , str , "message type must be bytes or unicode " )
3330
3431 _checktype (retries , int , "retries must be an int" )
3532 if retries < 0 :
@@ -39,10 +36,9 @@ def log_event(message: str | bytes, retries=10, wait=0.1):
3936 if wait < 0 :
4037 raise ValueError ("wait must be non-negative" )
4138
42- req = {
43- "message" : message ,
44- "timestamp" : int (time .time () * 1000 ),
45- }
39+ req = {}
40+ req ["message" ] = message
41+ req ["timestamp" ] = int (time .time () * 1000 )
4642 return _request (req , retries , wait )
4743
4844
@@ -68,21 +64,24 @@ def _connect(retries, wait):
6864
6965
7066def _request (req , retries , wait ):
71- buf = orjson .dumps (req ) + b"\n "
67+ buf = json .dumps (req , indent = None ) + "\n "
68+ # dumps returns unicode with python3, but sock requires bytes
69+ if isinstance (buf , str ):
70+ buf = buf .encode ("utf-8" )
7271
7372 sock = _connect (retries , wait )
7473 sock .sendall (buf )
7574
76- resp = b ""
75+ resp = ""
7776 while True :
7877 chunk = sock .recv (4000 )
7978 if not chunk :
8079 raise Exception ("no data" )
81- resp += chunk
82- if chunk .endswith (b "\n " ):
80+ resp += chunk . decode ( "utf-8" )
81+ if resp .endswith ("\n " ):
8382 break
8483
85- d = orjson .loads (resp [:- 1 ])
84+ d = json .loads (resp [:- 1 ])
8685 if isinstance (d , dict ):
8786 status = d ["status" ]
8887 if status == "ok" :
0 commit comments