Developer Interface¶
- class jsonscribe.AttributeSetter(*args, **kwargs)[source]¶
Ensure that attributes exist on
LogRecord
s.The values in the add_fields mapping can be strings that start with
'ext://'
to invoke custom behaviors. The following values are recognized:- UUID
Generate a new UUIDv4 instance via
uuid.uuid4()
- now
Generate a new timezone-aware UTC
datetime.datetime
instance
- class jsonscribe.JSONFormatter(*args, **kwargs)[source]¶
Format log records as JSON documents.
- Parameters
This class will format
logging.LogRecord
instances into JSON bodies that are output as single lines by mostlogging.Handler
instances. The result is your log messages collected together as a nice json-lines file.You have to set the list of fields to include in the JSON bodies during initialization. If you are using the
logging.config.dictConfig()
function to configure the logging layer, then use the following syntax to configure the formatter factory with the fields that you want to include in the log messages:'formatters': { 'json': { '()': 'jsonscribe.JSONFormatter', 'include_fields': ['message'] } }
You can use any of the fields of
LogRecord
and they will be included. This includes fields that you add using either theextras
keyword parameter or alogging.LoggerAdapter
. If you happen to reference a field that does not exist, thenNone
is used by default. This avoids completely blowing up because when you make a mistake logging.A few fields have special handling applied to them. The exc_info field is formatted as an array of strings instead of a blob of newline separated text. Other fields are passed as-is to the JSON encoder with
_jsonify()
used as the default keyword to the encoder.- json_encoder¶
A single
json.JSONEncoder
instance is used throughout the lifetime of the formatter instance. You can modify it if necessary.
Note
The use_loggly_names parameter SHOULD be set to
True
in the configuration if the logs are being sent to loggly.com. Failure to do this will result in some fields not being correctly indexed.- _jsonify(obj)[source]¶
Provide formatting for common object types.
- Parameters
obj – an object that the default
json.JSONEncoder
cannot format- Returns
a decent
str
representation of obj
Unlike the standard JSON library, this hook will not raise an exception for an unserializable object. It returns the objects
repr
instead.
- format(record)[source]¶
Format a log record to a JSON object.
- Parameters
record (logging.LogRecord) – the record to format
- Returns
the JSON formatted version of record as a string
- Return type
- class jsonscribe.utils.UTCZone[source]¶
Free-standing implementation of the UTC timezone.
This is implemented to provide some compatibility with older Python versions.
- jsonscribe.utils.utc = <jsonscribe.utils.UTCZone object>¶
UTC timezone instance.
Use this with
datetime.datetime.now()
to produce a timezone aware UTC timestamp.