API Reference

High-Level Client

class v2root.V2RootClient(http_port=2300, socks_port=2301, *, core_path=None, core_manager=None, auto_install=True, geosite_path=None, native_factory=<class 'v2root.native.NativeCore'>)[source]

Bases: object

Primary SDK facade.

Construction resolves or installs a compatible core. Configuration methods accept either share URIs, raw JSON, or configuration file paths supported by V2Root Core. Lifecycle operations are serialized per client.

configure_logging(level=None, output=None)[source]

Configure native log level and destination.

Parameters:
  • level (str | None) – Native level such as warning or debug.

  • output (str | os.PathLike[str] | None) – Writable native log path.

Returns:

Native process-global logging settings are updated in place.

Return type:

None

connect(config_input, *, validate=True)[source]

Select a configuration and start the runtime in one operation.

Parameters:
  • config_input (str) – Share URI, JSON, or supported config path.

  • validate (bool) – Validate again immediately before startup.

Returns:

This client for fluent usage.

Return type:

V2RootClient

Raises:
  • ConfigurationError – If parsing or validation fails.

  • NativeCallError – If startup fails.

parse(uri, **options)[source]

Convert a share URI into normalized Xray-compatible JSON.

Parameters:
  • uri (str) – VLESS, VMess, Trojan, or Shadowsocks share URI.

  • **options – Additional parser options documented by V2Root Core.

Returns:

Complete normalized JSON configuration.

Return type:

str

Raises:
  • ValueError – If uri is empty or not a string.

  • ConfigurationError – If the native parser returns an empty result.

property running: bool

Return whether the embedded runtime currently reports RUNNING.

Returns:

True only for RuntimeStatus.RUNNING.

Return type:

bool

property runtime_status: RuntimeStatus

Return the lifecycle status as a typed enumeration.

Returns:

Typed representation of the native status string.

Return type:

RuntimeStatus

Raises:

ValueError – If a future core returns an unknown status value.

set_config(config_input, parse_uri=True)[source]

Normalize, validate, and retain a runtime configuration.

Parameters:
  • config_input (str) – Share URI, raw JSON, or native-supported path.

  • parse_uri (bool) – Parse recognized share URI schemes before validation.

Returns:

Normalized configuration retained by this client.

Return type:

str

Raises:
  • ValueError – If config_input is empty or not a string.

  • ConfigurationError – If parsing or validation fails.

property speed

Return upload and download rates calculated by the native core.

Returns:

Upload and download rates in bytes per second.

Return type:

RealtimeSpeed

Raises:

NativeCallError – If the runtime is stopped or native JSON is invalid.

start(config_input=None, validate=True)[source]

Start the process-global embedded runtime.

Parameters:
  • config_input (str | None) – Configuration to start. None uses the retained configuration.

  • validate (bool) – Validate before startup when true.

Returns:

Runtime status after startup is accepted.

Return type:

str

Raises:
  • ValueError – If no configuration is available.

  • ConfigurationError – If pre-start validation fails.

  • NativeCallError – If the core rejects startup.

property status

Return the raw lifecycle status reported by V2Root Core.

Returns:

One of STOPPED, STARTING, RUNNING, or STOPPING.

Return type:

str

stop(ignore_stopped=True)[source]

Stop the process-global embedded runtime.

Parameters:

ignore_stopped (bool) – Treat server not running as success.

Returns:

Runtime status after the stop operation.

Return type:

str

Raises:

NativeCallError – If shutdown fails for another reason.

test_latency(configs, test_url='', timeout=10)[source]

Measure latency for one or more configurations.

Parameters:
  • configs (str | os.PathLike[str] | Iterable[str]) – One config, a text file containing configs, or an ordered iterable.

  • test_url (str) – HTTP(S) endpoint used by the native latency probe.

  • timeout (int) – Per-test timeout in seconds.

Returns:

Ordered numeric latencies and native error strings.

Return type:

list[int | str]

Raises:
  • ValueError – If the normalized configuration collection is empty.

  • NativeCallError – If the native batch operation itself fails.

test_latency_detailed(configs, test_url='', timeout=10)[source]

Measure latency and return structured per-configuration results.

Parameters:
  • configs (str | os.PathLike[str] | Iterable[str]) – Config source.

  • test_url (str) – HTTP(S) endpoint used by the native probe.

  • timeout (int) – Per-test timeout in seconds.

