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 easier to capture and filter!
  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!
  4. Cloud Logging compatible!

:confetti_ball: What You Get

:muscle: Powerful Automatic Context Fields

The pre-configured options include:

  1. :watch: Timestamps
    • UTC time in ISO 8601 format (YYYY-MM-DDTHH:MM:SS.ffffffZ)
  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
  4. :mag_right: Function names and line numbers where logging calls were made

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

:zap: Performance

structlog-sentry-logger is C-compiled and fully-tuned, leveraging orjson as the JSON serializer for lightning-fast logging (more than a 4x speedup over Python's built-in JSON library[^1]; see here for sample performance benchmarks). Don't 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)

Simply import and instantiate the logger:

import structlog_sentry_logger

LOGGER = structlog_sentry_logger.get_logger()

Now you can start adding logs as easily as print statements:

LOGGER.info("Your log message", extra_field="extra_value")

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

Which automatically produces this:

{
    "event": "Your log message",
    "extra_field": "extra_value",
    "funcName": "<module>",
    "level": "info",
    "lineno": 5,
    "logger": "docs_src.pure_structlog_logging_without_sentry",
    "timestamp": "2022-01-11T07:05:37.164744Z"
}

:outbox_tray: Log Custom Context Directly to Sentry

Incorporate custom messages in your exception handling which will automatically be reported to Sentry (thanks to the structlog-sentry module). To enable this behavior, export the STRUCTLOG_SENTRY_LOGGER_CLOUD_SENTRY_INTEGRATION_MODE_ON environment variable.

An easy way to do this is to put it into a local .env file[^2]:

echo "STRUCTLOG_SENTRY_LOGGER_CLOUD_SENTRY_INTEGRATION_MODE_ON=" >> .env

For a concrete example, given the following Python code:

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

We would get the following output:

{
    "event": "A dummy error for testing purposes is about to be thrown!\n",
    "funcName": "<module>",
    "level": "warning",
    "lineno": 12,
    "logger": "docs_src.sentry_integration",
    "sentry": "skipped",
    "timestamp": "2022-01-06T04:50:07.627633Z",
    "uuid": "fe2bdcbe2ed74432a87bc76bcdc9def4"
}
{
    "event": "I threw an error on purpose for this example!\nNow throwing another that explicitly chains from that one!\n",
    "exc_info": true,
    "funcName": "<module>",
    "level": "error",
    "lineno": 19,
    "logger": "docs_src.sentry_integration",
    "sentry": "sent",
    "sentry_id": null,
    "timestamp": "2022-01-06T04:50:07.628316Z",
    "uuid": "fe2bdcbe2ed74432a87bc76bcdc9def4"
}
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!

:cloud: Cloud Logging Compatibility

The logger will attempt to infer if an application is running in a cloud environment by inspecting for the presence of environment variables that may be automatically injected by cloud providers (namely, KUBERNETES_SERVICE_HOST, GCP_PROJECT, and GOOGLE_CLOUD_PROJECT).

If any of these environment variables are detected, log levels will be duplicated to a reserved severity key in the emitted logs to enable parsing of the log level and the remaining log context (as jsonPayload) by Cloud Logging (see: Cloud Logging: Structured logging).

:memo: ️Note
This behavior can also be manually enabled by adding the STRUCTLOG_SENTRY_LOGGER_CLOUD_LOGGING_COMPATIBILITY_MODE_ON variable to your environment, e.g., via a .env file[^2].

:warning:️ Warning
If a user manually specifies a value for the severity key, it will be overwritten! Avoid using this key if possible to preempt any future issues.

: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, export the STRUCTLOG_SENTRY_LOGGER_LOCAL_DEVELOPMENT_LOGGING_MODE_ON environment variable, e.g., in your local .env file[^2]:

echo "STRUCTLOG_SENTRY_LOGGER_LOCAL_DEVELOPMENT_LOGGING_MODE_ON=" >> .env

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

Output_Formatting_example_0 Output_Formatting_example_1

[^2]: This library uses python-dotenv to automatically populate your environment with this variable (if it exists) from the local .env file. Alternatively, you may use direnv and a .envrc file. A sample .envrc file (with all features enabled) has been provided at the root of the repository (.envrc.sample). If direnv is already installed, it's as simple as copying .envrc.sample to the root of your project, editing it to reflect your desired configurations, renaming it to .envrc, and running direnv allow :tada:

: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


: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.

: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.17.3.tar.gz (29.7 kB view details)

Uploaded Source

Built Distributions

structlog_sentry_logger-0.17.3-cp39-cp39-win_amd64.whl (103.4 kB view details)

Uploaded CPython 3.9 Windows x86-64

