lm-sensors 설치 후 파이썬 스크립트로 cpu core 온도를 로그 파일에 남기기 했다.
sudo apt install lm-sensors
# -*- coding: utf-8 -*-
import os
import json
import socket
from datetime import datetime
if __name__ == '__main__':
log_path = '/home/logs/temperature/cpu_core.log'
sensors_res = os.popen('sensors -j').read()
data = json.loads(sensors_res)
if 'coretemp-isa-0000' in data:
result = {
'hostname': socket.gethostname(),
'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'type': 'cpu core temperature'
}
for key in data['coretemp-isa-0000']:
if 'Core' in key:
for key2 in data['coretemp-isa-0000'][key]:
if '_input' in key2:
result[key] = data['coretemp-isa-0000'][key][key2]
else:
continue
else:
continue
with open(log_path, 'a') as file:
file.write(f'\n{json.dumps(result)}')
crontab에 1분 단위로 남기게 등록
# cpu temperature log
* * * * * python3 /home/app/sensors_logger.py >> /dev/null 2>&1
위처럼 하면 소스 내용대로 /home/logs/temperature/cpu_core.log에 로그를 분 단위로 남기게 된다.
하지만 파일 로그 긁어다가 넣는 것보다 DB에 바로 넣는 게 편하니 그라파나로 대시보드를 구성하고 싶으므로 influxdb에 적재를 하자.
서버에 influxdb는 이미 설치 되어 있으니 파이썬과 연동을 해야 한다.
일단 pip3가 없어서 설치
sudo apt install python3-pip
pip가 없으면 설치해야 된다.
파이썬용 패키지 설치
sudo pip3 install influxdb
데이터베이스 생성
influx -precision rfc3339
CREATE DATABASE {데이터베이스명}
테이블 생성 필요 없이 그냥 냅다 넣으면 된다.
# -*- coding: utf-8 -*-
import os
import json
import socket
from datetime import datetime
from influxdb import InfluxDBClient
if __name__ == '__main__':
sensors_res = os.popen('sensors -j').read()
data = json.loads(sensors_res)
if 'coretemp-isa-0000' in data:
result = {
'hostname': socket.gethostname(),
'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'type': 'cpu core temperature'
}
for key in data['coretemp-isa-0000']:
if 'Core' in key:
for key2 in data['coretemp-isa-0000'][key]:
if '_input' in key2:
result[key] = data['coretemp-isa-0000'][key][key2]
else:
continue
else:
continue
points = [
{
'measurement': 'temperature',
'tags': {'server': result['hostname']},
'fields': result,
'time': result['time']
}
]
client = InfluxDBClient('localhost', 8086)
client.switch_database('DB명')
client.write_points(points=points, protocol='json')
잘 들어가짐.
> select * from temperature;
name: temperature
time Core 0 Core 1 Core 2 Core 3 hostname server type
---- ------ ------ ------ ------ -------- ------ ----
2022-08-12T00:04:46Z 42 35 39 40 호스트명 호스트명 cpu core temperature
반응형