Returns:

Ordered results containing config, latency, and error.

Return type:

list[LatencyResult]

Raises:
  • ValueError – If no configurations are supplied.

  • NativeCallError – If the native batch operation fails.

test_subscription(manager, subscription_id=None, timeout=10)[source]

Test subscription configs and persist their results.

Parameters:
  • manager (SubscriptionManager) – Manager owning configs and persistence.

  • subscription_id (str | None) – Restrict testing to one source.

  • timeout (int) – Per-test timeout in seconds.

Returns:

Ordered structured measurements.

Return type:

list[LatencyResult]

Raises:
  • ValueError – If the selected source has no configurations.

  • NativeCallError – If the native latency operation fails.

  • PersistenceError – If results cannot be saved.

to_share_uri(config)[source]

Convert a JSON configuration to a supported share URI.

Parameters:

config (str | Mapping[str, object]) – JSON text or serializable mapping.

Returns:

VLESS, VMess, Trojan, or Shadowsocks share URI.

Return type:

str

Raises:
  • TypeError – If a non-string config is not JSON serializable.

  • ConfigurationError – If no outbound can be converted.

property traffic

Return cumulative non-API outbound traffic counters.

Returns:

Uploaded and downloaded byte counts.

Return type:

Traffic

Raises:

NativeCallError – If the runtime is stopped or native JSON is invalid.

update_core()[source]

Update the managed core while the runtime is stopped.

Returns:

Previous/current installations and change status.

Return type:

UpdateResult

Raises:
  • NativeCallError – If the runtime is not stopped.

  • CoreError – If release discovery, download, or installation fails.

update_geo_assets(asset_path='')[source]

Download geosite and geoip assets through the native core.

Parameters:

asset_path (str | os.PathLike[str]) – Destination directory. An empty path requests the core default.

Returns:

Per-file download status returned by the core.

Return type:

dict[str, str]

Raises:

NativeCallError – If the native response is invalid or globally fails.

validate(config_input=None)[source]

Validate a configuration without starting a persistent runtime.

Parameters:

config_input (str | None) – Configuration to validate. None uses the configuration previously selected by set_config().

Returns:

Native validation response, normally

{"result": "valid"}.

Return type:

dict[str, object]

Raises:
  • ValueError – If no configuration is available.

  • ConfigurationError – If native validation reports an error.

property version_info

Return typed build metadata for the loaded native core.

Returns:

Core code version, upstream version, and build date.

Return type:

VersionInfo

Raises:

NativeCallError – If native metadata is missing or invalid JSON.

Compatibility Facade

class v2root.V2ROOT(http_port=2300, socks_port=2301, v2ray_path=None, lib_path=None, geosite_path=None, auto_install=True, core_manager=None)[source]

Bases: V2RootClient

Expose familiar method names while executing the V2Root 2.0 implementation.

New applications should prefer V2RootClient. This class exists to ease source migration; it does not load the retired C wrapper or launch an external V2Ray executable.

get_realtime_speed()[source]

Return realtime speed in the legacy dictionary shape.

Returns:

Upload and download bytes per second.

Return type:

dict[str, float]

get_status()[source]

Return the current runtime status.

Returns:

Native lifecycle state.

Return type:

str

get_total_traffics()[source]

Return cumulative traffic in the legacy dictionary shape.

Returns:

uplink and downlink byte counters.

Return type:

dict[str, int]

get_version_info()[source]

Return version metadata with native JSON field names.

Returns:

Code version, upstream version, and release date.

Return type:

dict[str, object]

json_to_config_string(config)[source]

Convert JSON to a share URI through the legacy method name.

Parameters:

config (str | Mapping[str, object]) – JSON text or serializable mapping.

Returns:

Supported share URI.

Return type:

str

reset_network_proxy()[source]

Stop the runtime without changing operating-system proxy settings.

Returns:

Runtime status after shutdown.

Return type:

str

Notes

V2Root 2.0 intentionally does not mutate system proxy configuration.

set_config_string(config_str)[source]

Validate and retain a config using the legacy method name.

Parameters:

config_str (str) – Share URI, JSON, or supported config path.

Returns:

Legacy success object {"result": "valid"}.

Return type:

dict[str, str]

Raises:

ConfigurationError – If parsing or validation fails.

