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

DEBUG

10

Detailed diagnostic information

INFO

20

General operational messages

WARNING

30

Something unexpected but not fatal

SUCCESS

31

Custom: operation completed successfully

FAIL

35

Custom: operation failed (non-fatal)

ERROR

40

Serious problem

CRITICAL

50

Program may not continue

Warning Categories

  • SciTeXWarning – Base warning class

  • UnitWarning – SI unit convention issues

  • StyleWarning – Formatting issues

  • SciTeXDeprecationWarning – Deprecated features

  • PerformanceWarning – Performance issues

  • DataLossWarning – Potential data loss

Exception Hierarchy

All inherit from SciTeXError:

  • I/O: IOError, FileFormatError, SaveError, LoadError

  • Config: ConfigurationError, ConfigFileNotFoundError, ConfigKeyError

  • Path: PathError, InvalidPathError, PathNotFoundError

  • Data: DataError, ShapeError, DTypeError

  • Plotting: PlottingError, FigureNotFoundError, AxisError

  • Stats: StatsError, TestError

  • Scholar: ScholarError, SearchError, PDFDownloadError, DOIResolutionError

  • NN: NNError, ModelError

  • Template: 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 logging

  • enable_console (bool) – Whether to enable console logging

  • capture_prints (bool) – Whether to capture print() statements to logs

  • max_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.set_level(level)[source]

Set global log level for all SciTeX loggers.

scitex.logging.get_level()[source]

Get current global log level.

scitex.logging.enable_file_logging(enabled=True)[source]

Enable or disable file logging globally.

scitex.logging.is_file_logging_enabled()[source]

Check if file logging is enabled.

scitex.logging.get_log_path()[source]

Get the current log file path.

class scitex.logging.Tee(stream, log_path, verbose=True)[source]
write(data)[source]
Return type:

None

flush()[source]
Return type:

None

isatty()[source]
Return type:

bool

fileno()[source]
Return type:

int

property buffer
close()[source]

Explicitly close the log file.

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
Parameters:
  • sys_module (module) – System module containing stdout and stderr

  • sdir (str, optional) – Directory for log files

  • verbose (bool, default=True) – Whether to print log file locations

Returns:

Wrapped stdout and stderr objects

Return type:

tuple[Any, Any]

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:
  • file_path (Union[str, Path]) – Path to log file

  • level (int) – Logging level for this handler (default: DEBUG)

  • mode (str) – File mode (‘w’ for overwrite, ‘a’ for append)

  • formatter (Optional[Formatter]) – Custom formatter (default: SciTeXFileFormatter)

Yields:

The file handler (can be ignored)

exception scitex.logging.SciTeXWarning[source]

Base warning class for all SciTeX warnings.

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⁻¹)

exception scitex.logging.StyleWarning[source]

Warning for style/formatting issues.

exception scitex.logging.SciTeXDeprecationWarning[source]

Warning for deprecated SciTeX features.

exception scitex.logging.PerformanceWarning[source]

Warning for performance issues.

exception scitex.logging.DataLossWarning[source]

Warning for potential data loss.

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:
  • message (str) – Warning message

  • category (type) – Warning category (default: SciTeXWarning)

  • stacklevel (int) – Stack level for source location (default: 2 = caller)

Return type:

None

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:

None

Examples

>>> import scitex.logging as logging
>>> from scitex.logging import UnitWarning
>>> logging.filterwarnings("ignore", category=UnitWarning)
scitex.logging.resetwarnings()[source]

Reset all warning filters to default behavior.

Return type:

None

scitex.logging.warn_deprecated(old_name, new_name, version=None)[source]

Issue a deprecation warning.

Return type:

None

scitex.logging.warn_performance(operation, suggestion)[source]

Issue a performance warning.

Return type:

None

scitex.logging.warn_data_loss(operation, detail)[source]

Issue a data loss warning.

Return type:

None

exception scitex.logging.SciTeXError(message, context=None, suggestion=None)[source]

Base Exception class for all SciTeX errors.

__init__(message, context=None, suggestion=None)[source]

Initialize SciTeX error with detailed information.

Parameters:
  • message (str) – The error message

  • context (dict, optional) – Additional context information (e.g., file paths, variable values)

  • suggestion (str, optional) – Suggested fix or action

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.SaveError(filepath, reason)[source]

Raised when saving data fails.

exception scitex.logging.LoadError(filepath, reason)[source]

Raised when loading data fails.

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.PDFDownloadError(url, reason)[source]

Raised when PDF download fails.

exception scitex.logging.DOIResolutionError(doi, reason)[source]

Raised when DOI resolution 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.

exception scitex.logging.TestError(test_name, reason)[source]

Raised when statistical tests fail.

scitex.logging.check_path(path)[source]

Validate a path according to SciTeX conventions.

Return type:

None

scitex.logging.check_file_exists(filepath)[source]

Check if a file exists.

Return type:

None

scitex.logging.check_shape_compatibility(shape1, shape2, operation)[source]

Check if two shapes are compatible for an operation.

Return type:

None