Logging, envvars and launch profile

This commit is contained in:
Emanuele Trabattoni
2025-05-02 10:01:35 +02:00
parent 267416395e
commit 2b20b22f7f
2 changed files with 98 additions and 21 deletions

25
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,25 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Python Debugger: Tikmon",
"type": "debugpy",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"env": {
"INTERVAL" : "5",
"INFLUXDB_TOKEN":"rg5dZrBHQxJTH4Etq2jmDduggCC28QaWcua0VVvW4hjsEVhy_JUpVhcyg-aLAbM-TXv92pTB7IGJlyAPvi7Kvw==",
"INFLUXDB_URL" : "http://10.0.2.249:4567",
"INFLUXDB_ORG" : "edelweiss",
"INFLUXDB_BUCKET" : "router",
"MIKROTIK_IP": "10.128.0.1",
"MIKROTIK_USER": "service",
"MIKROTIK_PASSWORD": "edxservice",
"LOG_FILE": "D:\\Test\\routermon.log",
"LOG_FILE_LVL": "WARNING",
"LOG_CLI_LVL": "DEBUG"
}
}
]
}

View File

@@ -1,35 +1,54 @@
import os
import sys
import json
import time
import logging
import signal
import json
import routeros_api
import influxdb_client
from influxdb_client import Point
from influxdb_client.client.write_api import ASYNCHRONOUS
INTERVAL = 5
INFLUXDB_TOKEN='rg5dZrBHQxJTH4Etq2jmDduggCC28QaWcua0VVvW4hjsEVhy_JUpVhcyg-aLAbM-TXv92pTB7IGJlyAPvi7Kvw=='
URL = "http://10.0.2.249:4567"
ORG = "edelweiss"
BUCKET = "router"
# Get environment variables
env = dict(os.environ)
LOGGER = None
class Runner:
running: property = True
def __init__(self):
signal.signal(signal.SIGINT, self.stop)
signal.signal(signal.SIGTERM, self.stop)
def stop(self, _):
self.running = False
def main():
write_client = influxdb_client.InfluxDBClient(url=URL, token=INFLUXDB_TOKEN, org=ORG)
INTERVAL = int(env['INTERVAL'])
# Init InfluxDB
write_client = influxdb_client.InfluxDBClient(url=env['INFLUXDB_URL'],
token=env['INFLUXDB_TOKEN'],
org=env['INFLUXDB_ORG'])
write_api = write_client.write_api(write_options=ASYNCHRONOUS)
connection = routeros_api.RouterOsApiPool('10.128.0.1', username='service', password='edxservice', plaintext_login=True)
# Init routerOS API
connection = routeros_api.RouterOsApiPool(env['MIKROTIK_IP'],
username=env['MIKROTIK_USER'],
password=env['MIKROTIK_PASSWORD'],
plaintext_login=True)
api = connection.get_api()
run = True
if_stats_old = None
run = Runner.running
last = 0
points = []
if_stats_old = None
### MAIN LOOP ###
while run:
try:
if_stats = api.get_resource('/interface/ethernet').call('print', {'proplist': 'name,rx-bytes,tx-bytes'})
hw_stats = api.get_resource('/system/resource').call('print', {'proplist':'uptime,cpu-load'})[0]
# calcolo della velocita' interfaccia a ogni ciclo
now = time.time()
points = []
for n,d in enumerate(if_stats):
for k,v in d.items():
if str.isdecimal(v):
@@ -43,20 +62,53 @@ def main():
.field('rx-rate', if_stats[n]['rx-rate'])
.field('tx-rate', if_stats[n]['tx-rate'])
)
write_api.write(bucket=BUCKET, org=ORG, record=points)
write_api.write(bucket=BUCKET, org=ORG,
rs1 = write_api.write(bucket=env['INFLUXDB_BUCKET'], org=env['INFLUXDB_ORG'], record=points)
rs2 = write_api.write(bucket=env['INFLUXDB_BUCKET'], org=env['INFLUXDB_ORG'],
record=Point('resources')
.field('cpu',int(hw_stats['cpu-load']))
)
if_stats_old = if_stats
print(json.dumps(if_stats, indent=2))
print(json.dumps(hw_stats, indent=2))
last = time.time()
LOGGER.debug(f"\nInterfaces: {json.dumps(if_stats, indent = 2)}")
LOGGER.debug(f"\nResources: {json.dumps(hw_stats, indent = 2)}")
time.sleep(INTERVAL)
except KeyboardInterrupt:
run = False
except Exception as e:
print(f"Unexpected exception: [{e}]")
return 1
### END MAIN LOOP ###
connection.disconnect()
return 0
if __name__ == "__main__":
sys.exit(main())
# Logger Constants
LOG_FORMAT = '%(asctime)s| %(levelname)-7s|%(funcName)-10s|%(lineno)-3d: %(message)-50s'
# Enabling Logger
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG)
LOGGER.propagate = False
formatter = logging.Formatter(LOG_FORMAT, None)
levels = logging.getLevelNamesMapping()
# File logging
log_name = os.path.abspath(env['LOG_FILE'])
fh = logging.FileHandler(log_name)
fh.setLevel(levels[env['LOG_FILE_LVL']])
fh.setFormatter(formatter)
LOGGER.addHandler(fh)
# Console logging
cl = logging.StreamHandler(sys.stdout)
cl.setLevel(levels[env['LOG_CLI_LVL']])
cl.setFormatter(formatter)
LOGGER.addHandler(cl)
LOGGER.warning(f"Routermon started on: {time.asctime()}")
while main():
LOGGER.error("Main thread exited unexpectedly")
time.sleep(15)
sys.exit(0)