1. 程式人生 > >python遠端傳送syslog到某個機器上514埠,並注意addHandler()在迴圈執行時,呼叫只能一次

python遠端傳送syslog到某個機器上514埠,並注意addHandler()在迴圈執行時,呼叫只能一次

原始碼

#/usr/bin/python

#encoding:utf-8
import logging
import logging.handlers  # handlers要單獨import
import GetConfig
getcon=GetConfig.GetConfig()
IP=getcon[0]
Port=int(getcon[1])
logger = logging.getLogger('WebTamper')
fh = logging.handlers.SysLogHandler((IP, Port), logging.handlers.SysLogHandler.LOG_AUTH)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
def sendresyslog(mes):

    logger.warning(mes)

測試執行

import sendresyslog
# check_change.check()
i=0
for i in range(0,3):

    sendresyslog.sendresyslog('111111')

列印

<36>2018-03-01 10:27:59,617 - WebTamper - WARNING - 111111
<36>2018-03-01 10:28:01,619 - WebTamper - WARNING - 111111

<36>2018-03-01 10:28:03,619 - WebTamper - WARNING - 111111

注意:

logger.addHandler(fh) 只能在迴圈中呼叫一次,否則,會出現疊加式的列印

每次呼叫debug都會設定新增一個log handler,每個handler都會列印一次log,所有就會出現呼叫幾次debug,就會列印幾條相同的log。

<36>2018-03-01 10:27:59,617 - WebTamper - WARNING - 111111

<36>2018-03-01 10:28:01,619 - WebTamper - WARNING - 111111

<36>2018-03-01 10:28:03,619 - WebTamper - WARNING - 111111

<36>2018-03-01 10:28:01,619 - WebTamper - WARNING - 111111

<36>2018-03-01 10:28:03,619 - WebTamper - WARNING - 111111

<36>2018-03-01 10:28:01,619 - WebTamper - WARNING - 111111