set_log_level(level)[source]

Configure the native log level.

Parameters:

level (str) – Native level such as warning or debug.

Returns:

Process-global native logging is updated.

Return type:

None

set_log_output(path)[source]

Configure the native log destination.

Parameters:

path (str | os.PathLike[str]) – Writable log file path.

Returns:

Process-global native logging is updated.

Return type:

None

test_configs(configs, timeout=10, test_url='')[source]

Measure multiple configurations using the legacy batch method.

Parameters:
  • configs (str | os.PathLike[str] | Iterable[str]) – Config source.

  • timeout (int) – Timeout in seconds.

  • test_url (str) – Optional latency endpoint.

Returns:

Ordered latencies and native per-item errors.

Return type:

list[int | str]

test_connection(config_str, timeout=10, test_url='')[source]

Measure one configuration through the native latency service.

Parameters:
  • config_str (str) – Share URI or raw configuration.

  • timeout (int) – Timeout in seconds.

  • test_url (str) – Optional latency endpoint.

Returns:

Latency in milliseconds.

Return type:

int

Raises:

NativeCallError – If the individual result is nonnumeric.

validate_config(config_input=None)[source]

Validate a configuration using the legacy method name.

Parameters:

config_input (str | None) – Explicit config or retained config.

Returns:

Native validation response.

Return type:

dict[str, object]

Core Management

class v2root.CoreManager(cache_dir=None, repository='v2RayRoot/V2Root-Core', transport=None, target=None)[source]

Discover, install, update, activate, and roll back V2Root Core.

activate(tag)[source]

Atomically activate an already installed release.

Parameters:

tag (str) – Installed release tag.

Returns:

Activated installation.

Return type:

InstalledCore

Raises:
  • CoreNotInstalledError – If the tag is not a valid installation.

  • OSError – If the activation marker cannot be replaced.

property api_base

Return the configured GitHub REST API base.

Returns:

Repository releases API prefix.

Return type:

str

current()[source]

Resolve the currently activated core.

Returns:

Active valid installation, otherwise None.

Return type:

InstalledCore | None

property current_file

Return the active-release marker path.

Returns:

current file inside the managed cache.

Return type:

pathlib.Path

ensure(auto_install=True)[source]

Ensure that a usable active core exists.

Parameters:

auto_install (bool) – Install the latest compatible release when absent.

Returns:

Existing or newly installed active core.

Return type:

InstalledCore

Raises:
  • CoreNotInstalledError – If absent and automatic installation is disabled.

  • CoreError – If automatic installation fails.

get_release(tag)[source]

Fetch metadata for an explicitly tagged release.

Parameters:

tag (str) – Exact GitHub release tag.

Returns:

Normalized release metadata.

Return type:

CoreRelease

Raises:

CoreDownloadError – If the tag is unavailable or malformed.

install(tag=None, force=False)[source]

Download, verify, atomically install, and activate a release.

Parameters:
  • tag (str | None) – Exact release tag, or latest when omitted.

  • force (bool) – Reinstall even when the release is already cached.

Returns:

Verified active installation.

Return type:

InstalledCore

Raises:
  • CoreDownloadError – If metadata or the target asset is unavailable.

  • CoreIntegrityError – If archive layout or checksums are invalid.

  • OSError – If local atomic installation operations fail.

installed()[source]

Discover valid cached core installations.

Returns:

Installations ordered by timestamp descending.

Return type:

list[InstalledCore]

Notes

Corrupt unrelated manifests are skipped so one bad historical release does not prevent use of healthy installations.

latest_release()[source]

Fetch metadata for the latest published core release.

Returns:

Normalized release tag, publication date, and assets.

Return type:

CoreRelease

Raises:

CoreDownloadError – If metadata cannot be fetched or normalized.

remove(tag)[source]

Remove an inactive cached release.

Parameters:

tag (str) – Release tag to remove.

Returns:

Whether a release directory was deleted.

Return type:

bool

Raises:
  • CoreIntegrityError – If attempting to remove the active release.

  • OSError – If deletion fails.

rollback()[source]

Activate the newest valid installation other than the current one.

Returns:

Newly activated previous installation.

Return type:

InstalledCore

Raises:

CoreNotInstalledError – If no rollback candidate exists.

update()[source]

Update the active core to the latest release.

