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)

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:

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",
    "sentry": "skipped",
    "timestamp": "2022-01-06T04:48:40.795891Z"
}

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

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!\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.

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

echo "STRUCTLOG_SENTRY_LOGGER_LOCAL_DEVELOPMENT_LOGGING_MODE_ON=" >> .env

And it will be automatically picked up when the library is first imported:

# The below automatically sources library-relevant values from your local `.env` file
import structlog_sentry_logger

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:

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

Uploaded Source

Built Distributions

structlog_sentry_logger-0.16.0-cp39-cp39-win_amd64.whl (87.7 kB view details)

Uploaded CPython 3.9 Windows x86-64

structlog_sentry_logger-0.16.0-cp39-cp39-manylinux_2_31_x86_64.whl (160.0 kB view details)

Uploaded CPython 3.9 manylinux: glibc 2.31+ x86-64

structlog_sentry_logger-0.16.0-cp39-cp39-macosx_12_0_arm64.whl (164.7 kB view details)

Uploaded CPython 3.9 macOS 12.0+ ARM64

structlog_sentry_logger-0.16.0-cp39-cp39-macosx_10_16_x86_64.whl (97.6 kB view details)

Uploaded CPython 3.9 macOS 10.16+ x86-64

structlog_sentry_logger-0.16.0-cp38-cp38-win_amd64.whl (86.7 kB view details)

Uploaded CPython 3.8 Windows x86-64

structlog_sentry_logger-0.16.0-cp38-cp38-manylinux_2_31_x86_64.whl (159.0 kB view details)

Uploaded CPython 3.8 manylinux: glibc 2.31+ x86-64

structlog_sentry_logger-0.16.0-cp38-cp38-macosx_10_16_x86_64.whl (95.9 kB view details)

Uploaded CPython 3.8 macOS 10.16+ x86-64

structlog_sentry_logger-0.16.0-cp37-cp37m-win_amd64.whl (85.4 kB view details)

Uploaded CPython 3.7m Windows x86-64

structlog_sentry_logger-0.16.0-cp37-cp37m-manylinux_2_31_x86_64.whl (135.3 kB view details)

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

structlog_sentry_logger-0.16.0-cp37-cp37m-macosx_10_16_x86_64.whl (94.0 kB view details)

Uploaded CPython 3.7m macOS 10.16+ x86-64

File details

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

File metadata

  • Download URL: structlog-sentry-logger-0.16.0.tar.gz
  • Upload date:
  • Size: 28.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.9

File hashes

Hashes for structlog-sentry-logger-0.16.0.tar.gz
Algorithm Hash digest
SHA256 e303c7e909cb398a7dfe7226632d42f5df6517ff21d39e26f9f8225b2746e36b
MD5 8f4b569664e3bf263a232433491757a1
BLAKE2b-256 5464d0b37d9cd45d0e826dc39a04d734bc767f586d47c0ac903e53163b9500a0

See more details on using hashes here.

File details

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

File metadata

  • Download URL: structlog_sentry_logger-0.16.0-cp39-cp39-win_amd64.whl
  • Upload date:
  • Size: 87.7 kB
  • Tags: CPython 3.9, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.9

File hashes

Hashes for structlog_sentry_logger-0.16.0-cp39-cp39-win_amd64.whl
Algorithm Hash digest
SHA256 b7e3fd68b8589e26597c3b26ebd94c75bf651c199746231eea8f7da11a47012d
MD5 c79c84cfa9bc53e3a1c3846d69c46028
BLAKE2b-256 faa744a6625a7aa55193adb0486282bbdacc794236d03da4a8ed85d40c68648c

See more details on using hashes here.

File details

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

File metadata

  • Download URL: structlog_sentry_logger-0.16.0-cp39-cp39-manylinux_2_31_x86_64.whl
  • Upload date:
  • Size: 160.0 kB
  • Tags: CPython 3.9, manylinux: glibc 2.31+ x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.9

File hashes

Hashes for structlog_sentry_logger-0.16.0-cp39-cp39-manylinux_2_31_x86_64.whl
Algorithm Hash digest
SHA256 14fbd419504e77981f4a8f31687efad3b072cf2d913196929e2108e54dc05254
MD5 14120a0c267d9be3103d6b40eba6c11d
BLAKE2b-256 04e05f1f6fa4a9f1a1f68821f244bd1c6f74da57d13574a3fe0c4605a3207e58

See more details on using hashes here.

File details

Details for the file structlog_sentry_logger-0.16.0-cp39-cp39-macosx_12_0_arm64.whl.

File metadata

