python如何監控PostgreSQL代碼運行

来源:https://www.cnblogs.com/lottu/archive/2020/07/08/13266104.html
-Advertisement-
Play Games

如何監控PostgreSQL存儲過程/函數代碼運行?本文介紹用python+微信/郵件的方式進行報警、監控。 首先要有一張表、用於存放PostgreSQL存儲過程/函數代碼運行異常的信息。 處理原則:若出現異常;把“發生時間+所在的程式+**原因”**通過微信/郵件發給對應人員。當然發送一次即可;起 ...


如何監控PostgreSQL存儲過程/函數代碼運行?本文介紹用python+微信/郵件的方式進行報警、監控。

首先要有一張表、用於存放PostgreSQL存儲過程/函數代碼運行異常的信息。

處理原則:若出現異常;把“發生時間+所在的程式+原因”通過微信/郵件發給對應人員。當然發送一次即可;起到通知的效果。

一、媒介

通過什麼方式進行發送內容;下麵介紹微信/郵件兩種方式

1、python發送微信

py_wechar.py的內容

企業微信號;大家可以到企業微信上配置

#!/usr/bin/python3
#coding=utf-8
import json
import time
import urllib.request as urllib2
options = {
    'WeiXin': {
            'corp_id': '*',  #微信企業號ID
            'agent_id': '*', #微信企業號應用ID
            'agent_secret': '*',  #微信企業號密鑰
            'to_user': '@all'  #發送給誰
    },
}
class WeiXinSendMsg:
    def __init__(self, wx_conf):
        self.corp_id = wx_conf.get('corp_id')
        self.agent_secret = wx_conf.get('agent_secret')
        self.agent_id = wx_conf.get('agent_id')
        self.to_user = wx_conf.get('to_user')
        self.token = self.get_token() 
        self.token_update_time = int(time.time())
        
    def get_token(self):
        get_token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + self.corp_id + '&corpsecret=' + self.agent_secret
        token = json.loads(urllib2.urlopen(get_token_url).read().decode('utf-8'))['access_token']
        if token:
            return token
    # 微信發送端的token每1800秒會更新一次
    def update_token(self):
        if int(time.time()) - self.token_update_time >= 1800:
            self.token = self.get_token()
            self.token_update_time = int(time.time())
    def send_message(self, msg):
        try:
            self.update_token()
            send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.token
            send_val = {"touser":self.to_user, "toparty":"", "msgtype":"text", "agentid":self.agent_id, "text":{"content":msg}, "safe":"0"}
            send_data = json.dumps(send_val, ensure_ascii=True).encode("utf-8")
            send_request = urllib2.Request(send_url, send_data)
            response = json.loads(urllib2.urlopen(send_request).read())
        except Exception as e:
            print('Exception WeiXin send_message:', e)
if __name__ == '__main__':
    WeiXin = WeiXinSendMsg(options.get('WeiXin'))
    WeiXin.send_message('hello world / 測試')

2、python發送郵件

py_email.py的內容

#!/usr/bin/python3
#coding=utf-8
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr

options = {
    'Email': {
        'smtp_server': 'smtp.exmail.qq.com',  #郵箱伺服器地址
        'from_addr': '[email protected]',  #發送人賬號
        'password': '123456', #發送人密碼
        'to_addr': ['[email protected]', '[email protected]'], #發送給誰
    }
}
class EmailSendMsg:
    def __init__(self, email_conf):
        self.smtp_server = email_conf.get('smtp_server')
        self.from_addr = email_conf.get('from_addr')
        self.password = email_conf.get('password')
        self.to_addr = email_conf.get('to_addr')
    # def __del__(self):
    #     self.server.quit()
    def format_addr(self, str):
        name, addr = parseaddr(str)
        return formataddr(( \
            Header(name, 'utf-8').encode(), \
            addr.encode('utf-8') if isinstance(addr, unicode) else addr))
    
    def send_msg(self, text):
        try:
            self.server = smtplib.SMTP(self.smtp_server, 25)
            self.server.set_debuglevel(1)
            self.server.login(self.from_addr, self.password)

            msg = MIMEText(text, 'plain', 'utf-8')
            msg['From'] = self.format_addr(u'監控 <%s>' % self.from_addr)
            for i in range(len(self.to_addr)):
                msg['To'] = self.format_addr(u'<%s>' % self.to_addr[i])
            msg['Subject'] = Header(u'異常報警…', 'utf-8').encode()
            self.server.sendmail(self.from_addr, self.to_addr, msg.as_string())
            self.server.quit()
        except Exception as e:
            print 'Exception Email send_message:', e