Returns:

Previous/current installations and whether they differ.

Return type:

UpdateResult

Raises:

CoreError – If release discovery or installation fails.

Runtime Models

class v2root.RuntimeStatus(*values)[source]

Enumerate lifecycle states exposed by the process-global native runtime.

class v2root.VersionInfo(code_version, version, release_date)[source]

Expose build metadata reported by the loaded V2Root Core binary.

Parameters:
  • code_version (int)

  • version (str)

  • release_date (str | None)

classmethod from_dict(value)[source]

Create a typed version record from native JSON.

Parameters:

value (dict[str, Any]) – Decoded GetVersionInfo response.

Returns:

Normalized metadata with defensive defaults.

Return type:

VersionInfo

class v2root.Traffic(uplink, downlink)[source]

Contain cumulative uploaded and downloaded byte counters.

Parameters:
class v2root.RealtimeSpeed(uplink, downlink)[source]

Contain current upload and download rates measured in bytes per second.

Parameters:
class v2root.LatencyResult(index, config, latency_ms, error)[source]

Describe one ordered latency measurement or its per-item failure.

Parameters:
  • index (int)

  • config (str)

  • latency_ms (int | None)

  • error (str | None)

property succeeded: bool

Return whether the core produced a numeric latency.

Returns:

True when latency_ms is not None.

Return type:

bool

Subscriptions

class v2root.SubscriptionManager(storage_dir=None, *, repository=None, parser=None, transport=None)[source]

Coordinate subscription transport, parsing, persistence, and scheduling.

The manager is the application-service boundary for subscriptions. Its dependencies are injectable, allowing deterministic tests and alternative transports or repositories without changing domain models.

add_subscription(url, name=None, auto_update=False, update_interval=86400, enabled=True, priority=0, tags=None, fetch_now=True)[source]

Register, optionally fetch, persist, and schedule a subscription.

Parameters:
  • url (str) – Absolute HTTP(S) subscription URL.

  • name (str | None) – Optional display name.

  • auto_update (bool) – Start a periodic scheduler after registration.

  • update_interval (int) – Scheduler interval in seconds.

  • enabled (bool) – Include this source in aggregate queries.

  • priority (int) – Application-defined priority value.

  • tags (Iterable[str] | None) – Source classification labels.

  • fetch_now (bool) – Fetch and parse the source before returning.

Returns:

The registered and possibly populated model.

Return type:

Subscription

Raises:
  • ValueError – If the URL is duplicated or model values are invalid.

  • FetchError – If immediate fetching fails.

  • ParseError – If immediate parsing finds no valid configurations.

  • PersistenceError – If state cannot be saved.

best_config(**filters)[source]

Select the lowest-latency tested configuration after filtering.

Parameters:

**filters – Filters accepted by filter_configs().

Returns:

Best tested candidate, or None.

Return type:

ConfigMetadata | None

close()[source]

Stop all active schedulers and persist their disabled state.

Returns:

All known schedulers are synchronously requested to stop.

Return type:

None

filter_configs(subscription_tags=None, **filters)[source]

Filter enabled subscriptions and their configurations.

Parameters:
  • subscription_tags (Iterable[str] | None) – Require at least one matching source tag.

  • **filters – Keyword filters accepted by Subscription.filter_configs().

Returns:

Metadata satisfying source and config filters.

Return type:

list[ConfigMetadata]

Raises:

ValueError – If a delegated configuration filter is invalid.

get_all_configs(enabled_only=True)[source]

Flatten share URIs from all selected subscriptions.

Parameters:

enabled_only (bool) – Exclude disabled subscriptions when true.

Returns:

Configuration strings in subscription and source order.

Return type:

list[str]

get_config_metadata(enabled_only=True)[source]

Flatten metadata objects from all selected subscriptions.

Parameters:

enabled_only (bool) – Exclude disabled subscriptions when true.

Returns:

References to managed metadata objects.

Return type:

list[ConfigMetadata]

get_configs_from_subscription(subscription_id)[source]

Return share URIs for one source when it exists.

Parameters:

subscription_id (str) – Stable source identifier.

Returns:

Config strings or None for an unknown source.

Return type:

list[str] | None

get_subscription(subscription_id)[source]

Look up one subscription without raising when it is absent.

Parameters:

subscription_id (str) – Stable source identifier.

