1. 代码如下:
#!/usr/bin/env python
#encoding: utf8
import sys, os
reload(sys)
sys.setdefaultencoding('utf-8')
import logging
import logging.handlers
scriptDir = os.path.dirname(os.path.abspath(__file__))
def initLogger(logfile, level, console=False):
logger = logging.getLogger(__name__);
logger.setLevel(level)
formatter = logging.Formatter("[%(asctime)-15s] %(levelname)s %(name)s : %(message)s")
if console:
ch = logging.StreamHandler()
ch.setFormatter(formatter)
logger.addHandler(ch)
try:
logDir = os.path.dirname(logfile)
if not os.path.isdir(logDir):
os.makedirs(logDir)
handler = logging.handlers.TimedRotatingFileHandler(logfile, when="D", backupCount=30)
handler.setFormatter(formatter)
logger.addHandler(handler)
except Exception, e:
logger.warn("log file init failed: %s", e)
return logger
if __name__ == "__main__":
logfile = os.path.join(scriptDir, "../log/xxxx.log")
logger = initLogger(logfile, logging.INFO, console=True)
logger.debug("debug test!")
logger.info("info test!");
logger.warning("warning test!");
logger.error("error test!");
logger.critical("critical test!");
运行输出,并且还会在当前目录的上一级目录的 log 目录下面产生一个 xxxx.log 的文件
[2017-08-31 03:12:40,216] INFO __main__ : info test!
[2017-08-31 03:12:40,216] WARNING __main__ : warning test!
[2017-08-31 03:12:40,216] ERROR __main__ : error test!
[2017-08-31 03:12:40,216] CRITICAL __main__ : critical test!