logging_gelf.schemas
— Schemas¶
-
class
logging_gelf.schemas.
GelfSchema
¶ Schema which allow to specify a mapping for
logging.LogRecord
. It based onmarshmallow.Schema
. All schema MUST inherit from this.-
version
¶ The const version specify the GELF version.
-
host
¶ Hostname which emitted the log record. If not set,
socket.gethostname()
will be used.
-
short_message
¶ Plain message.
-
full_message
¶ Extended message
-
timestamp
¶ logging.LogRecord
creation time. Ifrecord.created
is not set, current timestamp will be set.
-
level
¶ Syslog level representation
-
lineno
¶ Origine line number. This value will be dump into line to match GELF spec.
-
pathname
¶ Origine file pathe. This value will be dump into file to match GELF spec.
-
classmethod
to_syslog_level
(value)¶ Map
value.levelno
into syslog level.Parameters: value (logging.LogRecord) – log record to serialize. Returns: syslog level Return type: int
-
classmethod
to_timestamp
(value)¶ Returns value.created or
time.time()
Parameters: value (logging.LogRecord) – log record to serialize. Returns: timestamp Return type: float
-
classmethod
to_message
(value)¶ Returns the
logging.LogRecord
formatted message.Parameters: value (logging.LogRecord) – log record to serialize. Returns: entry message Return type: str
-
fix_additional_fields
(data)¶ A “post dump” method which finalize data by prefixing with a “_” the additionals fields.
-
Note
Only fields set in the model will be serilialized.
Example¶
>>> import logging
>>> from logging_gelf.schemas import GelfSchema
>>> rec = logging.LogRecord(
... name="test-gelf", level=logging.DEBUG, pathname=None,
... lineno=None, msg="test", args=list(), exc_info=None
)
>>> GelfSchema().dump(rec).data
{'level': 7, 'line': None, 'host': 'host.example.com', 'short_message': 'test', 'version': '1.1', 'file': None, 'timestamp': 1484831977.3012216}
Nested fields¶
As Graylog doesn’t support objects, Nested marshmallow fields are “flat unpacked” using a pseudo path in keys:
>>> import logging
>>> import sys
>>> from logging_gelf.formatters import GELFFormatter
>>> from marshmallow import fields, Schema
>>> from logging_gelf.schemas import GelfSchema
>>> class Person(Schema):
... firstname = fields.String()
...
>>> class Family(GelfSchema):
... lastname = fields.String()
... father = fields.Nested(Person)
...
>>> familly = dict(lastname="Dumay", father=dict(firstname="Cedric"))
>>> logger = logging.getLogger("gelf")
>>> logger.setLevel(logging.DEBUG)
>>> handler = logging.StreamHandler(sys.stdout)
>>> handler.setFormatter(GELFFormatter(schema=Family))
>>> logger.addHandler(handler)
>>> logger.debug("A marshmallow example with Nested", extra=familly)
{"level": 7, "_father_firstname": "Cedric", "short_message": "A marshmallow example with Nested", "_lastname": "Dumay", "file": "<stdin>", "host": "host.example.com", "timestamp": 1484919251.3890517, "version": "1.1", "line": 1}
Note
As we can see familly['father']['firstname']
produce a GELF attribute _father_firstname