#3 Requests 的日志配置
requests logging 2019-08-09import http.client
import logging
import requests
LOG_LEVEL = logging.DEBUG
LOG_FORMAT = '%(asctime)s [%(thread)s] [%(name)s:%(funcName)s#%(lineno)d] %(levelname)s %(message)s'
logging.basicConfig(level=LOG_LEVEL, format=LOG_FORMAT)
LOG_HTTP = logging.getLogger("http.client")
def httpclient_log(*args):
LOG_HTTP.log(logging.DEBUG, " ".join(args))
http.client.print = httpclient_log
http.client.HTTPConnection.debuglevel = 1
#2 logging 时间格式
Python logging 2017-03-12import logging
LOG_LEVEL = logging.DEBUG
LOG_FORMAT = '%(asctime)s %(levelname)s %(message)s'
logging.basicConfig(level=LOG_LEVEL, format=LOG_FORMAT)
logging.info('hello world')
默认时间格式是 yyyy-mm-dd hh:mm:ss,xxx
,如果我们要改这个格式可以用 datefmt
参数,遵循 time.strftime
的格式化参数格式。
问题有一个,毫秒从哪里来?
方法一:使用 msecs 占位符
最简单的办法:在格式字符串中使用 msecs 占位符,比如:
import logging
LOG_LEVEL = logging.DEBUG
LOG_FORMAT = '%(asctime)s.%(msecs)03d %(levelname)s %(message)s'
LOG_DATEFMT = '%H:%M:%S'
logging.basicConfig(level=LOG_LEVEL, format=LOG_FORMAT, datefmt=LOG_DATEFMT)
logging.info('hello world')
方法二:改用 datetime 对象
import logging
from datetime import datetime
class MyFormatter(logging.Formatter):
converter = datetime.fromtimestamp
def formatTime(self, record, datefmt=None):
ct = self.converter(record.created)
if datefmt:
# s = time.strftime(datefmt, ct)
s = ct.strftime(datefmt)
else:
# t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
t = ct.strftime("%Y-%m-%d %H:%M:%S")
s = "%s,%03d" % (t, record.msecs)
return s
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
logger.addHandler(console)
formatter = MyFormatter(fmt='%(asctime)s %(levelname)s %(message)s', datefmt='%H:%M:%S.%f')
console.setFormatter(formatter)
logging.info('hello world')
#1 logging 不输出中文日志的问题
Python logging 日志 2014-07-16一个小问题。