Skip to content Skip to main navigation Skip to footer

Python: python 实现每天产生一个日志文件

与java apache log4j的ConsoleAppender,RollingFileAppender类似,python也有自己的实现,分别是logging.StreamHandler(),logging.handlers.TimedRotatingFileHandler.

下面是示例代码:

def script_path():
	path = os.path.realpath(sys.argv[0])
	if os.path.isfile(path):
	path = os.path.dirname(path)
	return os.path.abspath(path)
LOGGING_MSG_FORMAT  = '[%(asctime)s] [%(levelname)s] [%(module)s] [%(funcName)s] [%(lineno)d] %(message)s'
LOGGING_DATE_FORMAT	= '%Y-%m-%d %H:%M:%S'
logging.basicConfig(level=logging.DEBUG,format=LOGGING_MSG_FORMAT,datefmt=LOGGING_DATE_FORMAT)
log = logging.getLogger('xxx')
log_path = os.path.join(script_path(),'logs')
if not os.path.exists(log_path):
	os.makedirs(log_path)
log_file = os.path.join(log_path,'xxx.log')
logger = logging.handlers.TimedRotatingFileHandler(log_file,'midnight',1)
logger.setFormatter(logging.Formatter(LOGGING_MSG_FORMAT))
log.addHandler(logger)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(logging.Formatter(LOGGING_MSG_FORMAT))
log.addHandler(console)
 

注意事项:
不要在多线程程序中使用addHandler,removeHandler,否则可能产生一些意想不到的异常
。建议:
全局只初始化一次logger实例

原文:http://ucstudio.iteye.com/blog/2212447

0 Comments

There are no comments yet

Leave a comment

Your email address will not be published.