File hashes

Hashes for structlog_sentry_logger-0.16.0-cp39-cp39-macosx_12_0_arm64.whl
Algorithm Hash digest
SHA256 ba1a48a20af6612db2dae21252a86113fe61928522d53c76f46f9d54eb246791
MD5 2e95dd5f554c0f5c004cd07d13de9f96
BLAKE2b-256 300ee588b65e5c5dbc5fb17b0e82d68209692eaa11685fcdfb634bc1275702c0

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for structlog_sentry_logger-0.16.0-cp39-cp39-macosx_10_16_x86_64.whl
Algorithm Hash digest
SHA256 139ab7781f18f267dffae75639a54cd20480b668e203f2ec14cc0a58fa0c8708
MD5 d043280553d290e1bc855b8a8ce0fcd8
BLAKE2b-256 c91a1fb25db4516285a95c3cf7aa1a00d250444c2b4b25e52a72d3f2b7f45c9e

See more details on using hashes here.

File details

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

File metadata

  • Download URL: structlog_sentry_logger-0.16.0-cp38-cp38-win_amd64.whl
  • Upload date:
  • Size: 86.7 kB
  • Tags: CPython 3.8, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.9

File hashes

Hashes for structlog_sentry_logger-0.16.0-cp38-cp38-win_amd64.whl
Algorithm Hash digest
SHA256 d78340256104b6fa8c9a0c6b4de86c9ba9c960db8cededed33ebc36ba0e33228
MD5 4e9b7e3193d2f26a6bd64b5c3673a718
BLAKE2b-256 466b607b13f6351ea69ed427396ba606876c871f9ba123b1a1f81c8fb07d4a5f

See more details on using hashes here.

File details

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

File metadata

  • Download URL: structlog_sentry_logger-0.16.0-cp38-cp38-manylinux_2_31_x86_64.whl
  • Upload date:
  • Size: 159.0 kB
  • Tags: CPython 3.8, manylinux: glibc 2.31+ x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.9

File hashes

Hashes for structlog_sentry_logger-0.16.0-cp38-cp38-manylinux_2_31_x86_64.whl
Algorithm Hash digest
SHA256 d2eed15a9d75eef50fbf6e1ca92507bccf573da36c44dc06e5e393aca1b5b02d
MD5 d51e2297c0c4547f7af22f9fe53ebc87
BLAKE2b-256 47c6f807b325806e3d32aa99c25f61871c651985c8394213b2f811691c6a9990

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for structlog_sentry_logger-0.16.0-cp38-cp38-macosx_10_16_x86_64.whl
Algorithm Hash digest
SHA256 3c00e500d013a4729ba2cdb18a1fd3aafcb154e767554c11ba26d1de69a1a28a
MD5 31507aa5b60fe6bcdd636ed23a75eb50
BLAKE2b-256 466e6fbb89da94c8ad4057202c5bc666b7aa90ae312db994b35b341ff2801c78

See more details on using hashes here.

File details

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

File metadata

  • Download URL: structlog_sentry_logger-0.16.0-cp37-cp37m-win_amd64.whl
  • Upload date:
  • Size: 85.4 kB
  • Tags: CPython 3.7m, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.9

File hashes

Hashes for structlog_sentry_logger-0.16.0-cp37-cp37m-win_amd64.whl
Algorithm Hash digest
SHA256 b210459581ced0608dc444192c2f13125cb476ebb4766956d86bd710e8cc5b37
MD5 ebd70cb2fdfab5be3bfd7c3d49a509db
BLAKE2b-256 1baf920bcce7fbf95c6fd97f6d1f37b963e585b069823ce9688bb7a1639fd293

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for structlog_sentry_logger-0.16.0-cp37-cp37m-manylinux_2_31_x86_64.whl
Algorithm Hash digest
SHA256 4b5dbc39ce4c08ff97833bd3bf4241258881e4415874b447e58523572b31cb70
MD5 a3cd59651651faa9debc1f7b955ef4fe
BLAKE2b-256 9148399c6088233b053fd2947fdfdd987992e22bd6e86e24d6fb60e2196c6a6e

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for structlog_sentry_logger-0.16.0-cp37-cp37m-macosx_10_16_x86_64.whl
Algorithm Hash digest
SHA256 03487dd67c28f94c54ef92f28fc0ae314e53e800f83be2288f0c95958a02fd7a
MD5 96dbe86737f6e4ace496bdb62f519878
BLAKE2b-256 b2bcb0d18a155d68737345530f79cd0f87601a215ff34b25fd81aeeca381dcaa

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