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


Overview

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

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!

What You Get

:muscle: Powerful Automatic Context Fields

The pre-configured options include:

  1. Timestamps
    • DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
  2. Log levels
    • Added to the JSON context for filtering and categorization
  3. 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

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"
}

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

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.

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.

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

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

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.

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.

Documentation

make docs-clean docs-html

:memo: Note
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

structlog: Structured Logging for Python

Sentry: Monitor and fix crashes in realtime.

structlog-sentry: Provides the structlog SentryProcessor for Sentry integration.


:page_facing_up: Legal

License

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

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.0.tar.gz (22.4 kB view details)

Uploaded Source

Built Distributions

structlog_sentry_logger-0.9.0-cp39-cp39-win_amd64.whl (16.6 kB view details)

Uploaded CPython 3.9 Windows x86-64

structlog_sentry_logger-0.9.0-cp39-cp39-manylinux_2_31_x86_64.whl (16.6 kB view details)

Uploaded CPython 3.9 manylinux: glibc 2.31+ x86-64

structlog_sentry_logger-0.9.0-cp39-cp39-macosx_10_15_x86_64.whl (16.6 kB view details)

Uploaded CPython 3.9 macOS 10.15+ x86-64

structlog_sentry_logger-0.9.0-cp38-cp38-win_amd64.whl (16.6 kB view details)

Uploaded CPython 3.8 Windows x86-64

structlog_sentry_logger-0.9.0-cp38-cp38-manylinux_2_31_x86_64.whl (16.6 kB view details)

Uploaded CPython 3.8 manylinux: glibc 2.31+ x86-64

structlog_sentry_logger-0.9.0-cp38-cp38-macosx_10_15_x86_64.whl (16.6 kB view details)

Uploaded CPython 3.8 macOS 10.15+ x86-64

structlog_sentry_logger-0.9.0-cp37-cp37m-win_amd64.whl (16.6 kB view details)

Uploaded CPython 3.7m Windows x86-64

structlog_sentry_logger-0.9.0-cp37-cp37m-manylinux_2_31_x86_64.whl (16.6 kB view details)

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

structlog_sentry_logger-0.9.0-cp37-cp37m-macosx_10_15_x86_64.whl (16.6 kB view details)

Uploaded CPython 3.7m macOS 10.15+ x86-64

File details

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

File metadata

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

File hashes

Hashes for structlog-sentry-logger-0.9.0.tar.gz
Algorithm Hash digest
SHA256 b19e08e0141ec02abccccfed79802e8a343f89c7470bb402db76914961bfc0ee
MD5 54ac4bdfb6e393c553dbac33800a27b0
BLAKE2b-256 3b13507bf88b3fb6e89af2dc8f61a602d833e7885b98abe58985114969e05803

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for structlog_sentry_logger-0.9.0-cp39-cp39-win_amd64.whl
Algorithm Hash digest
SHA256 e060b008afcdd918a4d079f07c7de39f99ea670c95673d3af3d69c20d38517bf
MD5 e7315d368a4371af09ffdee4be74d386
BLAKE2b-256 e3dacce9d7d31935cd6de72c5963619cffe452b2d8ebdf714b30ad4025716ca7

See more details on using hashes here.

File details

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

File metadata

  • Download URL: structlog_sentry_logger-0.9.0-cp39-cp39-manylinux_2_31_x86_64.whl
  • Upload date:
  • Size: 16.6 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.6.3 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.0 CPython/3.9.6

File hashes

Hashes for structlog_sentry_logger-0.9.0-cp39-cp39-manylinux_2_31_x86_64.whl
Algorithm Hash digest
SHA256 c70698e5e8d17fa8f3921f6876d8ec325960379ded6f9cd5660e6ea3be7fe470
MD5 26b407fc6e4e3e4ef78685fd41224f30
BLAKE2b-256 591f05e9b5b939108299dc27d972246bbb9fda4eb27efa6427e0967655eb02d2

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for structlog_sentry_logger-0.9.0-cp39-cp39-macosx_10_15_x86_64.whl
Algorithm Hash digest
SHA256 4260c236b8de0bb4530d62c0d993b92017fb16d23f3205dd245b3613b8482bcb
MD5 070ef0adc4285c1c8d44e979340f22fd
BLAKE2b-256 e1bfe244c7bf5949d2977e1dfe0c55fa19fe0699f26b72930385d4f82cba6f5d

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for structlog_sentry_logger-0.9.0-cp38-cp38-win_amd64.whl
Algorithm Hash digest
SHA256 9780fc34796a0855229156459a972b3115ccdca7df0a4f5cf6976b41d293746e
MD5 61919bcdd4bacbcb327c2bff292e7583
BLAKE2b-256 bb69ec8d67daf86035758cd8a323448418ab12f6b6804dd41c21597ea3b9d2bf

See more details on using hashes here.

File details

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

File metadata

  • Download URL: structlog_sentry_logger-0.9.0-cp38-cp38-manylinux_2_31_x86_64.whl
  • Upload date:
  • Size: 16.6 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.6.3 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.0 CPython/3.9.6

File hashes

Hashes for structlog_sentry_logger-0.9.0-cp38-cp38-manylinux_2_31_x86_64.whl
Algorithm Hash digest
SHA256 e9fe7c63202365c07e6a98b63a15f815198680f08e64155f6be68183f2962d5e
MD5 905b1881bda56b0c50690e4d8f08af4b
BLAKE2b-256 7236b9bae7a31b26eb3d2644598dda58ee35183c2ce944d3a21ab10c97020161

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for structlog_sentry_logger-0.9.0-cp38-cp38-macosx_10_15_x86_64.whl
Algorithm Hash digest
SHA256 49adb0aa5a4f7c8fb6f8140c12b8e7aaf42e5a74f2424542fb132bc4148fe9e4
MD5 e0725d6cf77e934301385242cc9f31da
BLAKE2b-256 37f3fc4e40e723eb052bfba92c82584ca29f3466385c1ec83d49d6c14e0a46dd

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for structlog_sentry_logger-0.9.0-cp37-cp37m-win_amd64.whl
Algorithm Hash digest
SHA256 b28de6dc16c0ccfb06f5d5990be25743b80356e2f3e16e011cde009cfe3389f5
MD5 bc324847c360d77e7d21f6e0302ea297
BLAKE2b-256 002695bca6bfc1ceff7e63ea119b399549d211bd14e2ac4474fe65f9389a0daf

See more details on using hashes here.

File details

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

File metadata

  • Download URL: structlog_sentry_logger-0.9.0-cp37-cp37m-manylinux_2_31_x86_64.whl
  • Upload date:
  • Size: 16.6 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.6.3 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.0 CPython/3.9.6

File hashes

Hashes for structlog_sentry_logger-0.9.0-cp37-cp37m-manylinux_2_31_x86_64.whl
Algorithm Hash digest
SHA256 a329d57a888924bb74ddf41b5adebea00eebf6508a2d25417ffadc5f0cf32bdf
MD5 3dbd3127234538f51ec961376cba61d0
BLAKE2b-256 0ce2edb0e60300abdec8507dd5ee697bdb3c0aeed2cbddc0f920517da7863fc9

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for structlog_sentry_logger-0.9.0-cp37-cp37m-macosx_10_15_x86_64.whl
Algorithm Hash digest
SHA256 c98f5e738e2217e6714bac73928126c3c7fb76fc0d27cac60c37479ee9a86a0d
MD5 83b5bac2ee12386e0921aeb8add245e8
BLAKE2b-256 e8e013f3efec4759c1c54b3fd8d6cfe388616253425649c3ff29dc84d58195bb

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