backtrader.utils.log_message module¶
Log Message Module - Logging utilities for backtrader.
This module is the single logging entry point for the whole framework.
It builds on Python’s standard logging under the hood (no third-party
spdlog dependency) but framework and user code should go through the
helpers exposed here rather than importing logging directly:
get_logger()— get a logger under thebacktradernamespace.configure_logging()— opt-in handler/level setup (stderr + optional rotating file). Until this is called, backtrader emits nothing (aNullHandleris installed on the rootbacktraderlogger).set_level()/reset_logging()— runtime level control / test reset.SpdLogManager— legacy per-file logger factory (daily rotation), kept for backward compatibility and reused internally by the strategy TradeLogger path.
See docs/LOGGING_GUIDELINES.md for level-usage conventions.
Example
>>> from backtrader.utils.log_message import get_logger, configure_logging
>>> configure_logging(level="INFO", log_file="run.log")
>>> logger = get_logger(__name__)
>>> logger.info("Strategy started")
# Legacy factory (still supported): >>> log_manager = SpdLogManager(file_name=”mylog.log”) >>> logger = log_manager.create_logger()
- backtrader.utils.log_message.get_logger(name=None)[source]¶
Return a logger under the
backtradernamespace.- Parameters:
name – Usually
__name__of the calling module. If it already starts with"backtrader"it is used as-is; otherwise it is nested under thebacktraderroot (e.g."mystuff"->"backtrader.mystuff").Nonereturns the root logger.- Returns:
A logger in the backtrader hierarchy.
- Return type:
- backtrader.utils.log_message.configure_logging(level='INFO', log_file=None, fmt=None, datefmt=None, console=True, max_bytes=10485760, backup_count=5, propagate=False, *, log_dir=None, script_name=None, backend='auto', retention_days=30, _debug_scopes=())[source]¶
Configure the
backtraderlogger hierarchy (opt-in).Backtrader emits nothing until you call this. It configures only the
backtraderlogger (never the root logger), so it will not clobber a host application’s logging. Calling it again replaces backtrader-managed handlers (idempotent) while leaving host-added handlers untouched.- Parameters:
level – Level as int (
logging.INFO) or name ("INFO").log_file – If given, also write to this single file via a
RotatingFileHandler. Mutually exclusive withlog_dir.log_dir – If given, enable the iteration-29 split-file layout
log_dir/<script>/<YYYY_MM_DD>/{error,warning,info}.log(plusdebug.logwhenlevel=DEBUG).<script>comes fromscript_nameor auto-detection ofsys.argv[0].script_name – Directory name under
log_dir.Noneauto-detects fromsys.argv[0](xxx/run.py->xxx_run).backend –
"auto"(default; prefer the optionalspdlogpackage, fall back to stdlib with one diagnostic),"spdlog"(raiseImportErrorif unavailable) or"stdlib".retention_days – Date directories older than this many days under the script’s own directory are removed at configure/rollover time.
fmt – Message format. Defaults to
DEFAULT_FORMAT.datefmt – Date format. Defaults to
DEFAULT_DATEFMT.console – Whether to add a stderr
StreamHandler.max_bytes – Rotating file handler size before rollover (
log_file).backup_count – Number of rotated backups to keep (
log_file).propagate – Whether the backtrader logger propagates to the root logger (default
False).
- Returns:
The configured
backtraderroot logger.- Return type:
- backtrader.utils.log_message.set_level(level, name=None)[source]¶
Set the level of a backtrader logger at runtime.
- Parameters:
level – Level as int or name.
name – Sub-logger name (
__name__-style).Nonetargets the root. A root-level update with active split-file logging atomically rebuilds its handler matrix, so a DEBUG transition createsdebug.logand is inherited by optimization workers. A named DEBUG update creates a DEBUG sink restricted to that logger’s hierarchy, leaving unrelated loggers at the configured root level.
- backtrader.utils.log_message.reset_logging()[source]¶
Remove backtrader-managed handlers and restore the default NullHandler.
Mainly useful in tests to return to the pristine, no-output state. Also flushes and releases any spdlog-side resources held by managed handlers.
- class backtrader.utils.log_message.SpdLogManager[source]¶
Bases:
objectLogger factory using the Python standard
loggingmodule.Creates loggers with daily file rotation and optional console output. API is kept compatible with the previous spdlog-based implementation.
- file_name¶
Name of the log file.
- logger_name¶
Name for the logger.
- rotation_hour¶
Hour of day for log rotation (0-23).
- rotation_minute¶
Minute of hour for log rotation (0-59).
- print_info¶
Whether to also print to console.
- __init__(file_name='log_strategy_info.log', logger_name='hello', rotation_hour=0, rotation_minute=0, print_info=False)[source]¶
Initialize the SpdLogManager.
- Parameters:
file_name – Name of the output log file.
logger_name – Name for the logger.
rotation_hour – Hour (0-23) to rotate log files daily.
rotation_minute – Minute (0-59) to rotate log files.
print_info – Whether to also output to console.
- class backtrader.utils.log_message.SpdlogHandler[source]¶
Bases:
_NonFatalHandlerMixin,Handlerspdlog-backend handler mirroring
_DailyLevelFileHandler.The framework layer owns the layout: the Python formatter renders the full line and spdlog writes it with pattern
%v(message only), so line format matches the stdlib backend. Date rollover drops and reopens the underlying spdlog logger on the new path.- emit(record)[source]¶
Do whatever it takes to actually log the specified logging record.
This version is intended to be implemented by subclasses and so raises a NotImplementedError.
- backtrader.utils.log_message.flush_all()[source]¶
Flush every managed handler (use before reading log files in tests).
- backtrader.utils.log_message.set_throttle(enabled)[source]¶
Enable/disable storm suppression (diagnostic mode: disable).
- backtrader.utils.log_message.throttled_error(logger, key, msg, *args, every=100, window=60.0, exc_info=True)[source]¶
logger.error with storm suppression: first full, repeats summarized.