|
| 1 | +""" |
| 2 | +Show the usage of influx with python native logging. |
| 3 | +
|
| 4 | +This is useful if you |
| 5 | +* want to log to influx and a local file. |
| 6 | +* want to set up influx logging in a project without specifying it in submodules |
| 7 | +""" |
| 8 | +import datetime |
| 9 | +import logging |
| 10 | +import time |
| 11 | + |
| 12 | +from influxdb_client import InfluxLoggingHandler, WritePrecision, Point |
| 13 | + |
| 14 | +DATA_LOGGER_NAME = '…' |
| 15 | + |
| 16 | + |
| 17 | +def setup_logger(): |
| 18 | + """ |
| 19 | + Set up data logger with the influx logging handler. |
| 20 | +
|
| 21 | + This can happen in your core module. |
| 22 | + """ |
| 23 | + influx_logging_handler = InfluxLoggingHandler(url="…", token="…", org="…", bucket="…", |
| 24 | + client_args={'arg1': '…'}, |
| 25 | + write_api_args={'arg': '…'}) |
| 26 | + influx_logging_handler.setLevel(logging.DEBUG) |
| 27 | + |
| 28 | + data_logger = logging.getLogger(DATA_LOGGER_NAME) |
| 29 | + data_logger.setLevel(logging.DEBUG) |
| 30 | + data_logger.addHandler(influx_logging_handler) |
| 31 | + # feel free to add other handlers here. |
| 32 | + # if you find yourself writing filters e.g. to only log points to influx, think about adding a PR :) |
| 33 | + |
| 34 | + |
| 35 | +def use_logger(): |
| 36 | + """Use the logger. This can happen in any submodule.""" |
| 37 | + # `data_logger` will have the influx_logging_handler attached if setup_logger was called somewhere. |
| 38 | + data_logger = logging.getLogger(DATA_LOGGER_NAME) |
| 39 | + # write a line yourself |
| 40 | + data_logger.debug(f"my-measurement,host=host1 temperature=25.3, {int(time.time() * 1e9)}") |
| 41 | + # or make use of the influxdb helpers like Point |
| 42 | + data_logger.debug( |
| 43 | + Point('my-measurement') |
| 44 | + .tag('host', 'host1') |
| 45 | + .field('temperature', 25.3) |
| 46 | + .time(datetime.datetime.utcnow(), WritePrecision.MS) |
| 47 | + ) |
0 commit comments