為了配合LogStash日志收集服務,需要將線上服務的日志輸出改為json格式。python日志標準庫中并沒有json格式的formatter,網上雖然已經有一些json相關的formatter,但不是很滿意,就自己開發了一個并放到了github和pypi,目前僅支持 Python3 ,能夠很方便的解決 自定義名映射屬性 問題,也支持新增 自定義屬性 。
歡迎到我的github點星星、提問題:
https://github.com/MyColorfulDays/jsonformatter
先睹為快
核心配置
LogRecord屬性介紹可參考Python官網地址:
https://docs.python.org/3/library/logging.html#logrecord-attributes
# 自定義屬性
# key代表LogRecord新增/替換的屬性名稱
# value必須`callable`類型,且不支持參數
CUSTOM_ATTRS
=
{
"session_id"
:
lambda
:
str
(
random
.
random
(
)
)
[
2
:
10
]
}
# 輸出格式配置
# 支持json字符串,OrderedDict,dict(由于Python3.7之前dict是無序的,所以3.7之前的版本推薦使用OrderedDict或json字符串)
# key的值可任意
# value必須是LogRecord的屬性或新增的自定義屬性
# value也可以是“%(attribute)s/d/f”,它將被轉為字符串格式輸出,不再保持LogRecord屬性的原類型
# value如果包含多個LogRecord的屬性,必須為“%(attribute)s/d/f”格式拼接
# message若不屬于`str, int, float, bool, type(None)`,會自動被轉為字符串(防止輸出日志時報錯:xxx type is not JSON serializable.)
STRING_FORMAT
=
'''{
"@timestamp": "asctime",
"Module": "module",
"Lineno": "lineno",
"Str Lineno": "%(lineno)d",
"Level": "levelname",
"Session Id": "session_id",
"Multi Attrs": "%(module)s - %(lineno)d: %(funcName)s ",
"Message": "message"
}'''
輸出結果
$ python test_jsonformatter.py
{
"@timestamp"
:
"2019-07-12 16:43:36,889"
,
"Module"
:
"test_jsonformatter"
,
"Lineno"
:
46,
"Str Lineno"
:
"46"
,
"Level"
:
"INFO"
,
"Session Id"
:
"51916201"
,
"Multi Attrs"
:
"test_jsonformatter - 46: test_logger "
,
"Message"
:
1
}
{
"@timestamp"
:
"2019-07-12 16:43:36,889"
,
"Module"
:
"test_jsonformatter"
,
"Lineno"
:
47,
"Str Lineno"
:
"47"
,
"Level"
:
"INFO"
,
"Session Id"
:
"10761601"
,
"Multi Attrs"
:
"test_jsonformatter - 47: test_logger "
,
"Message"
:
"{}"
}
{
"@timestamp"
:
"2019-07-12 16:43:36,889"
,
"Module"
:
"test_jsonformatter"
,
"Lineno"
:
48,
"Str Lineno"
:
"48"
,
"Level"
:
"INFO"
,
"Session Id"
:
"42298281"
,
"Multi Attrs"
:
"test_jsonformatter - 48: test_logger "
,
"Message"
:
"測試參數: arg1"
}
完整代碼
test_jsonformatter.py
import
logging
import
random
from
jsonformatter
import
JsonFormatter
# 自定義屬性
# key代表LogRecord新增/替換的屬性名稱
# value必須`callable`類型,且不支持參數
CUSTOM_ATTRS
=
{
"session_id"
:
lambda
:
str
(
random
.
random
(
)
)
[
2
:
10
]
}
# 輸出格式配置
# 支持json字符串,OrderedDict,dict(由于Python3.7之前dict是無序的,所以3.7之前的版本推薦使用OrderedDict或json字符串)
# key的值可任意
# value必須是LogRecord的屬性或新增的自定義屬性
# value也可以是“%(attribute)s/d/f”,它將被轉為字符串格式輸出,不再保持LogRecord屬性的原類型
# value如果包含多個LogRecord的屬性,必須為“%(attribute)s/d/f”格式拼接
# message屬性若不屬于`str, int, float, bool, type(None)`,會自動被轉為字符串(防止輸出日志是報錯:xxx type is not JSON serializable.)
STRING_FORMAT
=
'''{
"@timestamp": "asctime",
"Module": "module",
"Lineno": "lineno",
"Str Lineno": "%(lineno)d",
"Level": "levelname",
"Session Id": "session_id",
"Multi Attrs": "%(module)s - %(lineno)d: %(funcName)s ",
"Message": "message"
}'''
def
config_logger
(
)
:
logger
=
logging
.
getLogger
(
)
logger
.
setLevel
(
logging
.
INFO
)
# JsonFormatter支持`json.dumps`的所有可選參數
formatter
=
JsonFormatter
(
STRING_FORMAT
,
record_custom_attrs
=
CUSTOM_ATTRS
,
indent
=
4
,
ensure_ascii
=
False
)
sh
=
logging
.
StreamHandler
(
)
sh
.
setFormatter
(
formatter
)
sh
.
setLevel
(
logging
.
INFO
)
logger
.
addHandler
(
sh
)
def
test_logger
(
)
:
logger
=
logging
.
getLogger
(
)
logger
.
info
(
1
)
logger
.
info
(
{
}
)
logger
.
info
(
"測試參數: %s"
,
'arg1'
)
if
__name__
==
'__main__'
:
config_logger
(
)
test_logger
(
)
日志的配置也支持通過配置文件方式設置,可以到我的github查看。
安裝
pip安裝:
$ pip
install
jsonformatter
克隆github源碼手工安裝:
$
git
clone https://github.com/MyColorfulDays/jsonformatter.git
$
cd
jsonformatter
$ python setup.py
install
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