structlog_sentry_logger-0.17.3-cp39-cp39-manylinux_2_31_x86_64.whl (183.4 kB view details)

Uploaded CPython 3.9 manylinux: glibc 2.31+ x86-64

structlog_sentry_logger-0.17.3-cp39-cp39-macosx_10_16_x86_64.whl (113.1 kB view details)

Uploaded CPython 3.9 macOS 10.16+ x86-64

structlog_sentry_logger-0.17.3-cp38-cp38-win_amd64.whl (102.5 kB view details)

Uploaded CPython 3.8 Windows x86-64

structlog_sentry_logger-0.17.3-cp38-cp38-manylinux_2_31_x86_64.whl (182.3 kB view details)

Uploaded CPython 3.8 manylinux: glibc 2.31+ x86-64

structlog_sentry_logger-0.17.3-cp38-cp38-macosx_10_16_x86_64.whl (110.5 kB view details)

Uploaded CPython 3.8 macOS 10.16+ x86-64

structlog_sentry_logger-0.17.3-cp37-cp37m-win_amd64.whl (101.2 kB view details)

Uploaded CPython 3.7m Windows x86-64

structlog_sentry_logger-0.17.3-cp37-cp37m-manylinux_2_31_x86_64.whl (155.6 kB view details)

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

structlog_sentry_logger-0.17.3-cp37-cp37m-macosx_10_16_x86_64.whl (108.6 kB view details)

Uploaded CPython 3.7m macOS 10.16+ x86-64

File details

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

File metadata

  • Download URL: structlog-sentry-logger-0.17.3.tar.gz
  • Upload date:
  • Size: 29.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.0 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.10

File hashes

Hashes for structlog-sentry-logger-0.17.3.tar.gz
Algorithm Hash digest
SHA256 ef7c007bd3158b352026d62c2a2f0e72a06be069e5326376618e57f564f46673
MD5 c0c2c81961b9883f53814ff7cbcf5931
BLAKE2b-256 34d2df8c758b0546105d477f2a68727da0ca75db6aed1ec1b472b8cd48f0cf17

See more details on using hashes here.

File details

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

File metadata

  • Download URL: structlog_sentry_logger-0.17.3-cp39-cp39-win_amd64.whl
  • Upload date:
  • Size: 103.4 kB
  • Tags: CPython 3.9, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.0 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.10

File hashes

Hashes for structlog_sentry_logger-0.17.3-cp39-cp39-win_amd64.whl
Algorithm Hash digest
SHA256 0ed14b159c41b3aa073d26dc1c414194adccec103b33027dd3a4b98d0537ccab
MD5 48af4100e80ef2d045e0dee1ed34eb16
BLAKE2b-256 2bc0a9852450c3053885844cfbf90c99374f8426099c277897a5b9c9eaf9be59

See more details on using hashes here.

File details

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

File metadata

  • Download URL: structlog_sentry_logger-0.17.3-cp39-cp39-manylinux_2_31_x86_64.whl
  • Upload date:
  • Size: 183.4 kB
  • Tags: CPython 3.9, manylinux: glibc 2.31+ x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.0 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.10

File hashes

Hashes for structlog_sentry_logger-0.17.3-cp39-cp39-manylinux_2_31_x86_64.whl
Algorithm Hash digest
SHA256 237a271d2ac65248dece8db321b1120727107dc84a7902c3a6add05e6e42d850
MD5 90e8ba6dcc9395a752bc1767ab4f80fb
BLAKE2b-256 4d572b67e2941c7e25538c7d605432b91c8147112be4ab92247cd7f37a1ffec6

See more details on using hashes here.

File details

Details for the file structlog_sentry_logger-0.17.3-cp39-cp39-macosx_10_16_x86_64.whl.

File metadata

  • Download URL: structlog_sentry_logger-0.17.3-cp39-cp39-macosx_10_16_x86_64.whl
  • Upload date:
  • Size: 113.1 kB
  • Tags: CPython 3.9, macOS 10.16+ x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.0 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.10

File hashes

Hashes for structlog_sentry_logger-0.17.3-cp39-cp39-macosx_10_16_x86_64.whl
Algorithm Hash digest
SHA256 992804b70d4020eda2b0b82545d0385460821d844b6a88a8f93c0a72bf363e4f
MD5 de0fae27ff6d4aa1e79ea5b80311f7cd
BLAKE2b-256 15240f7e9fbee3d4f52f749625b42284372d30ca76d5c36c593dd09b12ff437d

See more details on using hashes here.

File details

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

File metadata

  • Download URL: structlog_sentry_logger-0.17.3-cp38-cp38-win_amd64.whl
  • Upload date:
  • Size: 102.5 kB
  • Tags: CPython 3.8, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.0 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.10

