Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
structlog-sentry-logger
Advanced tools
Log without the setup via a pre-configured structlog logger with optional Sentry integration
Documentation: https://structlog-sentry-logger.readthedocs.io
Source Code: https://github.com/TeoZosa/structlog-sentry-logger
A multi-purpose, pre-configured,
performance-optimized structlog
logger with
(optional) Sentry integration
via structlog-sentry
.
The pre-configured options include:
YYYY-MM-DDTHH:MM:SS.ffffffZ
).py
files), relative to your project directory.
docs_src/sentry_integration.py
is
named docs_src.sentry_integration
:fire: Tip
For easier at-a-glance analysis, you can also sort log fields by key by exporting theSTRUCTLOG_SENTRY_LOGGER_KEY_SORTING_ON
environment variable. Note, however, that this has a substantial (~1.6x
) performance penalty.
- See
orjson
'sOPT_SORT_KEYS
documentation for more information.
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 library1; 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 benchmarksstructlog
: Performance" for
salient performance-related configurations.Automatically add much richer context to your Sentry reports.
structlog-sentry-logger
log level is error
or higher.
logger.error("")
, logger.exception("")
structlog-sentry
for more
details.Table of Contents
pip install structlog-sentry-logger
Optionally, install Sentry integration with
pip install "structlog-sentry-logger[sentry]"
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"
}
If you installed the library with the optional Sentry integration you can 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
file2:
echo "STRUCTLOG_SENTRY_LOGGER_CLOUD_SENTRY_INTEGRATION_MODE_ON=" >> .env
:memo: ️Note
By default, only logs at error-level or above are sent to Sentry. If you want to set a different minimum log level, you can specify a valid Python log level via theSTRUCTLOG_SENTRY_LOGGER_SENTRY_LOG_LEVEL
environment variable.For example, to send all logs at warning-level or above to Sentry you would simply set
STRUCTLOG_SENTRY_LOGGER_SENTRY_LOG_LEVEL=WARNING
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!
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
file2.
: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.
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
file2:
echo "STRUCTLOG_SENTRY_LOGGER_LOCAL_DEVELOPMENT_LOGGING_MODE_ON=" >> .env
In doing so, with our previous exception handling example we would get:
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.
structlog
: Structured Logging for PythonSentry
: Monitor and fix crashes in realtimestructlog-sentry
: Provides the structlog
integration for SentryFor 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.
Make sure you have Python 3.9+ 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.
The projects's build.py file specifies which modules to package.
For manual per-module compilation, see: Mypyc Documentation: Getting started - Compiling and running
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.
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.
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.
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.
Structlog-Sentry-Logger is licensed under the Apache License, Version 2.0. See LICENSE for the full license text.
This project was generated from
@TeoZosa
's
cookiecutter-cruft-poetry-tox-pre-commit-ci-cd
template.
Source: Choosing a faster JSON library for Python: Benchmarking ↩
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: ↩ ↩2 ↩3
FAQs
Log without the setup via a pre-configured structlog logger with optional Sentry integration
We found that structlog-sentry-logger demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.