if __name__ == '__main__':
	Email = EmailSendMsg(options.get('Email'))
	Email.send_msg('hello world!')

二、python連接資料庫

PostgreSQL Python

看這個鏈接可以研究下python如何連接PostgreSQL資料庫

三、python報警

上面我們知道如何通過python發送微信內容、以及python連接PostgreSQL資料庫。現在我們要如何獲取報警時機;報警內容。

python_alert.py

#!/usr/bin/python3
 
import psycopg2
from config import config
from py_wechar import WeiXinSendMsg,options

def get_errors():
    """ query data from the vendors table """
    conn = None
    try:
        params = config()
        WeiXin = WeiXinSendMsg(options.get('WeiXin'))
        conn = psycopg2.connect(**params)
        cur = conn.cursor()
        cur.execute("select error_time, error_desc, proc_name from adsas.tbl_error_log where deal_status = 0 order by id")
        rows = cur.fetchall()
        if cur.rowcount > 0 :
            WeiXin.send_message("The number of parts: {}".format(cur.rowcount))
            for row in rows:
           # WeiXin.send_message('-'*60)
           # WeiXin.send_message('發生時間:{}'.format(row[0]))
           # WeiXin.send_message('錯誤原因:{}'.format(row[1]))
           # WeiXin.send_message('報警代碼:{}'.format(row[2]))
                str_error='發生時間:{}\n錯誤原因:{}\n報警代碼:{}'.format(row[0],row[1],row[2])
                WeiXin.send_message(str_error)
            cur.execute("update adsas.tbl_error_log set deal_status = 1 where deal_status = 0 ")			
        conn.commit()
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()
			
if __name__ == '__main__':
    get_errors()

四、部署

可以通過cron/或者開源的定時任務系統進行報警;

報警信息:


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一 Nginx配置文件 1.1 Nginx主配置 Nginx主配置文件/etc/nginx/nginx.conf是一個純文本類型的文件,整個配置文件是以區塊的形式組織,通常每一個區塊以一對大括弧{}來表示開始與結束。 提示:若編譯安裝則為編譯時所指定目錄。 Main位於nginx.conf配置文件的 ...
  • 目錄 免費便捷方案--Mounty 藉助ntfs-3g開源軟體 一、使用Mounty 1.安裝(https://mounty.app/) brew cask install mounty 2.風險 My USB stick will not re-mount. An alert is popping ...
  • MySQL是目前主流的資料庫之一,且免費使用,所以適合中小企業或者是開發者使用,本文簡單介紹一下在不同的Linux發行版本下的安裝方法。 ...
  • 1. 現象 今天協助其他同學排查問題的時候,發現資料庫錯誤日誌文件已經有9G以上了,打開內容查看如下: 2020-07-08 13:47:43 0x7fe3723ff700 INNODB MONITOR OUTPUT Per second averages calculated from the l ...
  • 墨天輪資料庫周刊第31期發佈啦,每周1次推送本周資料庫相關熱門資訊、精選文章、乾貨文檔。 ...
  • SQL自學筆記 SQL的自我介紹 SQL分類的畫圖演示 DDL 操作資料庫 1.0 查詢和創建 2.0 修改、刪除、使用 操作表 1.0 查詢 e 2.創建 3.刪除 4.修改 DML 1.0 添加數據 2.0 刪除 3.0 修改 DQL 1.0 基礎查詢 2.0 條件查詢 3.模糊查詢 4.排序查 ...
  • MySQL 對window函數執行sum函數疑似Bug 使用MySql的視窗函數統計數據時,發現一個小的問題,與大家一起探討下。 環境配置: mysql-installer-community-8.0.20.0 問題點:在sum對window函數執行時,如果有重覆數據,會直接把相同的數據相加,並不是 ...
  • 大概在去年的時候,做項目中遇到這麼一個需求,如圖所示,根據Type欄位篩選查找對應數據行,並找到該行欄位為Levels中值最小的數據,例如當Type=1的時候,取出來的是0,當Type=2的時候,取出來的是2,當Type=3的時候,取出來的是1,當我第一次看到數據存儲方式的時候,我是有點吃驚的,因為 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...