提交 56c887d6 作者: martin

增加日志记录文件1.txt

增加数据库连接失败时的处理逻辑
上级 10d471e2
......@@ -13,8 +13,20 @@ import time
from time import sleep
from prometheus_client import start_http_server, Gauge
import argparse
import pymysql
from pymysql import connect
import requests
import logging
import os
current_file_path = os.path.abspath(__file__)
current_dir_path = os.path.dirname(current_file_path)
logging.basicConfig(
filename=f'{current_dir_path}/1.log',
# encoding='utf-8',
format='%(asctime)s - %(name)s - %(levelname)s - %(module)s:%(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.INFO
)
def service_status():
......@@ -29,7 +41,7 @@ def service_status():
# 连接到数据库
try:
connection = pymysql.connect(**config)
connection = connect(**config)
if connection.open:
# 创建一个游标对象
cursor = connection.cursor()
......@@ -51,7 +63,8 @@ def service_status():
for record in records:
try:
status = requests.get(record[2]).status_code
except Exception:
except Exception as e:
logging.error(f"访问{record[2]}失败,错误为:{e}")
# 当网页无法访问时,将状态码设置为777
status = 777
result.append({
......@@ -63,17 +76,14 @@ def service_status():
'owner_email': record[4],
'chk_time': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
})
# 关闭游标和连接
cursor.close()
connection.close()
return result
except Exception as e:
print(f"数据库连接错误: {e}")
finally:
# 关闭游标和连接
if connection.open:
cursor.close()
connection.close()
logging.error(f"数据库连接错误: {e}")
return False
if __name__ == '__main__':
......@@ -84,7 +94,7 @@ if __name__ == '__main__':
# 解析命令行参数
parser = argparse.ArgumentParser(description='这是一个服务状态检查程序,说明如下:')
parser.add_argument('--port', '-p', default='8761', help='监听端口,8761')
parser.add_argument('--port', '-p', default='18000', help='监听端口,8761')
parser.add_argument('--db_ip', default='114.116.11.225', help='指定mysql的ip,默认为114.116.11.225')
parser.add_argument('--db_port', default='3306', help='指定mysql端口,默认为3306')
parser.add_argument('--db_user', default='monitor', help='指定mysql的用户名,monitor')
......@@ -102,11 +112,13 @@ if __name__ == '__main__':
while True:
# 更新指标的值
res = service_status()
metric.clear()
for info in res:
metric.labels(project=info['project'], service_name=info['service_name'],
url=info['url'], owner_name=info['owner_name'],
owner_email=info['owner_email'], chk_time=info['chk_time']).set(info['status'])
if res:
metric.clear()
for info in res:
metric.labels(project=info['project'], service_name=info['service_name'],
url=info['url'], owner_name=info['owner_name'],
owner_email=info['owner_email'], chk_time=info['chk_time']).set(info['status'])
else:
logging.error("数据获取失败")
# 每隔30秒更新一次指标的值
sleep(30)
sleep(60)
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论