日志
在任何一個完整的程序中若锁,日志都是必不可少的一部分。日志的作用無需細說斧吐,下面是一個封裝了發(fā)送日志到本地和syslog服務(wù)器的接口又固。
# -*- coding:utf-8 -*-
"""
File Name : 'log'.py
Description:
Author: 'chengwei'
Date: '2016/5/24' '16:24'
python: 2.7.10
"""
import logging
from logging.handlers import SysLogHandler
import time
import ConfigParser
import os
import codecs
def example():
# 發(fā)送到遠程syslogserver
logger1 = to_syslog('local2', logging.INFO)
for i in range(0, 20):
time.sleep(0.5)
msg = "abc %s" % i
logger1.error(msg)
# 存儲日志到本地指定位置
logger2 = local_log("test.log")
for i in range(0, 20):
time.sleep(1.1)
msg = "abc %s" % i
logger2.error(msg)
def local_log(logname, level=logging.INFO):
"""
:param logname:表示存儲路徑和文件名
:param level:表示日志輸出級別logging.DEBUG,logging.INFO等等仲器,默認為logging.INFO
:return:logger
"""
format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(filename)s[line:%(lineno)d] - %(message)s')
handler = logging.FileHandler(logname)
handler.setFormatter(format)
logger = logging.getLogger()
logger.addHandler(handler)
logger.setLevel(level)
return logger
def to_syslog(user, level=logging.INFO):
"""
發(fā)送日志到syslog服務(wù)器
:param user:表示自定義local0-7
:param level:表示日志輸出級別logging.DEBUG,logging.INFO等等,默認為logging.INFO
:return:logger
"""
sysloghost = init()
format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(filename)s[line:%(lineno)d] - %(message)s')
handler = SysLogHandler(address=(sysloghost, 514), facility=user)
handler.setFormatter(format)
logger = logging.getLogger()
logger.addHandler(handler)
logger.setLevel(level)
return logger
def init(parasecname="LOG"):
"""
從配置文件獲取參數(shù)
:param parasecname: 配置文件中節(jié)點名稱
:return:配置信息
"""
cur_script_dir = os.path.split(os.path.realpath(__file__))[0]
cfg_path = os.path.join(cur_script_dir, "db.conf")
cfg_reder = ConfigParser.ConfigParser()
secname = parasecname
cfg_reder.readfp(codecs.open(cfg_path, "r", "utf_8"))
sysloghost = cfg_reder.get(secname, "server")
return sysloghost
if __name__ == '__main__':
example()