# logger URL: /api/utils/logger/ Section: utils -------------------------------------------------------------------------------- logger - Bengal window.BENGAL_THEME_DEFAULTS = { appearance: 'dark', palette: 'snow-lynx' }; // Progressive Enhancement System Configuration window.Bengal = window.Bengal || {}; window.Bengal.enhanceBaseUrl = '/bengal/assets/js/enhancements'; window.Bengal.watchDom = true; window.Bengal.debug = false; (function () { try { var defaults = window.BENGAL_THEME_DEFAULTS || { appearance: 'system', palette: '' }; var defaultAppearance = defaults.appearance; if (defaultAppearance === 'system') { defaultAppearance = (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light'; } var storedTheme = localStorage.getItem('bengal-theme'); var storedPalette = localStorage.getItem('bengal-palette'); var theme = storedTheme ? (storedTheme === 'system' ? defaultAppearance : storedTheme) : defaultAppearance; var palette = storedPalette ?? defaults.palette; document.documentElement.setAttribute('data-theme', theme); if (palette) { document.documentElement.setAttribute('data-palette', palette); } } catch (e) { document.documentElement.setAttribute('data-theme', 'light'); } })(); Skip to main content Magnifying Glass ESC Recent Clear Magnifying Glass No results for "" Try different keywords or check your spelling Start typing to search... ↑↓ Navigate ↵ Open ESC Close Powered by Lunr ᓚᘏᗢ Documentation Info About Arrow Clockwise Get Started Note Tutorials File Text Content Palette Theming Settings Building Starburst Extending Bookmark Reference Learning Tracks Releases Dev GitHub API Reference bengal CLI Magnifying Glass Search ⌘K Palette Appearance Chevron Down Mode Monitor System Sun Light Moon Dark Palette Snow Lynx Brown Bengal Silver Bengal Charcoal Bengal Blue Bengal List ᓚᘏᗢ Magnifying Glass Search X Close Documentation Info About Arrow Clockwise Get Started Note Tutorials File Text Content Palette Theming Settings Building Starburst Extending Bookmark Reference Learning Tracks Releases Dev GitHub API Reference bengal CLI Palette Appearance Chevron Down Mode Monitor System Sun Light Moon Dark Palette Snow Lynx Brown Bengal Silver Bengal Charcoal Bengal Blue Bengal API Reference __main__ bengal Caret Right Folder Analysis community_detection graph_analysis graph_reporting graph_visualizer knowledge_graph link_suggestions link_types page_rank path_analysis performance_advisor results Caret Right Folder Assets manifest pipeline Caret Right Folder Autodoc base config docstring_parser utils virtual_orchestrator Caret Right Folder Extractors cli openapi python Caret Right Folder Models cli common openapi python Caret Right Folder Cache asset_dependency_map cache_store cacheable compression dependency_tracker page_discovery_cache query_index query_index_registry taxonomy_index utils Caret Right Folder Build Cache autodoc_tracking core file_tracking fingerprint parsed_content_cache rendered_output_cache taxonomy_index_mixin validation_cache Caret Right Folder Indexes author_index category_index date_range_index section_index Caret Right Folder Cli __main__ base site_templates utils Caret Right Folder Commands assets build clean collections config debug explain fix health init perf project serve site skeleton sources theme utils validate Caret Right Folder Graph __main__ bridges communities orphans pagerank report suggest Caret Right Folder New config presets scaffolds site wizard Caret Right Folder Helpers cli_app_loader cli_output config_validation error_handling menu_config metadata progress site_loader traceback validation Caret Right Folder Skeleton hydrator schema Caret Right Folder Templates base registry Caret Right Folder Blog template Caret Right Folder Changelog template Caret Right Folder Default template Caret Right Folder Docs template Caret Right Folder Landing template Caret Right Folder Portfolio template Caret Right Folder Resume template Caret Right Folder Collections errors loader schemas validator Caret Right Folder Config defaults deprecation directory_loader env_overrides environment feature_mappings hash loader merge origin_tracker validators Caret Right Folder Content Layer entry loaders manager source Caret Right Folder Sources github local notion rest Caret Right Folder Content Types base registry strategies Caret Right Folder Core build_context cascade_engine menu section theme Caret Right Folder Asset asset_core css_transforms Caret Right Folder Page computed content metadata navigation operations page_core proxy relationships utils Caret Right Folder Site core data discovery factories page_caches properties section_registry theme Caret Right Folder Debug base config_inspector content_migrator delta_analyzer dependency_visualizer explainer incremental_debugger models reporter shortcode_sandbox Caret Right Folder Discovery asset_discovery content_discovery Caret Right Folder Fonts downloader generator Caret Right Folder Health autofix base health_check report Caret Right Folder Linkcheck async_checker ignore_policy internal_checker models orchestrator Caret Right Folder Validators anchors assets cache config connectivity cross_ref fonts links menu navigation output performance rendering rss sitemap taxonomy tracks Caret Right Folder Directives analysis checkers constants Caret Right Folder Orchestration asset content full_to_incremental incremental menu postprocess related_posts render section static streaming taxonomy Caret Right Folder Postprocess html_output redirects rss sitemap special_pages Caret Right Folder Output Formats index_generator json_generator llm_generator lunr_index_generator txt_generator utils Caret Right Folder Rendering api_doc_enhancer asset_extractor errors jinja_utils link_transformer link_validator pygments_cache renderer template_context template_profiler validator Caret Right Folder Parsers base factory mistune native_html pygments_patch python_markdown Caret Right Folder Pipeline core output thread_local toc transforms Caret Right Folder Plugins badges cross_references inline_icon term variable_substitution Caret Right Folder Directives _icons admonitions badge base button cache cards checklist code_tabs container contracts data_table dropdown embed errors example_label fenced figure glossary icon include list_table literalinclude marimo navigation options rubric steps tabs target term terminal tokens utils validator video Caret Right Folder Template Engine asset_url core environment manifest menu url_helpers Caret Right Folder Template Functions advanced_collections advanced_strings autodoc collections content crossref data dates debug files get_page i18n icons images math_functions navigation pagination_helpers seo strings tables taxonomies theme urls Caret Right Folder Server build_handler component_preview constants dev_server live_reload pid_manager reload_controller request_handler request_logger resource_manager utils Caret Right Folder Services validation Caret Right Folder Themes config Caret Right Folder Utils atomic_write autodoc build_context build_stats build_summary cli_output css_minifier dates dotdict error_handlers file_io file_lock hashing incremental_constants js_bundler live_progress logger metadata observability page_initializer pagination path_resolver paths performance_collector performance_report profile progress retry rich_console sections swizzle text theme_registry theme_resolution thread_local traceback_config traceback_renderer url_normalization url_strategy API Reference Utils ᗢ Caret Down Link Copy URL External Open LLM text Copy Copy LLM text Share with AI Ask Claude Ask ChatGPT Ask Gemini Ask Copilot Module utils.logger Structured logging system for Bengal SSG. Provides phase-aware logging with context propagation, timing, and structured event emission. Designed for observability into the 22-phase build pipeline. Example: from bengal.utils.logger import get_logger logger = get_logger(__name__) with logger.phase("discovery", page_count=100): logger.info("discovered_content", files=len(files)) logger.debug("parsed_frontmatter", page=page.path, keys=list(metadata.keys())) View source 4 Classes 8 Functions Classes LogLevel Log levels in order of severity. 0 Caret Right Log levels in order of severity. Inherits from Enum LogEvent dataclass Structured log event with context. 2 Caret Right Structured log event with context. Attributes Name Type Description timestamp str level str logger_name str event_type str message str phase str | None phase_depth int duration_ms float | None memory_mb float | None peak_memory_mb float | None context dict[str, Any] Methods 2 to_dict Convert to dictionary for JSON serialization. 0 dict[str, Any] Caret Right def to_dict(self) -> dict[str, Any] Convert to dictionary for JSON serialization. Returns dict[str, Any] format_console Format for console output using Rich markup. 1 str Caret Right def format_console(self, verbose: bool = False) -> str Format for console output using Rich markup. Parameters 1 verbose bool Returns str BengalLogger Phase-aware structured logger for Bengal builds. Tracks build phases, emits structured events, and… 14 Caret Right Phase-aware structured logger for Bengal builds. Tracks build phases, emits structured events, and provides timing information. All logs are written to both console and a build log file. Methods 10 phase Context manager for tracking build phases with timing and memory. 1 Any Caret Right def phase(self, name: str, **context: Any) -> Any Context manager for tracking build phases with timing and memory. Parameters 1 name str Phase name **context: Additional context to attach to all events in phase Returns Any debug Log debug event. 1 None Caret Right def debug(self, message: str, **context: Any) -> None Log debug event. Parameters 1 message str info Log info event. 1 None Caret Right def info(self, message: str, **context: Any) -> None Log info event. Parameters 1 message str warning Log warning event. 1 None Caret Right def warning(self, message: str, **context: Any) -> None Log warning event. Parameters 1 message str error Log error event. 1 None Caret Right def error(self, message: str, **context: Any) -> None Log error event. Parameters 1 message str critical Log critical event. 1 None Caret Right def critical(self, message: str, **context: Any) -> None Log critical event. Parameters 1 message str get_events Get all logged events. 0 list[LogEvent] Caret Right def get_events(self) -> list[LogEvent] Get all logged events. Returns list[LogEvent] get_phase_timings Extract phase timings from events. 0 dict[str, float] Caret Right def get_phase_timings(self) -> dict[str, float] Extract phase timings from events. Returns dict[str, float] — Dict mapping phase names to duration in milliseconds print_summary Print timing summary of all phases. 0 None Caret Right def print_summary(self) -> None Print timing summary of all phases. close Close log file handle. 0 None Caret Right def close(self) -> None Close log file handle. Internal Methods 4 Caret Right __init__ Initialize logger. 5 None Caret Right def __init__(self, name: str, level: LogLevel = LogLevel.INFO, log_file: Path | None = None, verbose: bool = False, quiet_console: bool = False) Initialize logger. Parameters 5 name str Logger name (typically name) level LogLevel Minimum log level to emit log_file Path | None Path to log file (optional) verbose bool Whether to show verbose output quiet_console bool Suppress console output (for live progress mode) _emit Emit a log event. 2 None Caret Right def _emit(self, level: LogLevel, message: str, **context: Any) -> None Emit a log event. Parameters 2 level LogLevel Log level message str Human-readable message **context: Additional context data __enter__ Context manager entry. 0 BengalLogger Caret Right def __enter__(self) -> BengalLogger Context manager entry. Returns BengalLogger __exit__ Context manager exit. 1 None Caret Right def __exit__(self, exc_type: type[BaseException] | None, *args: Any) -> None Context manager exit. Parameters 1 exc_type type[BaseException] | None _GlobalConfig 0 Caret Right Inherits from TypedDict Attributes Name Type Description level LogLevel log_file Path | None verbose bool quiet_console bool Functions truncate_str Truncate a string if it exceeds max_len characters. 3 str Caret Right def truncate_str(s: str, max_len: int = 500, suffix: str = ' ... (truncated)') -> str Truncate a string if it exceeds max_len characters. Parameters 3 Name Type Default Description s str — max_len int 500 suffix str ' ... (truncated)' Returns str truncate_error Safely truncate an exception string representation. 2 str Caret Right def truncate_error(e: Exception, max_len: int = 500) -> str Safely truncate an exception string representation. Parameters 2 Name Type Default Description e Exception — max_len int 500 Returns str configure_logging Configure global logging settings. 4 None Caret Right def configure_logging(level: LogLevel = LogLevel.INFO, log_file: Path | None = None, verbose: bool = False, track_memory: bool = False) -> None Configure global logging settings. Parameters 4 Name Type Default Description level LogLevel LogLevel.INFO Minimum log level to emit log_file Path | None None Path to log file verbose bool False Show verbose output track_memory bool False Enable memory profiling (adds overhead) get_logger Get or create a logger instance. 1 BengalLogger Caret Right def get_logger(name: str) -> BengalLogger Get or create a logger instance. Parameters 1 Name Type Default Description name str — Logger name (typically name) Returns BengalLogger — BengalLogger instance set_console_quiet Enable or disable console output for all loggers. Used by live progress manager to suppress struct… 1 None Caret Right def set_console_quiet(quiet: bool = True) -> None Enable or disable console output for all loggers. Used by live progress manager to suppress structured log events while preserving file logging for debugging. Parameters 1 Name Type Default Description quiet bool True If True, suppress console output; if False, enable it close_all_loggers Close all logger file handles. 0 None Caret Right def close_all_loggers() -> None Close all logger file handles. reset_loggers Close all loggers and clear the registry (for testing). 0 None Caret Right def reset_loggers() -> None Close all loggers and clear the registry (for testing). print_all_summaries Print timing and memory summaries from all loggers. 0 None Caret Right def print_all_summaries() -> None Print timing and memory summaries from all loggers. ← Previous live_progress Next → metadata List © 2025 Bengal ᓚᘏᗢ window.BENGAL_LAZY_ASSETS = { tabulator: '/bengal/assets/js/tabulator.min.js', dataTable: '/bengal/assets/js/data-table.js', mermaidToolbar: '/bengal/assets/js/mermaid-toolbar.9de5abba.js', mermaidTheme: '/bengal/assets/js/mermaid-theme.344822c5.js', graphMinimap: '/bengal/assets/js/graph-minimap.cc7e42e3.js', graphContextual: '/bengal/assets/js/graph-contextual.440e59c6.js' }; window.BENGAL_ICONS = { close: '/bengal/assets/icons/close.911d4fe1.svg', enlarge: '/bengal/assets/icons/enlarge.652035e5.svg', copy: '/bengal/assets/icons/copy.3d56e945.svg', 'download-svg': '/bengal/assets/icons/download.04f07e1b.svg', 'download-png': '/bengal/assets/icons/image.c34dfd40.svg', 'zoom-in': '/bengal/assets/icons/zoom-in.237b4a83.svg', 'zoom-out': '/bengal/assets/icons/zoom-out.38857c77.svg', reset: '/bengal/assets/icons/reset.d26dba29.svg' }; Arrow Up X -------------------------------------------------------------------------------- Metadata: - Author: lbliii - Word Count: 1927 - Reading Time: 10 minutes