Skip to content
This repository was archived by the owner on Dec 21, 2024. It is now read-only.

Commit 4ab18e6

Browse files
committed
Add some more examples to the README
Since it's longer, I also added some sub-headings.
1 parent d864a7b commit 4ab18e6

File tree

2 files changed

+82
-38
lines changed

2 files changed

+82
-38
lines changed

README.markdown

Lines changed: 76 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ Manual:
2121
Usage
2222
=====
2323

24+
## Integrating with Python's logging framework
25+
2426
Json outputs are provided by the JsonFormatter logging formatter. You can add the customer formatter like below:
2527

2628
**Please note: version 0.1.0 has changed the import structure, please update to the following example for proper importing**
@@ -36,64 +38,101 @@ Json outputs are provided by the JsonFormatter logging formatter. You can add th
3638
logHandler.setFormatter(formatter)
3739
logger.addHandler(logHandler)
3840
```
39-
The fmt parser can also be overidden if you want to use an alternate from the default.
41+
42+
## Customizing fields
43+
44+
The fmt parser can also be overidden if you want to have required fields that differ from the default of just `message`.
45+
46+
These two invocations are equivalent:
4047

4148
```python
42-
class CustomJsonFormatter(jsonlogger.JsonFormatter):
43-
def parse(self):
44-
return eval(self._fmt)
49+
class CustomJsonFormatter(jsonlogger.JsonFormatter):
50+
def parse(self):
51+
return self._fmt.split(';')
52+
53+
formatter = CustomJsonFormatter('one;two')
54+
55+
# is equivalent to:
56+
57+
formatter = jsonlogger.JsonFormatter('(one) (two)')
4558
```
4659

47-
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.
60+
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.
61+
4862
Contents of these dictionaries will be added at the root level of the entry and may override basic fields.
63+
64+
You can also use the `add_fields` method to add to or generally normalize the set of default set of fields, it is be 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:
65+
66+
```python
67+
class CustomJsonFormatter(jsonlogger.JsonFormatter):
68+
def add_fields(self, log_record, record, message_dict):
69+
super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)
70+
if not log_record.get('timestamp'):
71+
# this doesn't use record.created, so it is slightly off
72+
now = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
73+
log_record['timestamp'] = now
74+
if log_record.get('level'):
75+
log_record['level'] = log_record['level'].upper()
76+
else:
77+
log_record['level'] = record.levelname
78+
79+
formatter = CustomJsonFormatter('(timestamp) (level) (name) (message)')
80+
```
81+
82+
Items added to the log record will be included in *every* log message, no matter what the format requires.
83+
84+
## Adding custom object serialization
85+
4986
For custom handling of object serialization you can specify default json object translator or provide a custom encoder
5087

5188
```python
52-
def json_translate(obj):
53-
if isinstance(obj, MyClass):
54-
return {"special": obj.special}
89+
def json_translate(obj):
90+
if isinstance(obj, MyClass):
91+
return {"special": obj.special}
5592

56-
formatter = jsonlogger.JsonFormatter(json_default=json_translate,
57-
json_encoder=json.JSONEncoder())
58-
logHandler.setFormatter(formatter)
93+
formatter = jsonlogger.JsonFormatter(json_default=json_translate,
94+
json_encoder=json.JSONEncoder())
95+
logHandler.setFormatter(formatter)
5996

60-
logger.info({"special": "value", "run": 12})
61-
logger.info("classic message", extra={"special": "value", "run": 12})
97+
logger.info({"special": "value", "run": 12})
98+
logger.info("classic message", extra={"special": "value", "run": 12})
6299
```
63100

64-
With a Config File
65-
------------------
101+
## Using a Config File
102+
66103
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.
67104

68-
[loggers]
69-
keys = root,custom
105+
```ini
106+
[loggers]
107+
keys = root,custom
70108

71-
[logger_root]
72-
handlers =
109+
[logger_root]
110+
handlers =
73111

74-
[logger_custom]
75-
level = INFO
76-
handlers = custom
77-
qualname = custom
112+
[logger_custom]
113+
level = INFO
114+
handlers = custom
115+
qualname = custom
78116

79-
[handlers]
80-
keys = custom
117+
[handlers]
118+
keys = custom
81119

82-
[handler_custom]
83-
class = StreamHandler
84-
level = INFO
85-
formatter = json
86-
args = (sys.stdout,)
120+
[handler_custom]
121+
class = StreamHandler
122+
level = INFO
123+
formatter = json
124+
args = (sys.stdout,)
87125

88-
[formatters]
89-
keys = json
126+
[formatters]
127+
keys = json
90128

91-
[formatter_json]
92-
format = %(message)s
93-
class = pythonjsonlogger.jsonlogger.JsonFormatter
129+
[formatter_json]
130+
format = %(message)s
131+
class = pythonjsonlogger.jsonlogger.JsonFormatter
132+
```
94133

95-
Example
96-
=======
134+
Example Output
135+
==============
97136

98137
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.
99138

src/pythonjsonlogger/jsonlogger.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,12 @@ def _default_json_handler(obj):
8585
self._skip_fields.update(RESERVED_ATTR_HASH)
8686

8787
def parse(self):
88-
"""Parses format string looking for substitutions"""
88+
"""
89+
Parses format string looking for substitutions
90+
91+
This method is responsible for returning a list of fields (as strings)
92+
to include in all log messages.
93+
"""
8994
standard_formatters = re.compile(r'\((.+?)\)', re.IGNORECASE)
9095
return standard_formatters.findall(self._fmt)
9196

0 commit comments

Comments
 (0)