s
代码主要是转别人的
http://www.cnblogs.com/Jerryshome/archive/2012/02/01/2334444.html
http://www.cnblogs.com/Jerryshome/archive/2012/11/27/2791416.html
我是在他的第一版的基础上改的,然后有一些分析,最新版的还木有看,谢谢原作者的无私供献!
原版第一版是将log同时输出到stderr和./logs/log.txt
1. stderr---stdout
因为我是用wxPython写一个小工具,然后用py2exe转成exe的文件供公司里的人使用。这样输出到stderr有一个问题,每次关闭程序,总要提示"errors occurred",我现在认为只要stderr里有内容,wxPython就会有这个提示,所以我修改了下代码提定到stdout,就不再提示了,感觉整个世界都清静好多!
stderr和stdout到底是什么,有些了解,但不是很清楚。
2. 分析basicConfig
#set up logging to stderr默认值
logging.basicConfig(level = logging.NOTSET,
format = "%(asctime)s %(levelname)-8s %(message)s",
datefmt='%H:%M:%S')
stream Use the specified stream to initialize the StreamHandler. Note
that this argument is incompatible with 'filename' - if both
are present, 'stream' is ignored.
3.我用到的代码
# coding=utf-8
'''
Created on 2011-8-24
主要用途:
对程序中所使用的loggong模式做一般性配置
@author: JerryKwan
'''
import logging
import logging.handlers
import os, sys
LEVELS = {'NOSET': logging.NOTSET,
'DEBUG': logging.DEBUG,
'INFO': logging.INFO,
'WARNING': logging.WARNING,
'ERROR': logging.ERROR,
'CRITICAL': logging.CRITICAL}
# 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", "%H:%M:%S")
formatter = logging.Formatter("%(asctime)s %(levelname)-8s %(message)s", "%H:%M:%S")
rotatingFileHandler.setFormatter(formatter)
logging.getLogger("").addHandler(rotatingFileHandler)
#define a handler whitch writes messages to sys
console = logging.StreamHandler(sys.stdout)
console.setLevel(logging.NOTSET)
#set a format which is simple for console use
#formatter = logging.Formatter("%(name)-12s: %(levelname)-8s %(message)s")
formatter = logging.Formatter("%(asctime)s %(levelname)-8s %(message)s", "%H:%M:%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)
4.时间格式
formatter = logging.Formatter("%(asctime)s %(levelname)-8s %(message)s", "%H:%M:%S")
5.输出到stdout,如果不指定,默认是stderr
#define a handler whitch writes messages to sys
console = logging.StreamHandler(sys.stdout)