Skip to content

Formatting & Visualization API

The pretty-loguru formatting module provides powerful visualization tools that can transform monotonous logs into well-structured, easily readable information. This includes structured blocks, ASCII art, and deep integration with Rich library's advanced components.

logger.block() - Structured Blocks

Using logger.block() creates a panel with a title and border, perfect for displaying a group of related information.

python
def block(
    title: str,
    message_list: List[str],
    border_style: str = "cyan",
    log_level: str = "INFO",
    to_console_only: bool = False,
    to_log_file_only: bool = False
) -> None:
    ...

Parameter Descriptions:

ParameterTypeDescription
titlestrTitle of the block.
message_listList[str]List of messages to display within the block.
border_stylestrRich border style like "solid", "double", "rounded" or color name "green".
log_levelstrLog level for this message, such as "INFO", "WARNING".
to_console_onlyboolIf True, this message only appears in console, not written to file.
to_log_file_onlyboolIf True, this message only written to file, not displayed in console.

Examples:

python
logger.block(
    "System Status",
    [
        "Service: API Server - OK",
        "Database Connection: Success",
        "CPU Usage: 35%",
    ],
    border_style="green",
    log_level="SUCCESS"
)

ASCII Art Features

This feature requires additional installation of the art library (pip install art).

logger.ascii_header() - ASCII Art Headers

Converts text into ASCII art form headers, commonly used to mark program startup, shutdown, or important phases.

python
def ascii_header(
    text: str,
    font: str = "standard",
    border_style: str = "cyan",
    log_level: str = "INFO"
) -> None:
    ...

Parameter Descriptions:

ParameterTypeDescription
textstrText to convert (ASCII characters only).
fontstrFont supported by art library, such as "standard", "slant", "doom", "block".
border_stylestrBorder style or color.
log_levelstrLog level.

Examples:

python
logger.ascii_header("STARTUP", font="block", border_style="magenta")

logger.ascii_block() - ASCII Art Blocks

Combines ASCII headers with structured blocks, displaying both artistic headers and detailed information within one panel.

python
def ascii_block(
    title: str,
    message_list: List[str],
    ascii_header: Optional[str] = None,
    ascii_font: str = "standard",
    border_style: str = "cyan",
    log_level: str = "INFO"
) -> None:
    ...

Parameter Descriptions:

ParameterTypeDescription
titlestrTitle of the block.
message_listList[str]List of messages within the block.
ascii_headerOptional[str]ASCII text to convert. If None, uses title.
ascii_fontstrFont for ASCII art.
border_stylestrBorder style or color.
log_levelstrLog level.

Rich Advanced Components

pretty-loguru integrates various Rich advanced components to make log presentations more diverse.

logger.table() - Table Display

Display structured data in formatted tables.

python
def table(
    title: str,
    data: List[Dict[str, Any]],
    headers: Optional[List[str]] = None,
    log_level: str = "INFO",
    **table_kwargs
) -> None:
    ...

Parameter Descriptions:

ParameterTypeDescription
titlestrTitle of the table.
dataList[Dict[str, Any]]Data source for the table, a list of dictionaries.
headersOptional[List[str]]Custom headers. If None, uses keys from the first dictionary in data.
log_levelstrLog level.
**table_kwargsAnyAdditional parameters passed to rich.table.Table, such as show_lines=True.

Examples:

python
user_data = [
    {"ID": "001", "Name": "Alice", "Status": "Online"},
    {"ID": "002", "Name": "Bob", "Status": "Offline"},
]
logger.table("User Status", user_data, show_lines=True)

logger.tree() - Tree Structure

Display hierarchical data in tree structure format.

python
def tree(
    title: str,
    tree_data: Dict[str, Any],
    log_level: str = "INFO",
    **tree_kwargs
) -> None:
    ...

Parameter Descriptions:

ParameterTypeDescription
titlestrTitle for the tree root node.
tree_dataDict[str, Any]Tree structure data, supports nested dictionaries.
log_levelstrLog level.
**tree_kwargsAnyAdditional parameters passed to rich.tree.Tree.

Examples:

python
file_system = {
    "C:": {
        "Program Files": {"..."},
        "Users": {"Alice": {"Desktop": "..."}},
    }
}
logger.tree("File System", file_system)

logger.columns() - Column Display

Arrange a list of items neatly in multiple columns.

python
def columns(
    title: str,
    items: List[str],
    columns: int = 3,
    log_level: str = "INFO",
    **columns_kwargs
) -> None:
    ...

Parameter Descriptions:

ParameterTypeDescription
titlestrTitle for the column display.
itemsList[str]List of items to display.
columnsintNumber of columns to divide into.
log_levelstrLog level.
**columns_kwargsAnyAdditional parameters passed to rich.columns.Columns.

logger.progress - Progress Bars

Provides a progress bar tool integrated with the logging system, suitable for tracking long-running tasks.

logger.progress.progress_context()

A context manager for tracking tasks with a fixed total number of steps.

python
@contextmanager
def progress_context(description: str = "Processing", total: int = 100):
    ...

