Logging Module (stx.logging)
Unified logging with file/console output, custom warnings, exception hierarchy, and stream redirection.
Quick Reference
import scitex as stx
from scitex import logging
# Get a logger
logger = logging.getLogger(__name__)
logger.info("Processing data")
logger.success("Analysis complete") # Custom level (31)
logger.fail("Model diverged") # Custom level (35)
# Configure globally
logging.configure(level="DEBUG", log_file="./run.log")
logging.set_level("WARNING")
# Temporary file logging
with logging.log_to_file("analysis.log"):
logger.info("This goes to both console and file")
# Warnings
logging.warn("Large dataset", category=logging.PerformanceWarning)
logging.warn_deprecated("old_func", "new_func", version="3.0")
logging.filterwarnings("ignore", category=logging.UnitWarning)
Log Levels
Level |
Value |
Description |
|---|---|---|
|
10 |
Detailed diagnostic information |
|
20 |
General operational messages |
|
30 |
Something unexpected but not fatal |
|
31 |
Custom: operation completed successfully |
|
35 |
Custom: operation failed (non-fatal) |
|
40 |
Serious problem |
|
50 |
Program may not continue |
Warning Categories
SciTeXWarning– Base warning classUnitWarning– SI unit convention issuesStyleWarning– Formatting issuesSciTeXDeprecationWarning– Deprecated featuresPerformanceWarning– Performance issuesDataLossWarning– Potential data loss
Exception Hierarchy
All inherit from SciTeXError:
I/O:
IOError,FileFormatError,SaveError,LoadErrorConfig:
ConfigurationError,ConfigFileNotFoundError,ConfigKeyErrorPath:
PathError,InvalidPathError,PathNotFoundErrorData:
DataError,ShapeError,DTypeErrorPlotting:
PlottingError,FigureNotFoundError,AxisErrorStats:
StatsError,TestErrorScholar:
ScholarError,SearchError,PDFDownloadError,DOIResolutionErrorNN:
NNError,ModelErrorTemplate:
TemplateError,TemplateViolationError
Stream Redirection
from scitex.logging import tee
import sys
# Redirect stdout/stderr to log files
sys.stdout, sys.stderr = tee(sys, sdir="./output")
The @stx.session decorator handles this automatically.
API Reference
- scitex.logging.getLogger(name=None)[source]
Return a logger with the specified name, creating it if necessary.
If no name is specified, return the root logger.
- scitex.logging.configure(level='info', log_file=None, enable_file=True, enable_console=True, capture_prints=True, max_file_size=10485760, backup_count=5)[source]
Configure logging for SciTeX with both console and file output.
- Parameters:
level (
Union[str,int]) – Log level (string or logging constant)log_file (
Optional[str]) – Path to log file (default: ~/.scitex/logs/scitex-YYYY-MM-DD.log)enable_file (
bool) – Whether to enable file loggingenable_console (
bool) – Whether to enable console loggingcapture_prints (
bool) – Whether to capture print() statements to logsmax_file_size (
int) – Maximum size of log file before rotation (default: 10MB)backup_count (
int) – Number of backup files to keep (default: 5)
- scitex.logging.tee(sys, sdir=None, verbose=True)[source]
Redirects stdout and stderr to both console and log files.
Example
>>> import sys >>> sys.stdout, sys.stderr = tee(sys) >>> print("abc") # stdout >>> print(1 / 0) # stderr
- scitex.logging.log_to_file(file_path, level=10, mode='w', formatter=None)[source]
Context manager to temporarily log all output to a specific file.
- Usage:
import scitex_logging as logging logger = logging.getLogger(__name__)
- with logging.log_to_file(“/path/to/log.txt”):
logger.info(“This goes to both console and /path/to/log.txt”) logger.success(“This too!”)
- Parameters:
- Yields:
The file handler (can be ignored)
- exception scitex.logging.UnitWarning[source]
Warning for axis label unit issues (educational for SI conventions).
Raised when: - Axis labels are missing units - Units use parentheses instead of brackets (SI prefers []) - Units use division instead of negative exponents (m/s vs m·s⁻¹)
- scitex.logging.warn(message, category=<class 'scitex_logging._warnings.SciTeXWarning'>, stacklevel=2)[source]
Emit a warning (like warnings.warn but integrated with scitex.logging).
- Parameters:
- Return type:
Examples
>>> import scitex.logging as logging >>> from scitex.logging import UnitWarning >>> logging.warn("X axis has no units", UnitWarning)
- scitex.logging.filterwarnings(action, category=<class 'scitex_logging._warnings.SciTeXWarning'>, message=None)[source]
Control warning behavior (like warnings.filterwarnings).
- Parameters:
action (str) – One of: - “ignore”: Never show this warning - “error”: Raise as exception - “always”: Always show - “default”: Show first occurrence per location - “once”: Show only once total - “module”: Show once per module
category (type) – Warning category (default: SciTeXWarning = all)
message (str, optional) – Regex pattern to match warning message (not implemented yet)
- Return type:
Examples
>>> import scitex.logging as logging >>> from scitex.logging import UnitWarning >>> logging.filterwarnings("ignore", category=UnitWarning)
- scitex.logging.warn_deprecated(old_name, new_name, version=None)[source]
Issue a deprecation warning.
- Return type:
- scitex.logging.warn_performance(operation, suggestion)[source]
Issue a performance warning.
- Return type:
- exception scitex.logging.SciTeXError(message, context=None, suggestion=None)[source]
Base Exception class for all SciTeX errors.
- exception scitex.logging.ConfigurationError(message, context=None, suggestion=None)[source]
Raised when there are issues with SciTeX configuration.
- exception scitex.logging.ConfigFileNotFoundError(filepath)[source]
Raised when a required configuration file is not found.
- exception scitex.logging.ConfigKeyError(key, available_keys=None)[source]
Raised when a required configuration key is missing.
- exception scitex.logging.IOError(message, context=None, suggestion=None)[source]
Base class for input/output related errors.
- exception scitex.logging.FileFormatError(filepath, expected_format=None, actual_format=None)[source]
Raised when file format is not supported or incorrect.
- exception scitex.logging.ScholarError(message, context=None, suggestion=None)[source]
Base class for scholar module errors.
- exception scitex.logging.SearchError(query, source, reason)[source]
Raised when paper search fails.
- exception scitex.logging.EnrichmentError(paper_title, reason)[source]
Raised when paper enrichment fails.
- exception scitex.logging.PDFExtractionError(filepath, reason)[source]
Raised when PDF text extraction fails.
- exception scitex.logging.BibTeXEnrichmentError(bibtex_file, reason)[source]
Raised when BibTeX enrichment fails.
- exception scitex.logging.TranslatorError(translator_name, reason)[source]
Raised when Zotero translator operations fail.
- exception scitex.logging.AuthenticationError(provider, reason='')[source]
Raised when authentication fails.
- exception scitex.logging.PlottingError(message, context=None, suggestion=None)[source]
Base class for plotting-related errors.
- exception scitex.logging.FigureNotFoundError(fig_id)[source]
Raised when attempting to operate on a non-existent figure.
- exception scitex.logging.AxisError(message, axis_info=None)[source]
Raised when there are issues with plot axes.
- exception scitex.logging.DataError(message, context=None, suggestion=None)[source]
Base class for data processing errors.
- exception scitex.logging.ShapeError(expected_shape, actual_shape, operation)[source]
Raised when data shapes are incompatible.
- exception scitex.logging.DTypeError(expected_dtype, actual_dtype, operation)[source]
Raised when data types are incompatible.
- exception scitex.logging.PathError(message, context=None, suggestion=None)[source]
Base class for path-related errors.
- exception scitex.logging.InvalidPathError(path, reason)[source]
Raised when a path is invalid or doesn’t follow SciTeX conventions.
- exception scitex.logging.PathNotFoundError(path)[source]
Raised when a required path doesn’t exist.
- exception scitex.logging.TemplateError(message, context=None, suggestion=None)[source]
Base class for template-related errors.
- exception scitex.logging.TemplateViolationError(filepath, violation)[source]
Raised when SciTeX template is not followed.
- exception scitex.logging.NNError(message, context=None, suggestion=None)[source]
Base class for neural network module errors.
- exception scitex.logging.ModelError(model_name, reason)[source]
Raised when there are issues with neural network models.
- exception scitex.logging.StatsError(message, context=None, suggestion=None)[source]
Base class for statistics module errors.