Skip to main content

Cosmolog

Cosmolog provides structured log formatting for your application. It treats logs as event streams and will record each log event as a json object with a schema.

CosmologEvent Schema

A cosmolog event looks like the following:

{
    "version": 0,
    "stream_name": "foo_nginx",
    "origin": "foo-api1.com",
    "timestamp": "2016-09-02T16:34:12.019105Z",
    "format": "service {name} started",
    "level": 400,
    "payload": {"name": "foo"}
}

version     (int)    The version of the logging schema.
stream_name (string) The name that identifies the log stream.
origin      (string) FQDN of the host on which the stream originated.
timestamp   (string) UTC ISO8601 formatted datetime string.
format      (string) Optional Python Format String to format the payload to
                     make it human-readable. Please use format strings with
                     replacement fields that are delimited with "{}".
level       (int)    The log level.
payload     (dict)   A flat dictionary of key-value pairs where keys are
                     strings and values can be any scalar type.

Installation

pip install cosmolog

Quick Start

from cosmolog import setup_logging
from cosmolog import Cosmologger

setup_logging()

l = Cosmologger('foo')
l.info('Hello World')
l.info('Hello {person}', person='Dave')
l.info(value1=0.98, value2=4.0)

Human

human is a command line tool that formats machine readable logs for humans. It reads stdin and writes formatted lines to stdout.

$ echo '{"origin": "enterprise.starfleet.com", "stream_name": "telemetry", "format": "Measurement complete: gravity={gravity}", "timestamp": "2016-10-19T04:13:15.049920Z", "level": 400, "version": 0, "payload": {"gravity": 1.8}}' | human
Oct 19 04:13:15 enterprise.starfleet.com telemetry: [INFO] Measurement complete: gravity=1.8

Advanced Usage: setup_logging

setup_logging provides basic Python logging configuration with CosmologgerFormatter class as the default logging formatter. The default logging configuration looks like the following:

LOGGING_CONFIG = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'cosmolog': {
            '()': CosmologgerFormatter,
            'origin': origin,
            'version': 0,
        },
    },
    'handlers': {
        'default': {
            'class': 'logging.StreamHandler',
            'formatter': 'cosmolog'
        },
    },
    'root': {
        'handlers': ['default'],
        'level': level,
    }
}

By default, origin is set to socket.getfqdn(). To set it yourself:

setup_logging(origin='my-fully-qualified-domain.com')

You can configure Cosmologger with a custom configuration dictionary, as you would with regular Python logging. Let's say you want to stream your log entries to a file in the CosmologEvent schema, as well as stderr in a human- readable format:

my_custom_config = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'cosmolog': {
            '()': CosmologgerFormatter,
            'origin': origin,
            'version': 0,
        },
        'cosmolog-human': {
            '()': CosmologgerHumanFormatter,
            'origin': origin,
            'version': 0,
        },
    },
    'handlers': {
        'file_handler': {
            'class': 'logging.FileHandler',
            'formatter': 'cosmolog',
            'filename': '/path/to/my/file.log'
        },
        'stderr': {
            'class': 'logging.StreamHandler',
            'formatter': 'cosmolog-human',
	'color': True
        },
    },
    'root': {
        'handlers': ['file_handler', 'stderr'],
        'level': 'DEBUG',
    }
}

setup_logging(custom_config=my_custom_config)

By default, your log level will be set to INFO. You can set it to a different level:

setup_logging(level='DEBUG')

The table below shows the level names, and the numberic values they will be mapped to in the log output:

Level Numeric value
FATAL 100
ERROR 200
WARN 300
INFO 400
DEBUG 500
TRACE 600

Advanced usage: Exceptions

Normally, all keyword arguments are faithfully passed into the CosmologEvent payload field, except in the case of logging exceptions. Here, the conventions of the builtin logging library are followed. Calling Cosmologger.exception or any of the other logging methods with the keyword argument exc_info=1 will add traceback information to the payload's exc_text field. If there is no {exc_text} specified in the format string, then the format field will be appended with '\n{exc_text}'.

Development

pip install -e .[test]
tox

Release files for cosmolog 0.9.13

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cosmolog 0.9.13
File Size Uploaded
cosmolog-0.9.13.tar.gz 17.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for cosmolog 0.9.13
File Interpreter ABI Platform
cosmolog-0.9.13-py3-none-any.whl Python 3 none any Details

Total release size: 31.7 kB

Release files / cosmolog-0.9.13.tar.gz

Download URL cosmolog-0.9.13.tar.gz
Size 17.4 kB
Tags Source
SHA-256 checksum
How to use checksums
f8abcdeb0465c141488ebd7087e02110f5662654cf3391b8bfb0d94df5b7bf9b
BLAKE2b-256 checksum
How to use checksums
bb828fab32fdda96f904e8c1e4d7164086c1a0f1caf9fe10473468ce1837788c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.12

Release files / cosmolog-0.9.13-py3-none-any.whl

Download URL cosmolog-0.9.13-py3-none-any.whl
Size 14.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
73793a88e5ee38f6b2eab1ac98fc20ec59060989ed872055164f7e61da4f43d3
BLAKE2b-256 checksum
How to use checksums
f8b278b290cdf39c77c57b5d4d8f47a6cdec2027e46f1ea99ceba1fffb50654c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.12

Release history Release notifications | RSS feed

This release

0.9.13 This release

2 release files

0.9.12

2 release files

0.9.10

2 release files

0.9.9

2 release files

0.9.8

2 release files

0.9.7

2 release files

0.9.4

1 release file

0.9.0

1 release file

0.8.0

1 release file

0.7.0

1 release file

0.6.1

1 release file

0.6.0

1 release file

0.5.0

1 release file

0.4.3

1 release file

0.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page