![Build Status](https://github.com/madzak/python-json-logger/actions/workflows/build.yml/badge.svg)
[![License](https://img.shields.io/pypi/l/python-json-logger.svg)](https://pypi.python.org/pypi/python-json-logger/)
[![Version](https://img.shields.io/pypi/v/python-json-logger.svg)](https://pypi.python.org/pypi/python-json-logger/)
Overview
=======
This library is provided to allow standard python logging to output log data as json objects. With JSON we can make our logs more readable by machines and we can stop writing custom parsers for syslog type records.
News
=======
Hi, I see this package is quiet alive and I am sorry for ignoring it so long. I will be stepping up my maintenance of this package so please allow me a week to get things back in order (and most likely a new minor version) and I'll post and update here once I am caught up.
Installing
==========
Pip:
pip install python-json-logger
Pypi:
https://pypi.python.org/pypi/python-json-logger
Manual:
python setup.py install
Usage
=====
## Integrating with Python's logging framework
Json outputs are provided by the JsonFormatter logging formatter. You can add the custom formatter like below:
**Please note: version 0.1.0 has changed the import structure, please update to the following example for proper importing**
```python
import logging
from pythonjsonlogger import jsonlogger
logger = logging.getLogger()
logHandler = logging.StreamHandler()
formatter = jsonlogger.JsonFormatter()
logHandler.setFormatter(formatter)
logger.addHandler(logHandler)
```
## Customizing fields
The fmt parser can also be overidden if you want to have required fields that differ from the default of just `message`.
These two invocations are equivalent:
```python
class CustomJsonFormatter(jsonlogger.JsonFormatter):
def parse(self):
return self._fmt.split(';')
formatter = CustomJsonFormatter('one;two')
# is equivalent to:
formatter = jsonlogger.JsonFormatter('%(one)s %(two)s')
```
You can also add extra fields to your json output by specifying a dict in place of message, as well as by specifying an `extra={}` argument.
Contents of these dictionaries will be added at the root level of the entry and may override basic fields.
You can also use the `add_fields` method to add to or generally normalize the set of default set of fields, it is called for every log event. For example, to unify default fields with those provided by [structlog](http://www.structlog.org/) you could do something like this:
```python
class CustomJsonFormatter(jsonlogger.JsonFormatter):
def add_fields(self, log_record, record, message_dict):
super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)
if not log_record.get('timestamp'):
# this doesn't use record.created, so it is slightly off
now = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
log_record['timestamp'] = now
if log_record.get('level'):
log_record['level'] = log_record['level'].upper()
else:
log_record['level'] = record.levelname
formatter = CustomJsonFormatter('%(timestamp)s %(level)s %(name)s %(message)s')
```
Items added to the log record will be included in *every* log message, no matter what the format requires.
## Adding custom object serialization
For custom handling of object serialization you can specify default json object translator or provide a custom encoder
```python
def json_translate(obj):
if isinstance(obj, MyClass):
return {"special": obj.special}
formatter = jsonlogger.JsonFormatter(json_default=json_translate,
json_encoder=json.JSONEncoder)
logHandler.setFormatter(formatter)
logger.info({"special": "value", "run": 12})
logger.info("classic message", extra={"special": "value", "run": 12})
```
## Using a Config File
To use the module with a config file using the [`fileConfig` function](https://docs.python.org/3/library/logging.config.html#logging.config.fileConfig), use the class `pythonjsonlogger.jsonlogger.JsonFormatter`. Here is a sample config file.
```ini
[loggers]
keys = root,custom
[logger_root]
handlers =
[logger_custom]
level = INFO
handlers = custom
qualname = custom
[handlers]
keys = custom
[handler_custom]
class = StreamHandler
level = INFO
formatter = json
args = (sys.stdout,)
[formatters]
keys = json
[formatter_json]
format = %(message)s
class = pythonjsonlogger.jsonlogger.JsonFormatter
```
Example Output
==============
Sample JSON with a full formatter (basically the log message from the unit test). Every log message will appear on 1 line like a typical logger.
```json
{
"threadName": "MainThread",
"name": "root",
"thread": 140735202359648,
"created": 1336281068.506248,
"process": 41937,
"processName": "MainProcess",
"relativeCreated": 9.100914001464844,
"module": "tests",
"funcName": "testFormatKeys",
"levelno": 20,
"msecs": 506.24799728393555,
"pathname": "tests/tests.py",
"lineno": 60,
"asctime": ["12-05-05 22:11:08,506248"],
"message": "testing logging format",
"filename": "tests.py",
"levelname": "INFO",
"special": "value",
"run": 12
}
```
External Examples
=================
- [Wesley Tanaka - Structured log files in Python using python-json-logger](http://web.archive.org/web/20201130054012/https://wtanaka.com/node/8201)
- [Archive](https://web.archive.org/web/20201130054012/https://wtanaka.com/node/8201)
没有合适的资源?快使用搜索试试~ 我知道了~
标准 Python 记录器的 Json 格式化程序.zip
共18个文件
py:5个
txt:3个
md:2个
1.该资源内容由用户上传,如若侵权请联系客服进行举报
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
版权申诉
0 下载量 108 浏览量
2024-11-24
18:17:11
上传
评论
收藏 15KB ZIP 举报
温馨提示
概述此库用于允许标准 Python 日志记录将日志数据输出为 JSON 对象。使用 JSON,我们可以使日志更易于机器读取,并且无需再为 syslog 类型记录编写自定义解析器。消息嗨,我看到这个软件包很安静,很抱歉这么久没有更新。我将加强对这个软件包的维护,所以请给我一周时间让一切恢复正常(很可能是一个新的次要版本),一旦我跟上进度,我就会在这里发布和更新。安装点pip install python-json-logger皮皮https://pypi.python.org/pypi/python-json-logger手动的python setup.py install用法与 Python 的日志框架集成Json 输出由 JsonFormatter 日志格式化程序提供。您可以添加自定义格式化程序,如下所示请注意版本 0.1.0 已更改导入结构,请更新至以下示例以进行正确导入 import logging from pythonjsonlogger import jsonlogger logge
资源推荐
资源详情
资源评论
收起资源包目录
标准 Python 记录器的 Json 格式化程序.zip (18个子文件)
setup.py 2KB
.github
workflows
build.yml 989B
release.yml 713B
标签.txt 20B
src
pythonjsonlogger
__init__.py 0B
jsonlogger.py 10KB
py.typed 80B
LICENSE 1KB
requirements
ci.txt 60B
tests
__init__.py 0B
test_jsonlogger.py 12KB
CHANGELOG.md 3KB
tox.ini 501B
资源内容.txt 997B
MANIFEST.in 63B
.gitignore 129B
setup.cfg 1KB
README.md 5KB
共 18 条
- 1
资源评论
徐浪老师
- 粉丝: 8073
- 资源: 7322
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- 11月美宝莲专卖店店内海报 店内海报完稿310mmX360mm-op.ai
- 基于 Java 实现的24点卡牌游戏课程设计
- 基于ssm台球俱乐部管理系统 框架html + css + jquery + jsp + java + ssm + MySQL 用户类型 管理员 admin 123456 普通用户 002 0
- 纸中世界-跳跃游戏.sb3
- 通过示例在 Python 中解释 SOLID 原则 .zip
- 11月美宝莲专卖店背柜完稿740mmX400mm
- 基于ssm台球俱乐部管理系统 框架html + css + jquery + jsp + java + ssm + MySQL
- 通过 stdio 进行简单(但高效)的进程间通信,从 Node.js 运行 Python 脚本.zip
- STM32F030F4P6-LOCK+OLED
- 深度学习数据集详解与选用指南
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功