1
- """
2
- Use the influxdb_client together with python native logging
3
- """
1
+ """Use the influxdb_client with python native logging."""
4
2
import logging
5
3
6
4
from influxdb_client import InfluxDBClient
7
5
8
6
9
7
class InfluxLoggingHandler (logging .Handler ):
8
+ """
9
+ InfluxLoggingHandler instances dispatch logging events to influx.
10
+
11
+ There is no need to set a Formater.
12
+ The raw input will be passed on to the influx write api.
13
+ """
14
+
10
15
DEFAULT_LOG_RECORD_KEYS = logging .makeLogRecord ({}).__dict__ .keys ()
11
16
12
17
def __init__ (self , * , url , token , org , bucket , client_args = None , write_api_args = None ):
18
+ """
19
+ Initialize defaults.
20
+
21
+ The arguments `client_args` and `write_api_args` can be dicts of kwargs.
22
+ They are passed on to the InfluxDBClient and write_api calls respectively.
23
+ """
13
24
super ().__init__ ()
14
25
15
26
self .bucket = bucket
@@ -21,15 +32,17 @@ def __init__(self, *, url, token, org, bucket, client_args=None, write_api_args=
21
32
self .write_api = self .client .write_api (** write_api_args )
22
33
23
34
def __del__ (self ):
35
+ """Make sure all resources are closed."""
24
36
self .close ()
25
37
26
38
def close (self ) -> None :
39
+ """Close the write_api, client and logger."""
27
40
self .write_api .close ()
28
41
self .client .close ()
29
42
super ().close ()
30
43
31
44
def emit (self , record : logging .LogRecord ) -> None :
32
- """ Emit a record via the influxDB WriteApi """
45
+ """Emit a record via the influxDB WriteApi. """
33
46
try :
34
47
extra = self ._get_extra_values (record )
35
48
return self .write_api .write (record = record .msg , ** extra )
@@ -39,7 +52,11 @@ def emit(self, record: logging.LogRecord) -> None:
39
52
self .handleError (record )
40
53
41
54
def _get_extra_values (self , record : logging .LogRecord ) -> dict :
42
- """extracts all items from the record that were injected by logging.debug(msg, extra={key: value, ...})"""
55
+ """
56
+ Extract all items from the record that were injected via extra.
57
+
58
+ Example: `logging.debug(msg, extra={key: value, ...})`.
59
+ """
43
60
extra = {key : value
44
61
for key , value in record .__dict__ .items () if key not in self .DEFAULT_LOG_RECORD_KEYS }
45
62
if 'bucket' not in extra .keys ():
0 commit comments