Examples:

python
with logger.progress.progress_context("Downloading files", total=1024) as update:
    for chunk in range(1024):
        # ... process data ...
        update(1)

logger.progress.track_list()

An iterator for tracking progress when processing lists or other iterable objects.

python
def track_list(items: List[Any], description: str = "Processing items") -> List[Any]:
    ...

Examples:

python
import time
tasks = range(5)
for task in logger.progress.track_list(tasks, "Executing tasks"):
    time.sleep(0.5)

Code Highlighting Features

pretty-loguru provides powerful syntax highlighting capabilities through Rich integration.

logger.code() - Display Code Snippets

Display syntax-highlighted code directly from strings.

python
def code(
    code: str,
    language: str = "python",
    theme: str = "monokai",
    line_numbers: bool = True,
    word_wrap: bool = False,
    indent_guides: bool = True,
    title: Optional[str] = None,
    log_level: str = "INFO",
    to_console_only: bool = False,
    to_log_file_only: bool = False,
    **syntax_kwargs
) -> None:
    ...

Parameter Descriptions:

ParameterTypeDescription
codestrSource code to display
languagestrProgramming language (python, javascript, sql, etc.)
themestrSyntax highlighting theme
line_numbersboolWhether to show line numbers
word_wrapboolEnable automatic word wrapping
indent_guidesboolShow indentation guide lines
titleOptional[str]Optional title for the code block
log_levelstrLog level
to_console_onlyboolDisplay only in console
to_log_file_onlyboolSave only to log files
**syntax_kwargsAnyAdditional parameters for Rich Syntax

Examples:

python
code = '''
def fibonacci(n):
    """Calculate nth Fibonacci number"""
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)
'''

logger.code(code, language="python", title="Fibonacci Function")

logger.code_file() - Display Code from Files

Read and display code directly from files with automatic language detection.

python
def code_file(
    file_path: str,
    language: Optional[str] = None,
    theme: str = "monokai",
    line_numbers: bool = True,
    start_line: Optional[int] = None,
    end_line: Optional[int] = None,
    log_level: str = "INFO",
    to_console_only: bool = False,
    to_log_file_only: bool = False,
    **syntax_kwargs
) -> None:
    ...

Parameter Descriptions:

ParameterTypeDescription
file_pathstrPath to the source file
languageOptional[str]Override automatic language detection
themestrSyntax highlighting theme
line_numbersboolWhether to show line numbers
start_lineOptional[int]First line to display (1-based)
end_lineOptional[int]Last line to display (1-based)
log_levelstrLog level
to_console_onlyboolDisplay only in console
to_log_file_onlyboolSave only to log files
**syntax_kwargsAnyAdditional parameters for Rich Syntax

Examples:

python
# Display specific lines from a file
logger.code_file("script.py", start_line=10, end_line=25)

# Display entire file with auto-detected language
logger.code_file("config.json", theme="github-dark")

logger.diff() - Code Comparison

Display side-by-side code comparison with Git-style visual differentiation.

python
def diff(
    old_code: str,
    new_code: str,
    old_title: str = "Before",
    new_title: str = "After",
    language: str = "python",
    theme: str = "monokai",
    log_level: str = "INFO",
    to_console_only: bool = False,
    to_log_file_only: bool = False,
    **syntax_kwargs
) -> None:
    ...

Parameter Descriptions:

ParameterTypeDescription
old_codestrOriginal version of the code
new_codestrUpdated version of the code
old_titlestrLabel for old version (red border)
new_titlestrLabel for new version (green border)
languagestrProgramming language for syntax highlighting
themestrSyntax highlighting theme
log_levelstrLog level
to_console_onlyboolDisplay only in console
to_log_file_onlyboolSave only to log files
**syntax_kwargsAnyAdditional parameters for Rich Syntax

Examples:

python
old_func = "def hello(): print('Hi')"
new_func = "def hello(): print('Hello, World!')"

logger.diff(
    old_code=old_func,
    new_code=new_func,
    old_title="Before Refactoring",
    new_title="After Refactoring",
    language="python"
)

Supported Languages

The code highlighting feature supports many programming languages:

  • Python (.py) - python
  • JavaScript (.js) - javascript
  • TypeScript (.ts) - typescript
  • HTML (.html) - html
  • CSS (.css) - css
  • JSON (.json) - json
  • SQL (.sql) - sql
  • Markdown (.md) - markdown
  • YAML (.yaml, .yml) - yaml
  • XML (.xml) - xml
  • Bash (.sh) - bash
  • C/C++ (.c, .cpp) - c, cpp
  • Java (.java) - java
  • Go (.go) - go
  • Rust (.rs) - rust
  • PHP (.php) - php
  • Ruby (.rb) - ruby

Available Themes

Choose from various syntax highlighting themes:

  • monokai (default)
  • github-dark
  • github-light
  • one-dark
  • material
  • dracula
  • nord
  • solarized-dark
  • solarized-light

Back to API Overview

Released under the MIT License.