test.cfg文件:
[sysparm]
# CRITICAL 50; ERROR 40; WARNING 30; INFO 20; DEBUG 10, NOSET 0;
log_level:10
#!/usr/bin/env python
#coding=utf-8
import logging
import sys
from logging.handlers import RotatingFileHandler
from base_course.modules.configparseexample import get_cfg
def log_basic():
# CRITICAL 50; ERROR 40; WARNING 30; INFO 20; DEBUG 10, NOSET 0;
# 将日志写入文件
logging.basicConfig(filename="web.log",
level=logging.INFO,
format='%(asctime)s %(name)s %(levelname)s %(module)s:%(lineno)d %(message)s')
logging.getLogger("info").setLevel(logging.INFO)
logging.info("this is info log")
logging.getLogger("warning").setLevel(logging.WARNING)
logging.info("this is warning log")
logging.getLogger("debug").setLevel(logging.DEBUG)
logging.debug("this is debug log")
# 从配置文件中获取参数值
logging.basicConfig(stream=sys.stdout,
level=int(get_cfg("test.cfg").get('sysparm','log_level')),
format='%(asctime)s %(name)s %(levelname)s %(module)s:%(lineno)d %(message)s')
logging.getLogger("info").setLevel(logging.INFO)
logging.info("this is info log")
logging.getLogger("warning").setLevel(logging.WARNING)
logging.info("this is warning log")
logging.getLogger("debug").setLevel(logging.DEBUG)
logging.debug("this is debug log")
def log_rotate():
#日志备份
format='%(asctime)s %(name)s %(levelname)s %(module)s:%(lineno)d %(message)s'
logging.basicConfig(level=10,format='%(asctime)s %(name)s %(levelname)s %(module)s:%(lineno)d %(message)s')
#定义RotatingFileHandler,日志文件大小超过10M时进行旋转,最大5个备份日志文件。
rotateHandler = RotatingFileHandler('you.log', maxBytes=1024*0.01, backupCount=5)
rotateHandler.setLevel(logging.DEBUG)
rotateHandler.setFormatter(logging.Formatter(format))
logging.getLogger("").addHandler(rotateHandler)
logging.getLogger().propagate = False
logging.info("my log "*500)
if __name__=="__main__":
log_basic()
# log_rotate()
网友评论