[英]How to make a combined set of fields unique in Mongodb in Python
[英]How to set width of combined fields in Python logging
在 Python 日志記錄中,有沒有辦法設置兩個組合字段的寬度?
我希望結合文件名和行號以產生類似於以下內容的輸出:
2011-10-14 13:47:51 main.py:12 DEBUG - Initializing cluster
2011-10-14 13:47:51 cluster.py:364 DEBUG - Starting cluster
2011-10-14 13:47:51 cluster.py:98 INFO - Starting simulation
2011-10-14 13:47:51 simulation.py:79 DEBUG - Computing parameters
我將如何修改下面的格式字符串來實現這一點?
logging.Formatter('%(asctime)s %(filename)s:%(lineno)s %(levelname)5s - %(msg)s
更新:
正如@jonrsharpe 指出的那樣,沒有開箱即用的方法可以做到這一點,因此請自定義格式。
解決方案:@alecxe 推薦自定義Filter
,這里是一個完整的例子:
import logging
import logging.config
class FilenameLinenoFilter(logging.Filter):
def filter(self, record):
record.filename_lineno = '{}:{}'.format(record.filename, record.lineno)
return True
LOG_SETTINGS = {
'version': 1,
'filters': {
'filename_lineno_filter': {
'()': FilenameLinenoFilter,
},
},
'formatters': {
'standard': {
'format': '%(asctime)s %(filename_lineno)-18s %(levelname)5s - %(msg)s',
},
},
'handlers': {
'default': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'filters': ['filename_lineno_filter'],
'formatter': 'standard',
},
},
'loggers': {
'': {
'handlers': ['default'],
'level': 'DEBUG',
},
}
}
logging.config.dictConfig(LOG_SETTINGS)
logger = logging.getLogger()
logger.debug('Debug output goes here.')
logger.info('Informational goes here.')
您可以在自定義過濾器的幫助下創建組合字段:
import logging
class MyFilter(logging.Filter):
def filter(self, record):
record.filename_lineno = "%s:%d" % (record.filename, record.lineno)
return True
然后,您可以在格式字符串中引用%(filename_lineno)s
占位符。
Filter
不是這項工作的正確工具——過濾器用於決定哪些日志記錄被發出,哪些被靜音,而不是攔截日志記錄只是為了“猴子補丁”。
相反,從 Python 3.2 開始,您可以使用logging.setRecordFactory
函數注冊自定義LogRecord
子類或工廠函數以向每個LogRecord
添加自定義屬性:
import logging
class CustomLogRecord(logging.LogRecord):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.origin = f"{self.filename}:{self.lineno}"
然后,您可以在記錄器的格式字符串中設置此組合字段的寬度:
logging.setLogRecordFactory(CustomLogRecord)
logging.basicConfig(
style='{',
format="{asctime} {origin:20} {levelname} - {message}",
level=logging.INFO
)
logging.info("Test")
2020-06-26 16:10:03,193 scratch_2.py:16 INFO - Test
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.