Returns:

Registered model or None.

Return type:

Subscription | None

list_subscriptions()[source]

Serialize all registered subscriptions for presentation or export.

Returns:

JSON-compatible subscription documents.

Return type:

list[dict[str, object]]

record_latency(config_string, latency, success=True)[source]

Record and persist a test result for the matching share URI.

Parameters:
  • config_string (str) – Exact configuration string to locate.

  • latency (int) – Measured latency in milliseconds.

  • success (bool) – Whether the connection test succeeded.

Returns:

True when a matching config was updated.

Return type:

bool

Raises:

PersistenceError – If the owning subscription cannot be saved.

remove_subscription(subscription_id)[source]

Stop scheduling and remove one subscription from memory and storage.

Parameters:

subscription_id (str) – Stable source identifier.

Returns:

Whether the subscription existed in memory.

Return type:

bool

require(subscription_id)[source]

Look up one subscription and require that it exists.

Parameters:

subscription_id (str) – Stable source identifier.

Returns:

Registered model.

Return type:

Subscription

Raises:

KeyError – If no source has the requested identifier.

start_auto_update(subscription_id)[source]

Enable and start periodic updates for one subscription.

Parameters:

subscription_id (str) – Stable source identifier.

Returns:

Whether a new scheduler thread was started.

Return type:

bool

Raises:
  • KeyError – If the source is unknown.

  • PersistenceError – If the updated setting cannot be saved.

stop_auto_update(subscription_id)[source]

Disable periodic updates and join the source scheduler.

Parameters:

subscription_id (str) – Stable source identifier.

Returns:

Whether no scheduler remains running.

Return type:

bool

update_all(timeout=30, max_workers=4)[source]

Update all enabled subscriptions concurrently.

Parameters:
  • timeout (int | float) – Per-subscription network timeout in seconds.

  • max_workers (int) – Maximum number of worker threads.

Returns:

Mapping from source ID

to parsed configs or the exception raised by that source.

Return type:

dict[str, list[ConfigMetadata] | Exception]

update_subscription(subscription_id, timeout=30)[source]

Fetch, parse, merge, and persist one subscription.

Parameters:
  • subscription_id (str) – Stable identifier of a registered source.

  • timeout (int | float) – Network timeout in seconds.

Returns:

Newly parsed configuration metadata.

Return type:

list[ConfigMetadata]

Raises:
  • KeyError – If subscription_id is unknown.

  • FetchError – If the source cannot be downloaded.

  • ParseError – If downloaded content is invalid.

  • PersistenceError – If success or failure state cannot be persisted.

class v2root.Subscription(url, name=None, auto_update=False, update_interval=86400, enabled=True, priority=0, tags=<factory>, configs=<factory>, last_update_time=0, last_fetch_success=False, last_error_message='', total_updates=0, successful_updates=0, failed_updates=0)[source]

Represent one remote subscription and its persistent application state.

The model validates URL and scheduling invariants at construction time. It does not perform network I/O itself; fetching, parsing, and persistence are coordinated by SubscriptionManager.

Parameters:
url

Absolute HTTP or HTTPS subscription endpoint.

Type:

str

name

Display name; defaults to the endpoint hostname.

Type:

str | None

auto_update

Whether a manager should schedule periodic updates.

Type:

bool

update_interval

Scheduler interval in seconds.

Type:

int

enabled

Whether aggregate queries should include this source.

Type:

bool

priority

Application-defined source priority.

Type:

int

tags

Labels used to select groups of subscriptions.

Type:

list[str]

configs

Parsed configurations from the source.

Type:

list[ConfigMetadata]

id

Stable SHA-256-derived identifier generated from url.

Type:

str

filter_configs(protocols=None, min_success_rate=None, max_latency=None, tags=None, name_contains=None)[source]

Select configuration metadata matching all supplied constraints.

Parameters:
  • protocols (Iterable[str] | None) – Allowed protocol schemes.

  • min_success_rate (float | None) – Inclusive success-rate threshold between 0.0 and 1.0.

  • max_latency (int | float | None) – Inclusive maximum successful latency in milliseconds. Untested configs are excluded.

  • tags (Iterable[str] | None) – At least one tag must match.

  • name_contains (str | None) – Case-insensitive regular expression applied to the human-readable config name.

Returns:

Matching objects in their original order.

