很多程序都有記錄日志的需求,并且日志中包含的信息即有正常的程序訪問日志,還可能有錯誤、警告等信息輸出,python的logging模塊提供了標準的日志接口,你可以通過它存儲各種格式的日志,logging的日志可以分為 debug(), info(), warning(), error() and critical()5個級別,但是內置的logging使用不夠靈活,我們通過繼承類重新封裝logging,實現自定義logging模塊。
# coding:utf-8
import logging,time,logging.handlers,os
class Log(object):
def __init__(self, logger=None):
# 創建一個logger
self.logger = logging.getLogger(logger)
self.logger.setLevel(logging.DEBUG)
# 創建一個handler,用于寫入日志文件
self.logTime = time.strftime("%Y-%m-%d")
self.logPath = os.path.abspath(os.path.join(os.path.dirname(__file__), './logs'))
# 如果不存在這個logs文件夾,就自動創建一個
if not os.path.exists(self.logPath):
os.mkdir(self.logPath)
# 日志文件的地址
self.logName = self.logPath + '/' + self.logTime + '.amd5.cn.log'
# fh = logging.FileHandler(self.log_name, 'a') # python2
# fh = logging.FileHandler(self.log_name, 'a', encoding='utf-8') # python3
fh = logging.handlers.RotatingFileHandler(
filename=self.logName,
maxBytes=1024 * 1024 * 50,
backupCount=5
)
fh.setLevel(logging.INFO)
# 再創建一個handler,用于輸出到控制臺
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# 定義handler的輸出格式
formatter = logging.Formatter(
'[%(asctime)s] [%(filename)s]->%(funcName)s line:%(lineno)d [%(levelname)s]:%(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# 給logger添加handler
self.logger.addHandler(fh)
self.logger.addHandler(ch)
# 關閉打開的文件
fh.close()
ch.close()
def MyLog(self):
return self.logger
if __name__ == '__main__':
log = Log().MyLog()
def test1():
log.info('阿湯博客')
def test2():
log.error('阿湯博客地址是:http://m.maowutv.com/')
def test3():
log.warning('阿湯博客地址是:http://m.maowutv.com/,歡迎訪問!')
test1()
test2()
test3()
其他頁面調用:
from test import Log
log = Log().MyLog()
def test1():
log.info('阿湯博客')
def test2():
log.error('阿湯博客地址是:http://m.maowutv.com/')
def test3():
log.warning('阿湯博客地址是:http://m.maowutv.com/,歡迎訪問!')
test1()
test2()
test3()
日志輸出效果:
[2021-01-26 17:45:29,943] [test.py]->test1 line:56 [INFO]:阿湯博客 [2021-01-26 17:45:29,943] [test.py]->test2 line:58 [ERROR]:阿湯博客地址是:http://m.maowutv.com/ [2021-01-26 17:45:29,944] [test.py]->test3 line:60 [WARNING]:阿湯博客地址是:http://m.maowutv.com/,歡迎訪問! [2021-01-26 17:45:52,539] [config.py]->test1 line:282 [INFO]:阿湯博客 [2021-01-26 17:45:52,539] [config.py]->test2 line:284 [ERROR]:阿湯博客地址是:http://m.maowutv.com/ [2021-01-26 17:45:52,539] [config.py]->test3 line:286 [WARNING]:阿湯博客地址是:http://m.maowutv.com/,歡迎訪問!
贊
0
賞


