当前位置:   article > 正文

【实用工具】使用飞书机器人监控工程日志

【实用工具】使用飞书机器人监控工程日志

1.创建一个飞书群聊,设置-->群机器人-->添加机器人-->自定义机器人-->修改机器人名称-->添加

 2.复制webhook地址

3.编写日志请求代码

  1. import logging
  2. import requests
  3. import json
  4. import os
  5. from datetime import datetime
  6. import time
  7. import subprocess
  8. # curl -X POST -H "Content-Type: application/json" \
  9. # -d '{"msg_type":"text","content":{"text":"request example"}}' \
  10. # webhook地址
  11. def get_local_ip():
  12. try:
  13. # 执行系统命令获取本地 IP 地址
  14. result = subprocess.check_output(['ip', 'addr']).decode('utf-8')
  15. # 解析输出,找到本地 IP 地址
  16. lines = result.split('\n')
  17. for line in lines:
  18. if 'inet ' in line and '127.0.0.1' not in line:
  19. local_ip = line.strip().split(' ')[1]
  20. return local_ip.split('/')[0] # 返回不带掩码的 IP 地址
  21. return None
  22. except Exception as e:
  23. print("无法获取本地IP地址:", e)
  24. class send_mes:
  25. def __init__(self):
  26. self.data = {
  27. "msg_type": "text",
  28. "content": {
  29. # "text": "pid:%s,ip_addr:%s" % (current_process_id, ip_addr[0])
  30. "text": ""
  31. }
  32. }
  33. self.url = "webhook地址"
  34. self.headers = {
  35. "Content-Type": "application/json"
  36. }
  37. self.pid = os.getpid()
  38. self.ip_addr = get_local_ip()
  39. # sef send_message()
  40. def send_message(self, data):
  41. current_time = datetime.now()
  42. # 将当前时间转换为字符串格式
  43. current_time_str = current_time.strftime("%Y-%m-%d %H:%M:%S")
  44. data_li = [current_time_str, self.ip_addr, self.pid, data]
  45. data_li_str = [str(item) for item in data_li]
  46. self.log_ = "|".join(data_li_str)
  47. self.data["content"]["text"] = self.log_
  48. try:
  49. response = requests.post(self.url, json=self.data, headers=self.headers)
  50. if response.status_code == 200:
  51. print("消息发送成功:", response.json())
  52. else:
  53. print("消息发送失败:", response.text)
  54. except Exception as e:
  55. print("发送请求时出错:", e)
  56. if __name__ == "__main__":
  57. #实例化发送信息类
  58. send_mes_ = send_mes()
  59. #发送消息
  60. send_mes_.send_message("这是一条日志消息")

4.测试

日志信息将包括日期、执行程序的进程和ip,最后加上日志信息

  • 将error,info,debug放在三个机器人上,平时可以查看,等到真正使用时,把info和debug界别日志去掉,避免发送日志影响性能。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/420254
推荐阅读
相关标签
  

闽ICP备14008679号