Return type:

list[ConfigMetadata]

Raises:

ValueError – If min_success_rate is outside 0..1 or the regular expression is invalid.

classmethod from_dict(value)[source]

Restore a subscription from repository data.

Parameters:

value (dict[str, object]) – JSON-decoded subscription document.

Returns:

A validated source with restored runtime statistics.

Return type:

Subscription

Raises:
  • KeyError – If the required url field is absent.

  • ValueError – If persisted URL or interval values are invalid.

  • TypeError – If persisted fields have incompatible types.

get_configs()[source]

Return original configuration strings in subscription order.

Returns:

A new list containing each stored share URI.

Return type:

list[str]

get_statistics()[source]

Calculate an immutable statistical snapshot of current state.

Returns:

Counts, protocol distribution, update

totals, and average latency for successfully tested configs.

Return type:

SubscriptionStatistics

sort_configs(by='latency', reverse=False)[source]

Return configurations ordered by a supported metadata field.

Parameters:
  • by (str) – One of latency, success_rate, name, or protocol.

  • reverse (bool) – Reverse the selected ordering when true.

Returns:

A new sorted list; the model is not mutated.

Return type:

list[ConfigMetadata]

Raises:

ValueError – If by is not a supported field.

to_dict()[source]

Serialize the complete subscription into JSON-compatible values.

Returns:

Persistent source settings, update state, and

serialized configuration metadata.

Return type:

dict[str, object]

class v2root.ConfigMetadata(config_string, protocol='unknown', name='Unnamed Config', address='unknown', port=0, last_test_time=0, last_latency=-1, success_count=0, failure_count=0, tags=<factory>)[source]

Store parsed identity and historical health data for one share URI.

Parameters:
config_string

Original share URI. It may contain credentials and must not be written to logs without redaction.

Type:

str

protocol

Lowercase protocol scheme such as vless or vmess.

Type:

str

name

Human-readable node label extracted from the URI.

Type:

str

address

Server hostname or IP address without brackets.

Type:

str

port

Remote server port, or 0 when the format omits it.

Type:

int

last_test_time

Unix timestamp of the most recent test.

Type:

float

last_latency

Last successful latency in milliseconds, or -1.

Type:

int

success_count

Number of successful recorded tests.

Type:

int

failure_count

Number of failed recorded tests.

Type:

int

tags

User-defined labels used by subscription filters.

Type:

list[str]

classmethod from_dict(value)[source]

Restore metadata from a persisted dictionary.

Parameters:

value (dict[str, object]) – Serialized metadata. Unknown keys are ignored for forward compatibility.

Returns:

A populated metadata instance.

Return type:

ConfigMetadata

Raises:

TypeError – If required dataclass fields have incompatible values.

get_success_rate()[source]

Calculate the ratio of successful tests to all recorded tests.

Returns:

A value from 0.0 through 1.0. Untested configs return 0.0 rather than raising a division error.

Return type:

float

property tested: bool

Report whether at least one test result has been recorded.

Returns:

True when last_test_time is greater than zero.

Return type:

bool

to_dict()[source]

Serialize this metadata into JSON-compatible primitive values.

Returns:

A new dictionary suitable for JSON persistence.

Mutable collections are copied so callers cannot mutate state through the serialized representation.

Return type:

dict[str, object]

update_test_result(latency, success)[source]

Record the outcome of one connectivity test.

Parameters:
  • latency (int) – Measured latency in milliseconds. The value is stored only when success is true.

  • success (bool) – Whether the test produced a usable connection.

Returns:

The object is updated in place.

Return type:

None

Notes

A failed test stores -1 as last_latency while preserving cumulative success and failure counters.

Errors

v2root.explain_error(error)[source]

Explain one V2Root 2.0 exception using the default catalog.

Parameters:

error (BaseException) – Failure to classify.

Returns:

Presentation-neutral diagnosis.

Return type:

ErrorExplanation

class v2root.ErrorExplanation(code, title, summary, probable_causes, actions, retryable)[source]

A presentation-neutral diagnosis suitable for logs, CLIs, and user interfaces.

Parameters:
format()[source]

Render the diagnosis as readable plain text.

Returns:

Title, summary, probable causes, and numbered actions.

Return type:

str

Logging

class v2root.logger.V2RootLogger(name='v2root')[source]

