nfo

nfo Function Reference

This document provides a comprehensive reference of all functions in the nfo project, organized by module and category.

Core API

Decorators (nfo.decorators)

@log_call

Automatically logs function calls with arguments, return values, exceptions, and duration.

@log_call
def my_function(arg1, arg2):
    return arg1 + arg2

Parameters:

Returns: Decorated function

@catch

Like @log_call but suppresses exceptions and returns a default value.

@catch(default=None)
def risky_function():
    return 1 / 0  # Returns None instead of raising

Parameters:

Returns: Decorated function

@logged

Class decorator that automatically wraps all public methods with @log_call.

@logged
class MyService:
    def method1(self): pass  # Will be logged
    def _private(self): pass  # Won't be logged

Parameters:

Returns: Decorated class

@skip

Mark a public method to be excluded from @logged auto-wrapping.

@logged
class MyService:
    @skip
    def health_check(self): pass  # Excluded from logging

Auto-Logging (nfo.auto)

auto_log(*modules, **kwargs)

Automatically wrap all functions in specified modules with logging decorators.

import mymodule
auto_log(mymodule, level="INFO", catch_exceptions=True)

Parameters:

Returns: Number of functions patched

auto_log_by_name(*module_names, **kwargs)

Like auto_log() but accepts module name strings.

auto_log_by_name("myapp.api", "myapp.core", level="INFO")

Parameters:

Returns: Number of functions patched

Configuration (nfo.configure)

configure(**kwargs)

One-liner project setup with automatic environment variable support.

configure(
    sinks=["sqlite:logs.db", "csv:logs.csv"],
    level="INFO",
    modules=["myapp.api", "myapp.core"]
)

Parameters:

Returns: Configured Logger instance

Sinks

Built-in Sinks (nfo.sinks)

SQLiteSink(db_path, table)

Persist logs to SQLite database for querying.

sink = SQLiteSink("logs.db", table="function_calls")

Parameters:

CSVSink(file_path)

Append logs to CSV file.

sink = CSVSink("logs.csv")

Parameters:

MarkdownSink(file_path)

Write human-readable Markdown logs.

sink = MarkdownSink("logs.md")

Parameters:

JSONSink(file_path, pretty)

Write structured JSON Lines output.

sink = JSONSink("logs.jsonl", pretty=False)

Parameters:

Advanced Sinks

PrometheusSink (nfo.prometheus)

Export function call metrics to Prometheus.

sink = PrometheusSink(
    delegate=SQLiteSink("logs.db"),
    port=9090
)

Parameters:

Methods:

WebhookSink (nfo.webhook)

Send HTTP alerts to Slack, Discord, or Teams.

sink = WebhookSink(
    url="https://hooks.slack.com/...",
    levels=["ERROR"],
    format="slack"
)

Parameters:

LLMSink (nfo.llm)

AI-powered log analysis via litellm.

sink = LLMSink(
    model="gpt-4o-mini",
    delegate=SQLiteSink("logs.db"),
    detect_injection=True
)

Parameters:

Environment Sinks (nfo.env)

EnvTagger

Auto-tag logs with environment, trace ID, and version.

sink = EnvTagger(
    SQLiteSink("logs.db"),
    environment="prod",
    trace_id="abc123"
)

Parameters:

DynamicRouter

Route logs to different sinks based on rules.

router = DynamicRouter([
    (lambda e: e.level == "ERROR", SQLiteSink("errors.db")),
    (lambda e: e.environment == "prod", PrometheusSink())
])

Parameters:

DiffTracker

Detect when function output changes between versions.

sink = DiffTracker(SQLiteSink("logs.db"))

Parameters:

Utilities

LLM Functions (nfo.llm)

detect_prompt_injection(text)

Scan text for common prompt injection patterns.

result = detect_prompt_injection("ignore previous instructions")

Parameters:

Returns: Optional[str] - Injection type if detected

scan_entry_for_injection(entry)

Scan a LogEntry’s arguments for prompt injection.

injection = scan_entry_for_injection(log_entry)

Parameters:

Returns: Optional[str] - Injection type if detected

Environment Functions (nfo.env)

generate_trace_id()

Generate a new trace ID for distributed tracing.

trace_id = generate_trace_id()

Returns: str - UUID-based trace ID

Model Functions (nfo.models)

safe_repr(value, max_length)

Safe string representation with truncation.

repr_str = safe_repr(large_object, max_length=512)

Parameters:

Returns: str - Safe representation

CLI Interface

Main Commands (nfo.__main__)

nfo run -- <command>

Run any command with automatic logging.

nfo run -- python script.py
nfo run -- bash deploy.sh prod

nfo logs [options]

Query logs from SQLite database.

nfo logs --errors --last 24h
nfo logs --function deploy -n 50

nfo serve [--port]

Start centralized HTTP logging service.

nfo serve --port 8080

nfo version

Print nfo version.

nfo version

Data Models

LogEntry (nfo.models)

Core data structure representing a function call log.

Fields:

Methods:

Logger (nfo.logger)

Central dispatcher for log entries.

Methods:

Sink Interface

All sinks implement the same interface:

class Sink:
    def write(self, entry: LogEntry) -> None:
        """Write a log entry."""
        pass
    
    def close(self) -> None:
        """Close the sink and release resources."""
        pass

Environment Variables

nfo automatically reads these environment variables:

Sink Specifications

String format for configure() and CLI:

sqlite:path/to/db.db
csv:path/to/file.csv
md:path/to/file.md
json:path/to/file.jsonl
prometheus:9090

Error Handling

Common Exceptions

Best Practices

  1. Always wrap risky operations with @catch
  2. Use appropriate log levels (DEBUG for success, ERROR for failures)
  3. Configure multiple sinks for redundancy
  4. Set max_repr_length for functions with large arguments
  5. Use environment variables for deployment-specific configuration