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
  • 前言 在我們開發過程中基本上不可或缺的用到一些敏感機密數據,比如SQL伺服器的連接串或者是OAuth2的Secret等,這些敏感數據在代碼中是不太安全的,我們不應該在源代碼中存儲密碼和其他的敏感數據,一種推薦的方式是通過Asp.Net Core的機密管理器。 機密管理器 在 ASP.NET Core ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 順序棧的介面程式 目錄順序棧的介面程式頭文件創建順序棧入棧出棧利用棧將10進位轉16進位數驗證 頭文件 #include <stdio.h> #include <stdbool.h> #include <stdlib.h> 創建順序棧 // 指的是順序棧中的元素的數據類型,用戶可以根據需要進行修改 ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • C總結與剖析:關鍵字篇 -- <<C語言深度解剖>> 目錄C總結與剖析:關鍵字篇 -- <<C語言深度解剖>>程式的本質:二進位文件變數1.變數:記憶體上的某個位置開闢的空間2.變數的初始化3.為什麼要有變數4.局部變數與全局變數5.變數的大小由類型決定6.任何一個變數,記憶體賦值都是從低地址開始往高地 ...
  • 如果讓你來做一個有狀態流式應用的故障恢復,你會如何來做呢? 單機和多機會遇到什麼不同的問題? Flink Checkpoint 是做什麼用的?原理是什麼? ...
  • C++ 多級繼承 多級繼承是一種面向對象編程(OOP)特性,允許一個類從多個基類繼承屬性和方法。它使代碼更易於組織和維護,並促進代碼重用。 多級繼承的語法 在 C++ 中,使用 : 符號來指定繼承關係。多級繼承的語法如下: class DerivedClass : public BaseClass1 ...
  • 前言 什麼是SpringCloud? Spring Cloud 是一系列框架的有序集合,它利用 Spring Boot 的開發便利性簡化了分散式系統的開發,比如服務註冊、服務發現、網關、路由、鏈路追蹤等。Spring Cloud 並不是重覆造輪子,而是將市面上開發得比較好的模塊集成進去,進行封裝,從 ...
  • class_template 類模板和函數模板的定義和使用類似,我們已經進行了介紹。有時,有兩個或多個類,其功能是相同的,僅僅是數據類型不同。類模板用於實現類所需數據的類型參數化 template<class NameType, class AgeType> class Person { publi ...
  • 目錄system v IPC簡介共用記憶體需要用到的函數介面shmget函數--獲取對象IDshmat函數--獲得映射空間shmctl函數--釋放資源共用記憶體實現思路註意 system v IPC簡介 消息隊列、共用記憶體和信號量統稱為system v IPC(進程間通信機制),V是羅馬數字5,是UNI ...