[英]Python logging extra info
如果我有以下python代碼:
import logging
logging.basicConfig(filename='allow.txt', level=logging.DEBUG, format='%(asctime)s')
logging.debug(2+3)
但是當我運行它時,我得到的結果是3 + 2中甚至沒有5:
2018-10-20 10:06:45,177
如何使結果更像這樣:
2018-10-20 10:06:45 : 5
甚至更好:
Date: 2018-10-20, Time: 10:06:45 Answer: 5
您需要在格式字符串中包含%(message)s
,以便記錄日志消息:
logging.basicConfig(..., format='%(asctime)s : %(message)s')
您可以通過配置datefmt
參數在時間戳中包含字符串“ Date”和“ Time”:
logging.basicConfig(
... ,
datefmt='Date: %Y-%m-%d, Time: %H:%M:%S',
format='%(asctime)s Answer: %(message)s',
)
您忘記了%(消息)s
您可以使用datefmt可選參數
import logging logging.basicConfig(filename='allow.txt', level=logging.DEBUG, format='%(asctime)s: %(message)s', datefmt="Date: %Y-%m-%d Time: %H:%M:%S")
發生這種情況的原因在format
參數內。 您的日志消息格式化程序僅以asc格式打印時間。 您應該添加message
參數。
import logging
logging.basicConfig(filename='allow.txt', level=logging.DEBUG, format='%(asctime)s : %(message)s')
logging.debug(2+3)
結果將是: 2018-10-20 20:27:44,082 : 5
要使用“最佳情況”,您應該添加日期格式。
logging.basicConfig(filename='allow.txt', level=logging.DEBUG, format='%(asctime)s Answer: %(message)s', datefmt="Date: %Y-%m-%d, Time: %H:%M:%S")
結果為: Date: 2018-10-20, Time: 20:29:29 Answer: 5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.