Skip to main content

Log without the setup via a pre-configured structlog logger with optional Sentry integration

Project description

Structlog-Sentry-Logger

CI codecov License PyPI - Python Version PyPI pre-commit Code style: black powered by semgrep


Documentation: https://structlog-sentry-logger.readthedocs.io

Source Code: https://github.com/TeoZosa/structlog-sentry-logger


:teacher: Overview

A multi-purpose, pre-configured, performance-optimized structlog logger with ( optional) Sentry integration via structlog-sentry.

:sparkles: Features

  1. Makes logging as easy as using print statements, but prettier and less smelly!
  2. Highly opinionated! There are only two (2) distinct configurations.
  3. Structured logs in JSON format means they are ready to be ingested by many of your favorite log analysis tools!

:confetti_ball: What You Get

:muscle: Powerful Automatic Context Fields

The pre-configured options include:

  1. :watch: Timestamps
    • DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
  2. :vertical_traffic_light: Log levels
    • Added to the JSON context for filtering and categorization
  3. :mag: Logger names
    • Automatically assigned to namespaced versions of the initializing python modules (.py files), relative to your project directory.
      • e.g., the logger in docs_src/sentry_integration.py is named docs_src.sentry_integration

With fields sorted by key for easier at-a-glance analysis.

:zap: Performance

