為了調試方便,特意將python的logging模組封裝了一下,支援同時向console和file輸出,支援記錄檔復原。
(1)myloggingconfig.py
View Code
# -*- coding: utf-8 -*-
'''
Created on 2011-8-24
主要用途:
對程式中所使用的loggong模式做一般性配置
@author: JerryKwan
'''
import logging
import logging.handlers
import os
LEVELS = {'NOSET': logging.NOTSET,
'DEBUG': logging.DEBUG,
'INFO': logging.INFO,
'WARNING': logging.WARNING,
'ERROR': logging.ERROR,
'CRITICAL': logging.CRITICAL}
#set up logging to file
#logging.basicConfig(level = logging.NOTSET,
# format = "%(asctime)s %(name)-12s %(levelname)-8s %(message)s"
# )
## filename = "./log.txt",
## filemode = "w")
# create logs file folder
logs_dir = os.path.join(os.path.curdir, "logs")
if os.path.exists(logs_dir) and os.path.isdir(logs_dir):
pass
else:
os.mkdir(logs_dir)
# define a rotating file handler
rotatingFileHandler = logging.handlers.RotatingFileHandler(filename ="./logs/log.txt",
maxBytes = 1024 * 1024 * 50,
backupCount = 5)
formatter = logging.Formatter("%(asctime)s %(name)-12s %(levelname)-8s %(message)s")
rotatingFileHandler.setFormatter(formatter)
logging.getLogger("").addHandler(rotatingFileHandler)
#define a handler whitch writes messages to sys
console = logging.StreamHandler()
console.setLevel(logging.NOTSET)
#set a format which is simple for console use
formatter = logging.Formatter("%(name)-12s: %(levelname)-8s %(message)s")
#tell the handler to use this format
console.setFormatter(formatter)
#add the handler to the root logger
logging.getLogger("").addHandler(console)
# set initial log level
logger = logging.getLogger("")
logger.setLevel(logging.NOTSET)
(2)具體使用方法
import logging
logger = logging.getLogger(__name__)
if __name__ == "__main__":
import myloggingconfig
msg = “this is just a test”
logger.info(msg)
如果想動態更改logging的level,可以通過logging.getLogger("").setLevel(level)變更。