Log without the setup via a pre-configured structlog logger with optional Sentry integration
Project description
Structlog-Sentry-Logger
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
- Makes logging as easy as using print statements, but prettier and easier to capture and filter!
- Highly opinionated! There are only two (2) distinct configurations.
- Structured logs in JSON format means they are ready to be ingested by many of your favorite log analysis tools!
- Cloud Logging compatible!
:confetti_ball: What You Get
:muscle: Powerful Automatic Context Fields
The pre-configured options include:
- :watch: Timestamps
- UTC time in ISO 8601 format
(
YYYY-MM-DDTHH:MM:SS.ffffffZ
)
- UTC time in ISO 8601 format
(
- :vertical_traffic_light: Log levels
- Added to the JSON context for filtering and categorization
- :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 nameddocs_src.sentry_integration
- e.g., the logger in
- Automatically assigned to namespaced versions of the initializing python
modules (
- :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:
- "
orjson
: Serialize" for benchmarks - "
structlog
: Performance" for salient performance-related configurations.
[^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 iserror
or higher.- i.e.,
logger.error("")
,logger.exception("")
- i.e.,
- See
structlog-sentry
for more details.
Table of Contents
- :tada: Installation
- :rocket: Usage
- :chart_with_downwards_trend: Output: Formatting & Storage
- :clipboard: Summary
- :books: Further Reading
- :wrench: Development
- :judge: Legal
: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 theSTRUCTLOG_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 theseverity
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:
[^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
Invokingmake
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 withoutpoetry
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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distributions
File details
Details for the file structlog-sentry-logger-0.17.0.tar.gz
.
File metadata
- Download URL: structlog-sentry-logger-0.17.0.tar.gz
- Upload date:
- Size: 29.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
Algorithm | Hash digest | |
---|---|---|
SHA256 | 935cc4048d4f6947a0dffc9e1bf271a1ee1c5f41088aaeadc946d64acf19afb2 |
|
MD5 | 04fa3cf1d13f007091f2f8ac94f1fe2c |
|
BLAKE2b-256 | 117bbade6fd61d8f26371851ae5d19c8afb005ae9afb87177bf2876e0fce7897 |
File details
Details for the file structlog_sentry_logger-0.17.0-cp39-cp39-win_amd64.whl
.
File metadata
- Download URL: structlog_sentry_logger-0.17.0-cp39-cp39-win_amd64.whl
- Upload date:
- Size: 100.0 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
Algorithm | Hash digest | |
---|---|---|
SHA256 | 10c4ebf406f7fa88184506f7d4fe84b264c8629cc3137aec59c86dfc32622a8f |
|
MD5 | a0c37a3609a4517f3fa0807bda80749e |
|
BLAKE2b-256 | 8e9c37e00f89185aa3cb5933897142e209366cfb4d920f08e086f615c1eda0ce |
File details
Details for the file structlog_sentry_logger-0.17.0-cp39-cp39-manylinux_2_31_x86_64.whl
.
File metadata
- Download URL: structlog_sentry_logger-0.17.0-cp39-cp39-manylinux_2_31_x86_64.whl
- Upload date:
- Size: 178.5 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
Algorithm | Hash digest | |
---|---|---|
SHA256 | 32ed59a988f97f9dfda733afa025c6ae17652570e933614bcfe64010ab4b9d9f |
|
MD5 | ceedc5303b3713f24bbcdcca17749e95 |
|
BLAKE2b-256 | 4071355083078667ff81b3e228d0141763aaf5ec38ba53fc199a0d792ecfd460 |
File details
Details for the file structlog_sentry_logger-0.17.0-cp39-cp39-macosx_10_16_x86_64.whl
.
File metadata
- Download URL: structlog_sentry_logger-0.17.0-cp39-cp39-macosx_10_16_x86_64.whl
- Upload date:
- Size: 109.0 kB
- Tags: CPython 3.9, macOS 10.16+ 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
Algorithm | Hash digest | |
---|---|---|
SHA256 | 6080722e15320d730c629218d2c598287342c4bd6c9b07060e21e4786ae4d95a |
|
MD5 | 3403e8c405578b5af8fb9c7f117ed6c0 |
|
BLAKE2b-256 | ef7f145c8a0720ff6839a9e45ae81f2b5f60cf9f1226ab94fb0b9aefe767268f |
File details
Details for the file structlog_sentry_logger-0.17.0-cp38-cp38-win_amd64.whl
.
File metadata
- Download URL: structlog_sentry_logger-0.17.0-cp38-cp38-win_amd64.whl
- Upload date:
- Size: 99.2 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
Algorithm | Hash digest | |
---|---|---|
SHA256 | 43beb731b2139273a5fdbe440f8eb45ddde1bfecd9b399a1d53ac76a8e07452e |
|
MD5 | b2326f3a3a700ac1cd789dee56cdccfc |
|
BLAKE2b-256 | 71731f31af679502435b9fef48defdc563bf8ee9b6ff18a2eaed32aeae0f80d3 |
File details
Details for the file structlog_sentry_logger-0.17.0-cp38-cp38-manylinux_2_31_x86_64.whl
.
File metadata
- Download URL: structlog_sentry_logger-0.17.0-cp38-cp38-manylinux_2_31_x86_64.whl
- Upload date:
- Size: 177.2 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
Algorithm | Hash digest | |
---|---|---|
SHA256 | 631ae48f13fc34c555fa3bd7f96c660a1e26e3459e79dd37f8cdb9d3735dcc40 |
|
MD5 | 72bebcee81942fccf1e47c4e2aad1aa0 |
|
BLAKE2b-256 | 65c7f7bcbe5801b32dea6bb4bf15b013b651166e5044f7f29368b5d196272470 |
File details
Details for the file structlog_sentry_logger-0.17.0-cp38-cp38-macosx_10_16_x86_64.whl
.
File metadata
- Download URL: structlog_sentry_logger-0.17.0-cp38-cp38-macosx_10_16_x86_64.whl
- Upload date:
- Size: 107.1 kB
- Tags: CPython 3.8, macOS 10.16+ 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
Algorithm | Hash digest | |
---|---|---|
SHA256 | 2998bae621b3c2a7147e3df84a0b7111316212e0c64254286255bf868271332d |
|
MD5 | c6c1cfe42048e0f8977cc2df6cb9761d |
|
BLAKE2b-256 | a0072c6f305d306a6cdac6906c7f4e11a68f34c362d124f6e1f092ee40e77044 |
File details
Details for the file structlog_sentry_logger-0.17.0-cp37-cp37m-win_amd64.whl
.
File metadata
- Download URL: structlog_sentry_logger-0.17.0-cp37-cp37m-win_amd64.whl
- Upload date:
- Size: 97.9 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
Algorithm | Hash digest | |
---|---|---|
SHA256 | 001e1b58a70a2acbe70c254c44b0b5622a6c0d7e8af86057b300e28a8b9205cb |
|
MD5 | cb9be5d9162270c574c9eac2fe60755f |
|
BLAKE2b-256 | 194c4077ef0b090ebaf30632b5eaf5ab06586d25149a95d75320d3488e1a213b |
File details
Details for the file structlog_sentry_logger-0.17.0-cp37-cp37m-manylinux_2_31_x86_64.whl
.
File metadata
- Download URL: structlog_sentry_logger-0.17.0-cp37-cp37m-manylinux_2_31_x86_64.whl
- Upload date:
- Size: 152.6 kB
- Tags: CPython 3.7m, 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
Algorithm | Hash digest | |
---|---|---|
SHA256 | cb1a284bfd4db5b6fd168c610c60d47f5881827840cbafb35c67e258b916ddb2 |
|
MD5 | 209460028e3f66e294c0e467410976e6 |
|
BLAKE2b-256 | a4f58d85bc63b49ed042a0c3f6f28016a3a98fe60da1631dbef5134fc16addfa |
File details
Details for the file structlog_sentry_logger-0.17.0-cp37-cp37m-macosx_10_16_x86_64.whl
.
File metadata
- Download URL: structlog_sentry_logger-0.17.0-cp37-cp37m-macosx_10_16_x86_64.whl
- Upload date:
- Size: 105.0 kB
- Tags: CPython 3.7m, macOS 10.16+ 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
Algorithm | Hash digest | |
---|---|---|
SHA256 | 57343587432e7262c29ed800fd8a571d93af155ecaf6b6abbaa7cde1261a1352 |
|
MD5 | 8778a510ac87b03ba337a140902aee2c |
|
BLAKE2b-256 | baacf6c99a7f3d6cb4ef1599a4416d315fddcdb8bdd982a19d900beab065c1d2 |