Skip to content

pythonjsonlogger.core ๐Ÿ”—

Core functionality shared by all JSON loggers

LogRecord module-attribute ๐Ÿ”—

LogRecord: TypeAlias = Dict[str, Any]

Type alias

OptionalCallableOrStr module-attribute ๐Ÿ”—

OptionalCallableOrStr: TypeAlias = Optional[
    Union[Callable, str]
]

Type alias

RESERVED_ATTRS module-attribute ๐Ÿ”—

RESERVED_ATTRS: List[str] = [
    "args",
    "asctime",
    "created",
    "exc_info",
    "exc_text",
    "filename",
    "funcName",
    "levelname",
    "levelno",
    "lineno",
    "module",
    "msecs",
    "message",
    "msg",
    "name",
    "pathname",
    "process",
    "processName",
    "relativeCreated",
    "stack_info",
    "thread",
    "threadName",
]

Default reserved attributes.

These come from the default attributes of LogRecord objects.

Note

Although considered a constant, this list is dependent on the Python version due to different LogRecord objects having different attributes in different Python versions.

Changed in 3.0: RESERVED_ATTRS is now list[str] instead of tuple[str, ...].

BaseJsonFormatter ๐Ÿ”—

BaseJsonFormatter(
    fmt: Optional[str] = None,
    datefmt: Optional[str] = None,
    style: str = "%",
    validate: bool = True,
    *,
    prefix: str = "",
    rename_fields: Optional[Dict[str, str]] = None,
    rename_fields_keep_missing: bool = False,
    static_fields: Optional[Dict[str, Any]] = None,
    reserved_attrs: Optional[Sequence[str]] = None,
    timestamp: Union[bool, str] = False,
    defaults: Optional[Dict[str, Any]] = None
)

Bases: Formatter

Base class for all formatters

Must not be used directly.

New in 3.1

PARAMETER DESCRIPTION
fmt

string representing fields to log

TYPE: Optional[str] DEFAULT: None

datefmt

format to use when formatting asctime field

TYPE: Optional[str] DEFAULT: None

style

how to extract log fields from fmt

TYPE: str DEFAULT: '%'

validate

validate fmt against style, if implementing a custom style you must set this to False.

TYPE: bool DEFAULT: True

defaults

ignored - kept for compatibility with python 3.10+

TYPE: Optional[Dict[str, Any]] DEFAULT: None

prefix

an optional string prefix added at the beginning of the formatted string

TYPE: str DEFAULT: ''

rename_fields

an optional dict, used to rename field names in the output. Rename message to @message: {'message': '@message'}

TYPE: Optional[Dict[str, str]] DEFAULT: None

rename_fields_keep_missing

When renaming fields, include missing fields in the output.

TYPE: bool DEFAULT: False

static_fields

an optional dict, used to add fields with static values to all logs

TYPE: Optional[Dict[str, Any]] DEFAULT: None

reserved_attrs

an optional list of fields that will be skipped when outputting json log record. Defaults to all log record attributes.

TYPE: Optional[Sequence[str]] DEFAULT: None

timestamp

an optional string/boolean field to add a timestamp when outputting the json log record. If string is passed, timestamp will be added to log record using string as key. If True boolean is passed, timestamp key will be "timestamp". Defaults to False/off.

TYPE: Union[bool, str] DEFAULT: False

Changed in 3.1:

  • you can now use custom values for style by setting validate to False. The value is stored in self._style as a string. The parse method will need to be overridden in order to support the new style.
  • Renaming fields now preserves the order that fields were added in and avoids adding missing fields. The original behaviour, missing fields have a value of None, is still available by setting rename_fields_keep_missing to True.

add_fields ๐Ÿ”—

add_fields(
    log_record: Dict[str, Any],
    record: LogRecord,
    message_dict: Dict[str, Any],
) -> None

Extract fields from a LogRecord for logging

This method can be overridden to implement custom logic for adding fields.

PARAMETER DESCRIPTION
log_record

data that will be logged

TYPE: Dict[str, Any]

record

the record to extract data from

TYPE: LogRecord

message_dict

dictionary that was logged instead of a message. e.g logger.info({"is_this_message_dict": True})

TYPE: Dict[str, Any]

format ๐Ÿ”—

format(record: LogRecord) -> str

Formats a log record and serializes to json

PARAMETER DESCRIPTION
record

the record to format

TYPE: LogRecord

jsonify_log_record ๐Ÿ”—

jsonify_log_record(log_record: LogRecord) -> str

Convert this log record into a JSON string.

Child classes MUST override this method.

PARAMETER DESCRIPTION
log_record

the data to serialize

TYPE: LogRecord

parse ๐Ÿ”—

parse() -> List[str]

Parses format string looking for substitutions

This method is responsible for returning a list of fields (as strings) to include in all log messages.

You can support custom styles by overriding this method.

RETURNS DESCRIPTION
List[str]

list of fields to be extracted and serialized

process_log_record ๐Ÿ”—

process_log_record(log_record: LogRecord) -> LogRecord

Custom processing of the log record.

Child classes can override this method to alter the log record before it is serialized.

PARAMETER DESCRIPTION
log_record

incoming data

TYPE: LogRecord

serialize_log_record ๐Ÿ”—

serialize_log_record(log_record: LogRecord) -> str

Returns the final representation of the log record.

PARAMETER DESCRIPTION
log_record

the log record

TYPE: LogRecord

merge_record_extra ๐Ÿ”—

merge_record_extra(
    record: LogRecord,
    target: Dict,
    reserved: Container[str],
    rename_fields: Optional[Dict[str, str]] = None,
) -> Dict

Merges extra attributes from LogRecord object into target dictionary

PARAMETER DESCRIPTION
record

logging.LogRecord

TYPE: LogRecord

target

dict to update

TYPE: Dict

reserved

dict or list with reserved keys to skip

TYPE: Container[str]

rename_fields

an optional dict, used to rename field names in the output. e.g. Rename levelname to log.level: {'levelname': 'log.level'}

TYPE: Optional[Dict[str, str]] DEFAULT: None

Changed in 3.1: reserved is now Container[str].

str_to_object ๐Ÿ”—

str_to_object(obj: Any) -> Any

Import strings to an object, leaving non-strings as-is.

PARAMETER DESCRIPTION
obj

the object or string to process

TYPE: Any

New in 3.1