Reputation: 136497
I have a Python logging configuration which looks like this:
LOGGING_CONFIG:
version: 1
formatters:
human:
class: logging.Formatter
format: '[%(asctime)s]:[%(levelname)s]: %(message)s'
json:
class: pythonjsonlogger.jsonlogger.JsonFormatter
format: '%(asctime)s %(levelname)s %(message)s'
handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: json # change this to 'human' when you run it locally, json in production
file:
class: logging.FileHandler
filename: logfile.log
level: DEBUG
formatter: json
root: # Logging for 3rd party stuff
level: INFO
handlers:
- console
- file
project_name: # Logging this module
level: DEBUG
handlers:
- console
- file
For another system, I need the structured logging to have some fixed names. One example is that it should not be levelname
, but level
. How can I rename log fields?
What I have:
{"asctime": "2018-10-22 14:50:19,923", "levelname": "info", "message": "foobar"}
What I want:
{"asctime": "2018-10-22 14:50:19,923", "level": "info", "message": "foobar"}
Upvotes: 7
Views: 3617
Reputation: 653
You should be able to do it with this following configuration:
...
formatters:
json:
format: "%(asctime)s [%(process)d] [%(levelname)s] %(message)s"
(): pythonjsonlogger.jsonlogger.JsonFormatter
rename_fields:
levelname: level
timestamp: true
...
Upvotes: 1
Reputation: 6546
levelname
will not appear in normal Python loggers but in the custom formatter you used. From what I understood you could use below snippet to customize the dict it outputs:
class CustomJsonFormatter(jsonlogger.JsonFormatter):
def add_fields(self, log_record, record, message_dict):
super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)
log_record['level'] = log_record['levelname']
del log_record['levelname']
Then replace pythonjsonlogger.jsonlogger.JsonFormatter
with the address of CustomJsonFormatter
.
Upvotes: 11