Case 4. In Flask project, add LogRecord attribute for auto output
flask_demo.py
import datetime
import json
import logging
import random
from collections import OrderedDict
from jsonformatter import JsonFormatter
from flask import Flask, has_request_context, request, session
from flask.logging import default_handler
app = Flask(__name__)
# the key will add/replace `LogRecord` attribute.
# the value must be `callable` type and not support positional paramters, the returned value will be as the `LogRecord` attribute value.
RECORD_CUSTOM_ATTRS = {
# no parameters
'url': lambda: request.url if has_request_context() else None,
'username': lambda: session['username'] if has_request_context() and ('username' in session) else None,
# Arbitrary keywords parameters
'status': lambda **record_attrs: 'failed' if record_attrs['levelname'] in ['ERROR', 'CRITICAL'] else 'success'
}
RECORD_CUSTOM_FORMAT = OrderedDict([
# custom record attributes start
("Url", "url"),
("Username", "username"),
("Status", "status"),
# custom record attributes end
("Name", "name"),
("Levelno", "levelno"),
("Levelname", "levelname"),
("Pathname", "pathname"),
("Filename", "filename"),
("Module", "module"),
("Lineno", "lineno"),
("FuncName", "funcName"),
("Created", "created"),
("Asctime", "asctime"),
("Msecs", "msecs"),
("RelativeCreated", "relativeCreated"),
("Thread", "thread"),
("ThreadName", "threadName"),
("Process", "process"),
("Message", "message")
])
formatter = JsonFormatter(
RECORD_CUSTOM_FORMAT,
record_custom_attrs=RECORD_CUSTOM_ATTRS
)
default_handler.setFormatter(formatter)
app.logger.warning('hello, jsonformatter')
Case 4. Solve cumtom LogRecord attribute is not JSON serializable
import datetime
import json
import logging
import random
from collections import OrderedDict
from jsonformatter import JsonFormatter
# the key will add/replace `LogRecord` attribute.
# the value must be `callable` type and not support positional paramters, the returned value will be as the `LogRecord` attribute value.
RECORD_CUSTOM_ATTRS = {
# `datetime.datetime` type is not JSON serializable.
# solve it in three ways, choose which you like.
# 1. use `LogRecord` attribute `Format`: %(asctme)s.
# 2. use `json.dumps` optional parameter `default`.
# 3. use `json.dumps` optional parameter `cls`.
'asctime': lambda: datetime.datetime.today(),
'user id': lambda: str(random.random())[2:10]
}
RECORD_CUSTOM_FORMAT = OrderedDict([
("User id", "user id"), # new custom attrs
("Name", "name"),
("Levelno", "levelno"),
("Levelname", "levelname"),
("Pathname", "pathname"),
("Filename", "filename"),
("Module", "module"),
("Lineno", "lineno"),
("FuncName", "funcName"),
("Created", "created"),
("Asctime", "%(asctime)s"), # use `LogRecord` attribute `Format` to find matched key from RECORD_CUSTOM_ATTRS and call it value.
("Msecs", "msecs"),
("RelativeCreated", "relativeCreated"),
("Thread", "thread"),
("ThreadName", "threadName"),
("Process", "process"),
("Message", "message")
])
# use `json.dumps` optional parameter `default`
def DEFAULT_SOLUTION(o):
if not isinstance(o, (str, int, float, bool, type(None))):
return str(o)
else:
return o
# use `json.dumps` optional parameter `cls`
class CLS_SOLUTION(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime.datetime):
return o.isoformat()
return json.JSONEncoder.default(self, o)
root = logging.getLogger()
root.setLevel(logging.INFO)
formatter = JsonFormatter(RECORD_CUSTOM_FORMAT, record_custom_attrs=RECORD_CUSTOM_ATTRS, default=DEFAULT_SOLUTION, cls=CLS_SOLUTION)
sh = logging.StreamHandler()
sh.setFormatter(formatter)
sh.setLevel(logging.INFO)
root.addHandler(sh)
root.info('record custom attrs')
The tuple of arguments merged into msg to produce message, or a dict whose values are used for the merge (when there is only one argument, and it is a dictionary).
asctime
%(asctime)s
Human-readable time when the LogRecord was created. By default this is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma are millisecond portion of the time).
created
%(created)f
Time when the LogRecord was created (as returned by time.time()).
exc_info
You shouldn’t need to format this yourself.
Exception tuple (à la sys.exc_info) or, if no exception has occurred, None.
filename
%(filename)s
Filename portion of pathname.
funcName
%(funcName)s
Name of function containing the logging call.
levelname
%(levelname)s
Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').
levelno
%(levelno)s
Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL).
lineno
%(lineno)d
Source line number where the logging call was issued (if available).
message
%(message)s
The logged message, computed as msg % args. This is set when Formatter.format() is invoked.
module
%(module)s
Module (name portion of filename).
msecs
%(msecs)d
Millisecond portion of the time when the LogRecord was created.
msg
You shouldn’t need to format this yourself.
The format string passed in the original logging call. Merged with args to produce message, or an arbitrary object (see Using arbitrary objects as messages).
name
%(name)s
Name of the logger used to log the call.
pathname
%(pathname)s
Full pathname of the source file where the logging call was issued (if available).
process
%(process)d
Process ID (if available).
processName
%(processName)s
Process name (if available).
relativeCreated
%(relativeCreated)d
Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
stack_info
You shouldn’t need to format this yourself.
Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call which resulted in the creation of this record.
thread
%(thread)d
Thread ID (if available).
threadName
%(threadName)s
Thread name (if available).
Alternatives
Use instead of jsonformatter: tools that do the same job, closest first.