我試圖在Python腳本中使用logging
和warnings
模塊。我想使用warnings.warn()
來記錄警告,但仍然使用我爲記錄器設置的格式。python - 同時使用日誌和警告模塊拋出'TypeError:預期的字符緩衝區對象'
我打電話給logging.captureWarnings(True)
,用我自己的功能代替warnings.formatwarning()
。我的代碼如下所示:
def _my_format_warning(message, category, filename, lineno, line=None):
logging.warning(message)
# ... rest of code
# setup in main function:
logging.basicConfig(format='[%(asctime)s] %(levelname)s: %(message)s', level=logging.WARNING)
logging.captureWarnings(True)
warnings.formatwarning=_my_format_warning
測試各種選項:
如果我不和我自己的函數重載
warnings.formatwarning()
,我得到了內置的預警格式,其中包含新行和我不想字段(大膽下面標):[2015-01-07 21:40:43,436] WARNING: robots.py:435: UserWarning: Robot schematic contains less than 1 laser attachment.
"laser attachment.".format(self.MIN_RECOMMENDED_LASERS)如果我重寫
warnings.formatwarning()
但不叫logging.captureWarnings(True)
,我的腳本崩潰的一個例外:[2015-01-07 21:40:43,436] WARNING: Robot schematic contains less than 1 laser attachment.
Traceback (most recent call last):
File "robots.py", line 435, in activate()
"laser attachment.".format(self.MIN_RECOMMENDED_LASERS)
File "warnings.py", line 29, in _show_warning
file.write(formatwarning(message, category, filename, lineno, line))
TypeError: expected a character buffer object
有什麼不對?