250 total views , 1 views today
測試環境為 CentOS 8 x86_64 (虛擬機)
參考文章 – https://docs.python.org/3/library/logging.html
在使用 ogging 以下 Method ,可以發現參數除了 msg 後面接著 *args, **kwargs 這是要怎麼使用?
- logging.debug(msg, *args, **kwargs)
- logging.info(msg, *args, **kwargs)
- logging.warning(msg, *args, **kwargs)
- logging.error(msg, *args, **kwargs)
- logging.critical(msg, *args, **kwargs)
- logging.exception(msg, *args, **kwargs)
- logging.log(level, msg, *args, **kwargs)
下面來看一下.
- *args
使用上跟 print 字串一樣. - **kwargs
kwargs (keyword arguments) 有 3 種使用方式.- exc_info – 看不懂
- stack_info – 看不懂
- extra – 在 formatter 來定義哪些資訊是透過字典 dict 資料型態物件來獲取.
字典 dict 資料型態物件定義使用大括號{} 來表示為 dic ,內的格式為 key:valu ( pair 組成 並由逗點隔開) 如下.d = {
'clientip'
:
'192.168.0.1'
,
'user'
:
'fbloggs'
}
看一下下面範例
[root@localhost ~]# python3 Python 3.6.8 ( default , Mar 25 2022, 11:15:52) [GCC 8.5.0 20210514 (Red Hat 8.5.0-10)] on linux Type "help" , "copyright" , "credits" or "license" for more information. >>> import logging >>> FORMAT = '%(asctime)s %(clientip)-15s %(user)-8s %(message)s' >>> logging.basicConfig(format=FORMAT) >>> d = { 'clientip' : '192.168.0.1' , 'user' : 'fbloggs' } >>> logging.warning( 'Protocol problem: %s' , 'connection reset' , extra=d) 2022-05-31 16:28:51,850 192.168.0.1 fbloggs Protocol problem: connection reset |
說明:
Formatter 格式請參考說明 – https://docs.python.org/3/library/logging.html#logrecord-attributes , 其中 clientip 與 user 是透過字典 dict 資料型態物件來獲取.
FORMAT = '%(asctime)s %(clientip)-15s %(user)-8s %(message)s' logging.basicConfig(format=FORMAT) |
logging.warning 這邊使用到 extra=d , d 就是我們定義的 字典 dict 資料型態物件.
d = { 'clientip' : '192.168.0.1' , 'user' : 'fbloggs' } logging.warning( 'Protocol problem: %s' , 'connection reset' , extra=d) |
Format 與輸出結果.
%(asctime)s -> 2022-05-31 16:28:51,850 |
%(clientip)-15s -> 192.168.0.1 |
%(user)-8s -> fbloggs |
%(message)s -> Protocol problem: %s ', ' connection reset' -> Protocol problem: connection reset |
沒有解決問題,試試搜尋本站其他內容