File hashes

Hashes for structlog_sentry_logger-0.17.3-cp38-cp38-win_amd64.whl
Algorithm Hash digest
SHA256 a61d383d3515488911c712f438a32bb3318d8c66e4b11a01e8ac8a835ac8d8c8
MD5 f7aeb05ba852210fee330faefffc4682
BLAKE2b-256 9640e4de201315f82bc8726cf23356a125e18165eb70f29d7d51dbcf319130e4

See more details on using hashes here.

File details

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

File metadata

  • Download URL: structlog_sentry_logger-0.17.3-cp38-cp38-manylinux_2_31_x86_64.whl
  • Upload date:
  • Size: 182.3 kB
  • Tags: CPython 3.8, manylinux: glibc 2.31+ x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.0 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.10

File hashes

Hashes for structlog_sentry_logger-0.17.3-cp38-cp38-manylinux_2_31_x86_64.whl
Algorithm Hash digest
SHA256 cb5fb0ba57e5816da8b1941758a93a1e869f5d65337c266122e83992c9a1fee2
MD5 bbe64d01b02a48841b74de431545c5ee
BLAKE2b-256 ebee39c92e97a4946d6ece69f6a7c0b519c426c25a8d901ce36e25e0db164b1c

See more details on using hashes here.

File details

Details for the file structlog_sentry_logger-0.17.3-cp38-cp38-macosx_10_16_x86_64.whl.

File metadata

  • Download URL: structlog_sentry_logger-0.17.3-cp38-cp38-macosx_10_16_x86_64.whl
  • Upload date:
  • Size: 110.5 kB
  • Tags: CPython 3.8, macOS 10.16+ x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.0 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.10

File hashes

Hashes for structlog_sentry_logger-0.17.3-cp38-cp38-macosx_10_16_x86_64.whl
Algorithm Hash digest
SHA256 27c8c76aa8583c933b5e974187a91e552d216a525a3b9ddf5204816a658615c9
MD5 6a90c4abc85c25f728f0e3c1a89091b8
BLAKE2b-256 072ac9ac274c063f6da29296c44cb7680966e39d3c2b5b7b826dd4022e9d4e85

See more details on using hashes here.

File details

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

File metadata

  • Download URL: structlog_sentry_logger-0.17.3-cp37-cp37m-win_amd64.whl
  • Upload date:
  • Size: 101.2 kB
  • Tags: CPython 3.7m, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.0 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.10

File hashes

Hashes for structlog_sentry_logger-0.17.3-cp37-cp37m-win_amd64.whl
Algorithm Hash digest
SHA256 573a68c4b99f6dab447bb7a89ddc8d7be6a9f02946b159f470ebd3940d79de3c
MD5 85323aee5975ec498f486658b7246a6d
BLAKE2b-256 2e8496c6a71256d8c2eeedada4aba8cfb15495e86b045732ab3c137070f12783

See more details on using hashes here.

File details

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

File metadata

  • Download URL: structlog_sentry_logger-0.17.3-cp37-cp37m-manylinux_2_31_x86_64.whl
  • Upload date:
  • Size: 155.6 kB
  • Tags: CPython 3.7m, manylinux: glibc 2.31+ x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.0 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.10

File hashes

Hashes for structlog_sentry_logger-0.17.3-cp37-cp37m-manylinux_2_31_x86_64.whl
Algorithm Hash digest
SHA256 d109f8786d39902b9ac287a2f7e7a8bdbf94a9e02bac7c4056634e0db067b76e
MD5 9c2946d06644a87798ac9796122ad535
BLAKE2b-256 2393851900402249174aaec15336d772e99f1a3033a566622768ad9376966558

See more details on using hashes here.

File details

Details for the file structlog_sentry_logger-0.17.3-cp37-cp37m-macosx_10_16_x86_64.whl.

File metadata

  • Download URL: structlog_sentry_logger-0.17.3-cp37-cp37m-macosx_10_16_x86_64.whl
  • Upload date:
  • Size: 108.6 kB
  • Tags: CPython 3.7m, macOS 10.16+ x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.0 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.10

File hashes

Hashes for structlog_sentry_logger-0.17.3-cp37-cp37m-macosx_10_16_x86_64.whl
Algorithm Hash digest
SHA256 86339b4a8214db84dc48c68def3302947ca73f7e125a5074316ddd7bea9c8ff9
MD5 84e6a0e79b2c01173462b994060dc6af
BLAKE2b-256 2445e6fcab7bceacba486910d049bdffeb8852163f0edd13b7e2055f5216948c

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