Manage handlers and convenience methods for the shared package logger.

Parameters:

name (str) – Base logger name. Child loggers inherit its handlers.

Notes

The wrapper does not create files during construction. Applications must call configure() or configure_logger() explicitly.

configure(*, log_level=20, log_to_file=False, log_to_console=True, log_dir=None, max_file_size=5242880, backup_count=3)[source]

Replace package handlers with explicit console and file outputs.

Parameters:
  • log_level (int) – Standard logging threshold such as logging.INFO.

  • log_to_file (bool) – Create a rotating UTF-8 log file when true.

  • log_to_console (bool) – Emit formatted records to stderr when true.

  • log_dir (str | os.PathLike[str] | None) – File logging directory. Platform-specific user storage is used when omitted.

  • max_file_size (int) – Rotation threshold in bytes.

  • backup_count (int) – Number of rotated files to retain.

Returns:

This configured wrapper for fluent setup.

Return type:

V2RootLogger

Raises:
  • ValueError – If size or backup values are negative.

  • OSError – If the log directory or file cannot be created.

critical(msg, *args, **kwargs)[source]

Emit a CRITICAL record.

Parameters:
  • msg (object) – Message or formatting template.

  • *args – Values interpolated by Python logging.

  • **kwargs – Standard logging.Logger.critical options.

Returns:

The record is delegated to the shared logger.

Return type:

None

debug(msg, *args, **kwargs)[source]

Emit a DEBUG record.

Parameters:
  • msg (object) – Message or formatting template.

  • *args – Values interpolated by Python logging.

  • **kwargs – Standard logging.Logger.debug options.

Returns:

The record is delegated to the shared logger.

Return type:

None

error(msg, *args, **kwargs)[source]

Emit an ERROR record.

Parameters:
  • msg (object) – Message or formatting template.

  • *args – Values interpolated by Python logging.

  • **kwargs – Standard logging.Logger.error options.

Returns:

The record is delegated to the shared logger.

Return type:

None

exception(msg, *args, **kwargs)[source]

Emit an ERROR record with the active traceback.

Parameters:
  • msg (object) – Message or formatting template.

  • *args – Values interpolated by Python logging.

  • **kwargs – Standard logging.Logger.exception options.

Returns:

The record is delegated to the shared logger.

Return type:

None

get_logger(name=None)[source]

Return the package logger or one of its named descendants.

Parameters:

name (str | None) – Optional suffix such as core.manager.

Returns:

Shared root logger or v2root.<name> child.

Return type:

logging.Logger

info(msg, *args, **kwargs)[source]

Emit an INFO record.

Parameters:
  • msg (object) – Message or formatting template.

  • *args – Values interpolated by Python logging.

  • **kwargs – Standard logging.Logger.info options.

Returns:

The record is delegated to the shared logger.

Return type:

None

log_function_call(func=None, *, log_args=False, log_result=False, level=10)[source]

Create a decorator that records function entry, exit, and failures.

Parameters:
  • func (Callable[P, R] | None) – Function when used as @decorator.

  • log_args (bool) – Include bounded argument representations.

  • log_result (bool) – Include a bounded result representation.

  • level (int) – Logging level for successful entry and exit messages.

Returns:

Decorated function, or a decorator when func is absent.

Return type:

Callable

Notes

Representations are truncated to reduce accidental credential exposure. Sensitive APIs should still avoid log_args=True.

set_level(level)[source]

Set the threshold on the root logger and every owned handler.

Parameters:

level (int) – Standard numeric Python logging level.

Returns:

Logger and handler levels are updated in place.

Return type:

None

warning(msg, *args, **kwargs)[source]

Emit a WARNING record.

Parameters:
  • msg (object) – Message or formatting template.

  • *args – Values interpolated by Python logging.

  • **kwargs – Standard logging.Logger.warning options.

Returns:

The record is delegated to the shared logger.

Return type:

None

v2root.configure_logger(**kwargs)[source]

Configure the process-wide V2Root logger.

Parameters:

**kwargs – Keyword arguments accepted by V2RootLogger.configure().

Returns:

Configured shared logger wrapper.

Return type:

V2RootLogger

Raises:
  • TypeError – If an unsupported configuration keyword is supplied.

  • ValueError – If rotation settings are invalid.

  • OSError – If requested file logging cannot be initialized.