structlog-sentry-logger is fully-tuned and leverages ORJSON as the JSON serializer for lightning-fast logging (more than a 4x speedup over Python's built-in JSON library[1]). It's 2021, you don't have to let your obligate cross-cutting concerns cripple performance any longer!

For further reference, see:

[1] source: Choosing a faster JSON library for Python: Benchmarking

:robot: Built-in Sentry Integration (Optional)

Automatically add much richer context to your Sentry reports.

  • Your entire logging context is sent as a Sentry event when the structlog-sentry-logger log level is error or higher.
    • i.e., logger.error(""), logger.exception("")
  • See structlog-sentry for more details.

Table of Contents

:tada: Installation

pip install structlog-sentry-logger

:rocket: Usage

:loud_sound: Pure structlog Logging (Without Sentry)

At the top of your Python module, import and instantiate the logger:

import structlog_sentry_logger

LOGGER = structlog_sentry_logger.get_logger()

Now anytime you want to print anything, don't. Instead do this:

LOG_MSG = "Information that's useful for future me and others"
LOGGER.info(LOG_MSG, extra_field="extra_value")

:memo: Note
All the regular Python logging levels are supported.

Which automatically produces this:

{
    "event": "Information that's useful for future me and others",
    "extra_field": "extra_value",
    "level": "info",
    "logger": "docs_src.pure_structlog_logging_without_sentry",
    "sentry": "skipped",
    "timestamp": "2020-10-18 15:30:05"
}

:goal_net: Sentry Integration

Export your Sentry DSN into your local environment.

  • An easy way to do this is to put it into a local .env file and use python-dotenv to populate your environment:
# On the command line:
SENTRY_DSN=YOUR_SENTRY_DSN
echo "SENTRY_DSN=${SENTRY_DSN}" >> .env

Then load the .env file in your Python code prior to instantiating the logger, e.g.:

from dotenv import find_dotenv, load_dotenv

load_dotenv(find_dotenv())

import structlog_sentry_logger

LOGGER = structlog_sentry_logger.get_logger()

:outbox_tray: Log Custom Context Directly to Sentry

With structlog, you can even incorporate custom messages in your exception handling which will automatically be reported to Sentry (thanks to the structlog-sentry module):

import uuid

import structlog_sentry_logger

LOGGER = structlog_sentry_logger.get_logger()

curr_user_logger = LOGGER.bind(uuid=uuid.uuid4().hex)  # LOGGER instance with bound UUID
try:
    curr_user_logger.warn("A dummy error for testing purposes is about to be thrown!")
    x = 1 / 0
except ZeroDivisionError as err:
    ERR_MSG = (
        "I threw an error on purpose for this example!\n"
        "Now throwing another that explicitly chains from that one!"
    )
    curr_user_logger.exception(ERR_MSG)
    raise RuntimeError(ERR_MSG) from err
{
    "event": "A dummy error for testing purposes is about to be thrown!",
    "level": "warning",
    "logger": "docs_src.sentry_integration",
    "sentry": "skipped",
    "timestamp": "2020-10-18 15:29:55",
    "uuid": "181e0e00b9034732af4fed2b8424fb11"
}
{
    "event": "I threw an error on purpose for this example!\nNow throwing another that explicitly chains from that one!",
    "exception": 'Traceback (most recent call last):\n  File "/app/structlog-sentry-logger/docs_src/sentry_integration.py", line 10, in <module>\n    x = 1 / 0\nZeroDivisionError: division by zero',
    "level": "error",
    "logger": "docs_src.sentry_integration",
    "sentry": "sent",
    "sentry_id": null,
    "timestamp": "2020-10-18 15:29:55",
    "uuid": "181e0e00b9034732af4fed2b8424fb11"
}
Traceback (most recent call last):
  File "/app/structlog-sentry-logger/docs_src/sentry_integration.py", line 10, in <module>
    x = 1 / 0
ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/app/structlog-sentry-logger/docs_src/sentry_integration.py", line 17, in <module>
    raise RuntimeError(ERR_MSG) from err
RuntimeError: I threw an error on purpose for this example!
Now throwing another that explicitly chains from that one!

:chart_with_downwards_trend: Output: Formatting & Storage

The default behavior is to stream JSON logs directly to the standard output stream like a proper 12 Factor App.

For local development, it often helps to prettify logging to stdout and save JSON logs to a .logs folder at the root of your project directory for later debugging. To enable this behavior, set the following environment variable (e.g. via python-dotenv as in the Sentry Integration section):

CI_ENVIRONMENT_SLUG=dev-local

In doing so, with our previous exception handling example we would get:

Output_Formatting_example

:wrench: Development

For convenience, implementation details of the below processes are abstracted away and encapsulated in single Make targets.

:fire: Tip
Invoking make without any arguments will display auto-generated documentation on available commands.

:building_construction: Package and Dependencies Installation

Make sure you have Python 3.7+ and poetry installed and configured.

To install the package and all dev dependencies, run:

make provision-environment

:fire: Tip
Invoking the above without poetry installed will emit a helpful error message letting you know how you can install poetry.

:package: Python Module to C-Extension Compilation

The projects's build.py file specifies which modules to package.

For manual per-module compilation, see: Mypyc Documentation: Getting started - Compiling and running

:white_check_mark: Testing

We use tox and pytest for our test automation and testing frameworks, respectively.

To invoke the tests, run:

make test

Run mutation tests to validate test suite robustness (Optional):

make test-mutations

:information_source: Technical Details
Test time scales with the complexity of the codebase. Results are cached in .mutmut-cache, so once you get past the initial cold start problem, subsequent mutation test runs will be much faster; new mutations will only be applied to modified code paths.

:rotating_light: Code Quality

We use pre-commit for our static analysis automation and management framework.

To invoke the analyses and auto-formatting over all version-controlled files, run:

make lint

:rotating_light: Danger
CI will fail if either testing or code quality fail, so it is recommended to automatically run the above locally prior to every commit that is pushed.

:arrows_counterclockwise: Automate via Git Pre-Commit Hooks

To automatically run code quality validation on every commit (over to-be-committed files), run:

make install-pre-commit-hooks

:warning:️ Warning
This will prevent commits if any single pre-commit hook fails (unless it is allowed to fail) or a file is modified by an auto-formatting job; in the latter case, you may simply repeat the commit and it should pass.

:memo: Documentation

make docs-clean docs-html

:fire: Tip
For faster feedback loops, this will attempt to automatically open the newly built documentation static HTML in your browser.

:clipboard: Summary

That's it. Now no excuses. Get out there and program with pride knowing no one will laugh at you in production! For not logging properly, that is. You're on your own for that other observability stuff.

:books: Further Reading

:one: structlog: Structured Logging for Python

:two: Sentry: Monitor and fix crashes in realtime

:three: structlog-sentry: Provides the structlog integration for Sentry


:judge: Legal

:page_facing_up: License

Structlog-Sentry-Logger is licensed under the Apache License, Version 2.0. See LICENSE for the full license text.

:busts_in_silhouette: Credits

This project was generated from @TeoZosa's cookiecutter-cruft-poetry-tox-pre-commit-ci-cd template.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

structlog-sentry-logger-0.9.1.tar.gz (28.1 kB view details)

Uploaded Source

Built Distributions

structlog_sentry_logger-0.9.1-cp39-cp39-win_amd64.whl (84.0 kB view details)

Uploaded CPython 3.9 Windows x86-64

structlog_sentry_logger-0.9.1-cp39-cp39-manylinux_2_31_x86_64.whl (306.7 kB view details)

Uploaded CPython 3.9 manylinux: glibc 2.31+ x86-64

structlog_sentry_logger-0.9.1-cp39-cp39-macosx_10_15_x86_64.whl (85.2 kB view details)

Uploaded CPython 3.9 macOS 10.15+ x86-64

structlog_sentry_logger-0.9.1-cp38-cp38-win_amd64.whl (82.8 kB view details)

Uploaded CPython 3.8 Windows x86-64

structlog_sentry_logger-0.9.1-cp38-cp38-manylinux_2_31_x86_64.whl (305.4 kB view details)

Uploaded CPython 3.8 manylinux: glibc 2.31+ x86-64

structlog_sentry_logger-0.9.1-cp38-cp38-macosx_10_15_x86_64.whl (84.3 kB view details)

Uploaded CPython 3.8 macOS 10.15+ x86-64

structlog_sentry_logger-0.9.1-cp37-cp37m-win_amd64.whl (82.6 kB view details)

Uploaded CPython 3.7m Windows x86-64

structlog_sentry_logger-0.9.1-cp37-cp37m-manylinux_2_31_x86_64.whl (285.4 kB view details)

Uploaded CPython 3.7m manylinux: glibc 2.31+ x86-64

structlog_sentry_logger-0.9.1-cp37-cp37m-macosx_10_15_x86_64.whl (83.3 kB view details)

Uploaded CPython 3.7m macOS 10.15+ x86-64

File details

Details for the file structlog-sentry-logger-0.9.1.tar.gz.

File metadata

  • Download URL: structlog-sentry-logger-0.9.1.tar.gz
  • Upload date:
  • Size: 28.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.2 CPython/3.9.7

File hashes

Hashes for structlog-sentry-logger-0.9.1.tar.gz
Algorithm Hash digest
SHA256 fbeaa4048a5ac5a25349e5700f8b5e55739fc9861aced33fc24f4049382acc38
MD5 fc125e4d6d2a4a9e8d35e77a1e52a733
BLAKE2b-256 183d49512e4d69dafd78e113c2bdee2ed09936b3da51220ddf099a9578c8dcf4

See more details on using hashes here.

File details

Details for the file structlog_sentry_logger-0.9.1-cp39-cp39-win_amd64.whl.

File metadata

  • Download URL: structlog_sentry_logger-0.9.1-cp39-cp39-win_amd64.whl
  • Upload date:
  • Size: 84.0 kB
  • Tags: CPython 3.9, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.2 CPython/3.9.7

File hashes

Hashes for structlog_sentry_logger-0.9.1-cp39-cp39-win_amd64.whl
Algorithm Hash digest
SHA256 537f4f84bfbd7bc528307dbf89c03fae04d2c781f1c439efa2f16f0cfdbc3131
MD5 c889da61fa69537b2d8b459366d97b61
BLAKE2b-256 3453e5d8419a95eb40616a8025c0a2546562be4faf18fa4b24ce1a292fcc3189

See more details on using hashes here.

File details

Details for the file structlog_sentry_logger-0.9.1-cp39-cp39-manylinux_2_31_x86_64.whl.

File metadata

  • Download URL: structlog_sentry_logger-0.9.1-cp39-cp39-manylinux_2_31_x86_64.whl
  • Upload date:
  • Size: 306.7 kB
  • Tags: CPython 3.9, manylinux: glibc 2.31+ x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.2 CPython/3.9.7

File hashes

Hashes for structlog_sentry_logger-0.9.1-cp39-cp39-manylinux_2_31_x86_64.whl
Algorithm Hash digest
SHA256 73172f20454344295ab58ab3e5bf70e8b4c5d7a9224e8156bfa30163c3d4514f
MD5 d0adc1f187f71688064a3b745014b1ee
BLAKE2b-256 6e7c2006610ee72192b683086f3c419a77e7a65a7e8c2e2bbd29d89b26a31726

See more details on using hashes here.

File details

Details for the file structlog_sentry_logger-0.9.1-cp39-cp39-macosx_10_15_x86_64.whl.

File metadata

  • Download URL: structlog_sentry_logger-0.9.1-cp39-cp39-macosx_10_15_x86_64.whl
  • Upload date:
  • Size: 85.2 kB
  • Tags: CPython 3.9, macOS 10.15+ x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.2 CPython/3.9.7

File hashes

Hashes for structlog_sentry_logger-0.9.1-cp39-cp39-macosx_10_15_x86_64.whl
Algorithm Hash digest
SHA256 3d5b8708e9bb49e17e84bec0df829dbc2c0e7097cfc1aa8db75fe876a42e2c3c
MD5 a84efd26c9326cd4cc53d3f12be35f89
BLAKE2b-256 b8288375ce2d4858c2d04a77e8ec14babf3fd9c9bbff8a7a54e7f8cbda28eb85

See more details on using hashes here.

File details

Details for the file structlog_sentry_logger-0.9.1-cp38-cp38-win_amd64.whl.

File metadata

  • Download URL: structlog_sentry_logger-0.9.1-cp38-cp38-win_amd64.whl
  • Upload date:
  • Size: 82.8 kB
  • Tags: CPython 3.8, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.2 CPython/3.9.7

File hashes

Hashes for structlog_sentry_logger-0.9.1-cp38-cp38-win_amd64.whl
Algorithm Hash digest
SHA256 7907bccab2786d60eb0d531d0395cc86ba7da578f080bbedbf338eab6e7130db
MD5 b56985b3b642aec14c948506fae5a21f
BLAKE2b-256 d9bb510bd7021aafb46681a9599e81880a33c8acdea1c72937c00e952b4f732b

See more details on using hashes here.

File details

Details for the file structlog_sentry_logger-0.9.1-cp38-cp38-manylinux_2_31_x86_64.whl.

File metadata

  • Download URL: structlog_sentry_logger-0.9.1-cp38-cp38-manylinux_2_31_x86_64.whl
  • Upload date:
  • Size: 305.4 kB
  • Tags: CPython 3.8, manylinux: glibc 2.31+ x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.2 CPython/3.9.7

File hashes

Hashes for structlog_sentry_logger-0.9.1-cp38-cp38-manylinux_2_31_x86_64.whl
Algorithm Hash digest
SHA256 aa0fbb582d0b57c939f4a93f56f76db392c63cf584ac64a22364a36e8f172948
MD5 a832cb01cc61aaec6597c103e03ea51c
BLAKE2b-256 8dedda57bbf206fc8fc46530cc2e047a0f56ff6c98f18aee22078e5b67e5bedf

See more details on using hashes here.

File details

Details for the file structlog_sentry_logger-0.9.1-cp38-cp38-macosx_10_15_x86_64.whl.

File metadata

  • Download URL: structlog_sentry_logger-0.9.1-cp38-cp38-macosx_10_15_x86_64.whl
  • Upload date:
  • Size: 84.3 kB
  • Tags: CPython 3.8, macOS 10.15+ x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.2 CPython/3.9.7

File hashes

Hashes for structlog_sentry_logger-0.9.1-cp38-cp38-macosx_10_15_x86_64.whl
Algorithm Hash digest
SHA256 bf0565bf489f05d6f617a6021283e1b1c42bfee916fc8d52d556d208c440560d
MD5 7739550e2a77b6548c84aabae3f9d2fb
BLAKE2b-256 2a33c38207077e35978d0920276a74ae3196d4e16a328af21f24b3c4de518b23

See more details on using hashes here.

File details

Details for the file structlog_sentry_logger-0.9.1-cp37-cp37m-win_amd64.whl.

File metadata

  • Download URL: structlog_sentry_logger-0.9.1-cp37-cp37m-win_amd64.whl
  • Upload date:
  • Size: 82.6 kB
  • Tags: CPython 3.7m, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.2 CPython/3.9.7

File hashes

Hashes for structlog_sentry_logger-0.9.1-cp37-cp37m-win_amd64.whl
Algorithm Hash digest
SHA256 fdebc396458daf60ad6dca124d1dcea969c960661b82e873411dc419ce8a7b89
MD5 f7636ef0f5b9d2aef3cd406e901d251b
BLAKE2b-256 42451c369f0dc9367f7fe50296d309f42c967a8f24ac7ca515b2fbdd15e49361

See more details on using hashes here.

File details

Details for the file structlog_sentry_logger-0.9.1-cp37-cp37m-manylinux_2_31_x86_64.whl.

File metadata

  • Download URL: structlog_sentry_logger-0.9.1-cp37-cp37m-manylinux_2_31_x86_64.whl
  • Upload date:
  • Size: 285.4 kB
  • Tags: CPython 3.7m, manylinux: glibc 2.31+ x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.2 CPython/3.9.7

File hashes

Hashes for structlog_sentry_logger-0.9.1-cp37-cp37m-manylinux_2_31_x86_64.whl
Algorithm Hash digest
SHA256 bf49340c555a74ad4eaa0f8538343cdc2034255fb70142ef7d8ed031f26123e5
MD5 455029e082ac9a25dab98fd6214f5974
BLAKE2b-256 1e2c8790c3aaf57e74aec19966816c9bb8894317c933d30d5726289eb2698b36

See more details on using hashes here.

File details

Details for the file structlog_sentry_logger-0.9.1-cp37-cp37m-macosx_10_15_x86_64.whl.

File metadata

File hashes

Hashes for structlog_sentry_logger-0.9.1-cp37-cp37m-macosx_10_15_x86_64.whl
Algorithm Hash digest
SHA256 9ffdf4a836d16d922276cb10a13d49e5243e4026df2bc0d763dac2177548aa5a
MD5 0656ce327cb1ab8122342067835bd4ba
BLAKE2b-256 ea7e0344411cae987edb940b0c49f46a35290f7d03c7a210d20371ab2b8b251d

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page