Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python logging libraries record events from a running program, such as requests, warnings, and errors. Most of them extend the standard logging module that ships with Python. These libraries give developers the records they search when a service fails in production.
Popularity
Rich has the most monthly downloads in this comparison, at 579.9M, a count that covers the whole Rich package rather than its logging handler alone.
Rich renders formatted text, tables, progress bars, and syntax highlighting in the terminal, and its RichHandler class is a handler for the standard logging module. The handler formats and colorizes each record that logging emits. Passing it in the handlers list of logging.basicConfig changes the output without touching any log call. With rich_tracebacks set, exceptions go through Rich's traceback formatter, which shows more context than the built-in one, and tracebacks_suppress hides frames from frameworks such as Click.
Downloads / mo
579.9M
Stars
57.8K
Last release
15.0.0
License
MIT
Strengths
Keeps standard logging APIs.Attach RichHandler to the standard logging configuration.
Formats detailed exception tracebacks.Enable rich_tracebacks to render exceptions through Rich’s traceback formatter.
Limitations
Markup is disabled by default.Enable markup only when log messages intentionally contain Rich markup.
The OpenTelemetry SDK is the Python implementation of OpenTelemetry for traces, metrics, and logs. For logs, LoggingHandler attaches to the standard logging module and writes each record in OTLP, the OpenTelemetry protocol. Processors such as BatchLogRecordProcessor pass records to an exporter. ConsoleLogRecordExporter prints them for debugging, while sending them to a collector over HTTP or gRPC takes a separate exporter package, such as opentelemetry-exporter-otlp-proto-http.
Downloads / mo
345.7M
Last release
1.45.2
License
Apache-2.0
Strengths
Writes OTLP records.LoggingHandler sends standard logging records to a network destination or a file in OTLP format.
def setup_events(
application_name,
environment,
event_logger,
otlp_endpoint,
otlp_headers,
disable_batch,
):
"""Setup OpenTelemetry events with the given configuration.
Args:
application_name: Name of the application
environment: Deployment environment
event_logger: Optional pre-configured Logger instance
otlp_endpoint: Optional OTLP endpoint for exporter
otlp_headers: Optional headers for OTLP exporter
Returns:
Logger: The configured OTel Logger for emitting events as LogRecords
"""
# If an external events_logger is provided, return it immediately. if event_logger:
return event_logger
# Proceed with setting up a new events or configuration only if EVENTS_SET is False. global EVENTS_SET
try:
if not EVENTS_SET:
existing_provider = _logs.get_logger_provider()
if isinstance(existing_provider, SDKLoggerProvider):
logger.info("Detected existing LoggerProvider, reusing it")
else:
# No SDK provider configured yet -- create one. resource = Resource.create(
attributes={
SERVICE_NAME: application_name,
DEPLOYMENT_ENVIRONMENT: environment,
TELEMETRY_SDK_NAME: "openlit",
}
)
logger_provider = SDKLoggerProvider(resource=resource)
if otlp_endpoint is not None:
os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = otlp_endpoint
if otlp_headers is not None:
if isinstance(otlp_headers, dict):
headers_str = ",".join(
f"{key}={value}" for key, value in otlp_headers.items()
)
else:
headers_str = otlp_headers
os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = headers_str
exporters_config = parse_exporters("OTEL_LOGS_EXPORTER")
processors_added = False
if exporters_config is not None:
for exporter_name in exporters_config:
if exporter_name == "otlp":
event_exporter = OTLPLogExporter()
log_processor = (
BatchLogRecordProcessor(event_exporter)
if not disable_batch
else SimpleLogRecordProcessor(event_exporter)
)
logger_provider.add_log_record_processor(log_processor)
processors_added = True
elif exporter_name == "console":
event_exporter = ConsoleLogRecordExporter()
log_processor = SimpleLogRecordProcessor(event_exporter)
logger_provider.add_log_record_processor(log_processor)
processors_added = True
elif exporter_name == "none":
continue
else:
logger.warning("Unknown log exporter: %s", exporter_name)
if not processors_added:
logger.warning(
"OTEL_LOGS_EXPORTER is set but no valid exporters "
"configured. Log export is disabled. "
"Valid exporters: otlp, console"
)
else:
if os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT"):
event_exporter = OTLPLogExporter()
# pylint: disable=line-too-long log_processor = (
BatchLogRecordProcessor(event_exporter)
if not disable_batch
else SimpleLogRecordProcessor(event_exporter)
)
else:
event_exporter = ConsoleLogRecordExporter()
log_processor = SimpleLogRecordProcessor(event_exporter)
logger_provider.add_log_record_processor(log_processor)
_logs.set_logger_provider(logger_provider)
EVENTS_SET = True
return _logs.get_logger(__name__)
except Exception as e:
logger.error("Failed to setup OpenTelemetry events: %s", e, exc_info=True)
return None
Sentry SDK
The Sentry SDK reports errors and logs from a Python application to Sentry, a hosted error tracking service. After sentry_sdk.init runs with a project DSN, the sentry_sdk.logger namespace sends structured messages whose placeholders, such as {user_id}, become searchable attributes. The LoggingIntegration captures records from the standard logging module as Sentry logs and breadcrumbs. Records at error level and above can also become error events through the event_level option.
Downloads / mo
157.9M
Last release
2.75.0
License
MIT
Strengths
Searchable by attribute.Logs appear beside related errors and can be searched by text or by individual attributes.
Limitations
Recent SDK required.Logs need Sentry Python SDK 2.35.0 or later.
def setup_error_handling(version: str) -> None:
settings = ErrorHandlingSettings()
if settings.sentry_url:
# Disabled everywhere for now. Let's have less knobs to tweak. # Either we use with with sentry or we don't. # enabled_integrations: list[Any] = [ # LoggingIntegration(level=logging.CRITICAL, event_level=logging.CRITICAL) # ] sentry_sdk.init(
release=version,
environment=settings.environment,
dsn=settings.sentry_url,
integrations=[
LoggingIntegration(
level=None,
),
],
)
sentry_sdk.set_tag("zone", settings.zone)
structlog
structlog builds each log entry as a dictionary of key and value pairs, called an event. A configured chain of processors adds fields such as the level and a timestamp, then a renderer turns the event into JSON, logfmt, or colored console text. structlog.get_logger works with no setup and prints to standard output. Values bound once with bind or through context variables appear on every later event. The final output can also go through the standard logging module.
Downloads / mo
128.0M
Stars
5.0K
Last release
26.1.0
License
MIT OR Apache-2.0
Strengths
Processes structured event dictionaries.Choose processors and a renderer for the desired event output.
Binds request-local log context.Merge context variables into events and bind request fields once.
Limitations
Request context needs explicit reset.Clear context variables at request entry before binding the next request’s fields.
async def async_streaming_content_wrapper(
streaming_content: AsyncIterator[bytes], context: Any
) -> AsyncGenerator[bytes, Any]:
with structlog.contextvars.bound_contextvars(**context):
logger.log(app_settings.REQUEST_STARTED_LOG_LEVEL, "streaming_started")
try:
async for chunk in streaming_content:
yield chunk
except asyncio.CancelledError:
logger.log(app_settings.REQUEST_CANCELLED_LOG_LEVEL, "streaming_cancelled")
raise
except Exception:
logger.exception("streaming_failed")
raise
else:
logger.log(app_settings.STATUS_2XX_LOG_LEVEL, "streaming_finished")
Python JSON Logger
Python JSON Logger supplies formatter classes for the standard logging module that encode each record as JSON. JsonFormatter attaches to any existing handler through setFormatter. The fmt argument sets the fields and accepts the same format styles as logging. Messages can also be dictionaries, and values passed through extra become fields of the JSON object.
Downloads / mo
106.9M
Last release
4.2.0
License
BSD-2-Clause
Strengths
Plugs into existing handlers.The formatter attaches to a standard logging handler, and existing log calls stay unchanged.
def add_fields(
self,
log_record: dict[str, object],
record: logging.LogRecord,
message_dict: dict[str, object],
) -> None:
super().add_fields(log_record, record, message_dict)
if self._refkey and hasattr(record, "k8s_ref"):
ref = getattr(record, "k8s_ref")
log_record[self._refkey] = ref
if "severity" not in log_record:
log_record["severity"] = (
"debug"
if record.levelno <= logging.DEBUG
else "info"
if record.levelno <= logging.INFO
else "warn"
if record.levelno <= logging.WARNING
else "error"
if record.levelno <= logging.ERROR
else "fatal"
)
Loguru
Loguru replaces the setup of the standard logging module with one preconfigured logger that writes to standard error on import. The add method registers each destination, called a sink, which can be a file path, a function, a file object, or a standard logging handler. File sinks take rotation, retention, and compression settings. With serialize set, each record reaches the sink as a JSON string, and bind attaches fields to later messages.
Downloads / mo
85.4M
Stars
24.2K
Last release
0.8.0
License
MIT
Strengths
Manages rotating log sinks.Configure file rotation, retention, and compression on the logger.
Serializes structured log events.Enable serialize to send JSON-formatted records to the configured sink.
Limitations
Diagnostics include variable values.Set diagnose=False when production tracebacks must omit local variable values.
def define_log_level(print_level="INFO", logfile_level="DEBUG", name: str = None):
"""Adjust the log level to above level"""
global _print_level
_print_level = print_level
current_date = datetime.now()
formatted_date = current_date.strftime("%Y%m%d")
log_name = f"{name}_{formatted_date}" if name else formatted_date # name a log with prefix name
_logger.remove()
_logger.add(sys.stderr, level=print_level)
_logger.add(METAGPT_ROOT / f"logs/{log_name}.txt", level=logfile_level)
return _logger
colorlog
colorlog adds color to the output of the standard logging module. Its ColoredFormatter class extends logging.Formatter and replaces the formatter on any existing handler. A log_colors mapping assigns a color to each level name, and secondary_log_colors colors other parts of the format string. On Windows, colorama installs as a dependency so that the colors display.
Downloads / mo
48.6M
Last release
6.12.0
License
MIT
Strengths
Extends logging.Formatter.ColoredFormatter replaces the formatter on any standard logging handler.
Limitations
Color off outside terminals.Colors turn off on output that is not a terminal unless force_color is set.
def create_default_formatter() -> logging.Formatter:
"""Create a default formatter of log messages.
This function is not supposed to be directly accessed by library users.
"""
header = "[%(levelname)1.1s %(asctime)s]"
message = "%(message)s"
return colorlog.TTYColoredFormatter(
f"%(log_color)s{header}%(reset)s {message}",
stream=sys.stderr,
)
coloredlogs
coloredlogs colors terminal output from the standard logging module with ANSI escape sequences. One call to coloredlogs.install adds a colored handler to the root logger. The ColoredFormatter class inherits from logging.Formatter for setups that attach their own handlers. On Windows, the package tries native ANSI support first and falls back on colorama when it is installed.
Downloads / mo
40.2M
Last release
15.0.1
License
MIT
Strengths
One-call setup.coloredlogs.install adds a colored handler to the root logger, which also colors messages from other libraries.
def set_logger_configuration(is_debug=False, quiet=False, output_file_path=None):
"""
Configure whether full stacktraces should be dumped in the console output
"""
# set debug level global verbose_exceptions
verbose_exceptions = is_debug
# if "quiet" is set, don't output anything if quiet:
coloredlogs.install(level='ERROR', logger=logger)
else:
coloredlogs.install(level='DEBUG' if is_debug else 'INFO', logger=logger)
if output_file_path:
# For some reason, hostname information is not passed to the FileHandler # Add it using a filter class HostnameFilter(logging.Filter):
hostname = platform.node()
def filter(self, record):
record.hostname = HostnameFilter.hostname
return True
# create file handler which logs messages fh = logging.FileHandler(output_file_path, 'w+')
# Add filter to add hostname information fh.addFilter(HostnameFilter())
# create formatter and add it to the handlers formatter = logging.Formatter(fmt='%(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
fh.setFormatter(formatter)
# add the handlers to the logger logger.addHandler(fh)
FAQ
The standard logging module ships with Python, and most libraries here plug into it. Rich, colorlog, and coloredlogs add color, and Python JSON Logger adds JSON, with no change to existing log calls. Loguru and structlog replace the setup with their own logger API.
Loguru provides one preconfigured logger, and its add method registers each output, called a sink, in place of the handlers, formatters, and filters that logging uses. File sinks take rotation, retention, and compression settings directly.
structlog builds each event as a dictionary that passes through a chain of processors, then renders JSON, logfmt, or console output, or hands the event to logging. Loguru keeps a single logger that sends message records to sinks, and writes JSON when a sink sets serialize.
Python JSON Logger adds a JSON formatter to existing logging handlers. structlog renders JSON with JSONRenderer, and Loguru writes JSON when a sink sets serialize.
Pass RichHandler() in the handlers list of logging.basicConfig. Setting rich_tracebacks on the handler formats exceptions with Rich's traceback renderer.
The standard library includes RotatingFileHandler for size and TimedRotatingFileHandler for time. Loguru takes a rotation setting on each file sink.
For coding agents
Found your logging library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.