API Reference
Full reference for all functions in the statly module.
Initialization
init()
Initialize the SDK. Call once at application startup.
def init(
dsn: str,
environment: str | None = None,
release: str | None = None,
debug: bool = False,
sample_rate: float = 1.0,
max_breadcrumbs: int = 100,
before_send: Callable | None = None,
transport: Transport | None = None,
) -> NoneParameters:
dsn- Data Source Name (required)environment- Environment namerelease- Application versiondebug- Enable debug loggingsample_rate- Event sampling rate (0.0-1.0)max_breadcrumbs- Maximum breadcrumbs per eventbefore_send- Callback to filter/modify eventstransport- Custom transport implementation
Example:
from statly_observe import Statly
Statly.init(
dsn='https://sk_live_xxx@statly.live/your-org',
environment='production',
release='1.2.3',
)Capturing Events
capture_exception()
Capture an exception.
def capture_exception(
exception: BaseException | None = None,
context: dict | None = None,
) -> strParameters:
exception- Exception to capture (uses current if None)context- Additional context data
Returns: Event ID (UUID string)
Example:
from statly_observe import Statly
try:
risky_operation()
except Exception as e:
event_id = Statly.capture_exception(e, context={
'operation': 'risky_operation',
'user_id': current_user.id,
})
print(f'Captured: {event_id}')capture_message()
Capture a message event.
def capture_message(
message: str,
level: str = 'info',
context: dict | None = None,
) -> strParameters:
message- Message textlevel- Severity: debug, info, warning, error, fatalcontext- Additional context data
Returns: Event ID
Example:
from statly_observe import Statly
Statly.capture_message('User completed checkout', level='info')
Statly.capture_message('Payment retry needed', level='warning')
Statly.capture_message('Critical system error', level='fatal')Context Management
set_user()
Set user context for all future events.
def set_user(
id: str | None = None,
email: str | None = None,
username: str | None = None,
**kwargs,
) -> NoneExample:
from statly_observe import Statly
# Set user after login
Statly.set_user(
id='user_123',
email='jane@example.com',
username='janedoe',
plan='enterprise', # Custom field
)
# Clear user on logout
Statly.set_user() # No args clears userset_tag()
Set a single tag.
def set_tag(key: str, value: str) -> NoneExample:
from statly_observe import Statly
Statly.set_tag('feature', 'checkout')
Statly.set_tag('experiment', 'new_ui')set_tags()
Set multiple tags at once.
def set_tags(tags: dict[str, str]) -> NoneExample:
from statly_observe import Statly
Statly.set_tags({
'region': 'us-east-1',
'service': 'payment-api',
'version': '2.1.0',
})Breadcrumbs
add_breadcrumb()
Add a breadcrumb to the trail.
def add_breadcrumb(
message: str,
category: str | None = None,
level: str = 'info',
data: dict | None = None,
type: str = 'default',
) -> NoneExample:
from statly_observe import Statly
# Navigation
Statly.add_breadcrumb(
message='User navigated to /checkout',
category='navigation',
level='info',
)
# Database query
Statly.add_breadcrumb(
message='SELECT * FROM users WHERE id = ?',
category='query',
level='info',
data={'duration_ms': 45},
)
# HTTP request
Statly.add_breadcrumb(
message='POST /api/orders',
category='http',
level='info',
data={'status': 201, 'duration': 245},
)Lifecycle
flush()
Wait for all pending events to be sent.
def flush(timeout: float | None = None) -> NoneExample:
from statly_observe import Statly
Statly.capture_message('Important event')
Statly.flush(timeout=5.0) # Wait up to 5 secondsclose()
Flush pending events and shut down the SDK.
def close(timeout: float | None = None) -> NoneExample:
from statly_observe import Statly
import atexit
Statly.init(dsn='...')
atexit.register(lambda: Statly.close(timeout=2.0))get_client()
Get the SDK client instance.
def get_client() -> StatlyClient | NoneExample:
from statly_observe import Statly
client = Statly.get_client()
if client:
print('SDK is initialized')Exception Handling
Unhandled exceptions are automatically captured when Statly.init() is called. The SDK installs a Python exception hook that captures any unhandled exceptions before the program exits.
Logger
The Logger class provides structured logging with automatic scrubbing, batching, and session management.
Logger()
Create a new logger instance.
class Logger:
def __init__(
self,
dsn: str,
environment: str | None = None,
release: str | None = None,
logger_name: str | None = None,
session_id: str | None = None,
user: dict | None = None,
default_context: dict | None = None,
min_level: str = 'trace',
sample_rates: dict | None = None,
scrub_patterns: list[str] | None = None,
batch_size: int = 50,
flush_interval: float = 5.0,
max_queue_size: int = 1000,
) -> NoneExample:
from statly_observe import Logger
logger = Logger(
dsn='https://sk_live_xxx@statly.live/your-org',
environment='production',
logger_name='api-server',
)Logging Methods
trace(message, **data)
Log at trace level (ultra-detailed debugging).
logger.trace('Entering function', args=[1, 2, 3])debug(message, **data)
Log at debug level.
logger.debug('Processing request', request_id='req_123')info(message, **data)
Log at info level.
logger.info('User logged in', user_id='user_123')warn(message, **data)
Log at warning level.
logger.warn('Rate limit approaching', current=95, limit=100)error(message, **data)
Log at error level.
logger.error('Payment failed', order_id='ord_456', error='Card declined')fatal(message, **data)
Log at fatal level.
logger.fatal('Database connection lost', host='db.example.com')audit(message, **data)
Log at audit level (security/compliance).
logger.audit('User role changed', user_id='user_123', new_role='admin')child()
Create a child logger with inherited settings and additional context.
def child(
self,
context: dict | None = None,
logger_name: str | None = None,
) -> LoggerExample:
request_logger = logger.child(
context={'request_id': 'req_123'},
logger_name='request-handler',
)
request_logger.info('Processing request') # Includes request_idset_user()
Set user context for the logger.
def set_user(
self,
id: str | None = None,
email: str | None = None,
name: str | None = None,
**kwargs,
) -> NoneExample:
logger.set_user(
id='user_123',
email='jane@example.com',
name='Jane Doe',
)flush()
Flush all pending logs to the server.
def flush(self, timeout: float | None = None) -> NoneExample:
# Before shutdown
logger.flush(timeout=5.0)close()
Flush and close the logger.
def close(self, timeout: float | None = None) -> NoneExample:
import atexit
logger = Logger(dsn='...')
atexit.register(lambda: logger.close(timeout=2.0))with statement
The Logger supports context managers for automatic cleanup:
with Logger(dsn='...') as logger:
logger.info('Processing...')
# Logger automatically flushed and closedLog Levels
| Level | Numeric Value | Description |
|---|---|---|
trace | 0 | Ultra-detailed debugging |
debug | 10 | Development debugging |
info | 20 | General information |
warn | 30 | Warning conditions |
error | 40 | Error conditions |
fatal | 50 | Critical failures |
audit | 60 | Security/compliance events |
Sample Rates
Configure per-level sampling to control log volume:
logger = Logger(
dsn='...',
sample_rates={
'trace': 0.01, # 1% of trace logs
'debug': 0.1, # 10% of debug logs
'info': 0.5, # 50% of info logs
'warn': 1.0, # 100% of warnings
'error': 1.0, # 100% of errors
'fatal': 1.0, # 100% of fatal
},
)Secret Scrubbing
The logger automatically scrubs sensitive data. Add custom patterns:
logger = Logger(
dsn='...',
scrub_patterns=[
r'my-custom-secret-[a-z0-9]+',
r'internal-token-\d+',
],
)