Skip to content

Logging↲

The pyvesync library uses Python's standard logging module with the logger name pyvesync. The LibraryLogger class in pyvesync.utils.logs provides structured logging with automatic context (module and class name) and helper methods for API call logging.

pyvesync.utils.logs.LibraryLogger ↲

Library Logging Interface.

LibraryLogger provides a logging interface that automatically adds context (module and class name) and offers helper methods for structured logging, such as API call logs.

Attributes:

Name Type Description
debug bool

Class attribute to enable or disable debug logging, prints API requests & responses that return an error.

shouldredact bool

Class attribute whether to redact sensitive information from logs.

verbose bool

Class attribute to print all request & response content.

Examples:

Logging an API call:

>>> LibraryLogger.log_api_call(logger, response)
    2025-02-01 12:34:56 - DEBUG - my_library - ========API CALL========
    API CALL to endpoint: /api/v1/resource
    Method: POST
    Request Headers:
    {
        REQUEST HEADERS
    }
    Request Body:
        {
            "key": "value"
        }
    Response Body:
        {
            RESPONSE BODY
        }

Logging an API exception:

>>> LibraryLogger.log_api_exception(logger, request_dict, exception)
    2025-02-01 12:34:56 - DEBUG - pyvesync -
    Error in API CALL to endpoint: /api/v1/resource
    Response Status: 500
    Exception: <Exception>
    Method: POST
    Request Headers:
        {
            REQUEST HEADERS
        }
    Request Body:
        {
            "key": "value"
        }

Attributes↲

debug_enabled class-attribute instance-attribute ↲

debug_enabled = False

Class attribute to cache status of debug logging to avoid expensive calls.

shouldredact class-attribute instance-attribute ↲

shouldredact = True

Class attribute to determine if sensitive information should be redacted.

verbose class-attribute instance-attribute ↲

verbose = False

Class attribute to print all request & response content.

Functions↲

api_printer classmethod ↲

api_printer(
    api: Mapping | bytes | str | None,
) -> str | None

Print the API dictionary in a readable format.

check_debug classmethod ↲

check_debug() -> bool

Check if debug logging is enabled.

configure_file_logging staticmethod ↲

configure_file_logging(
    log_file: str | Path,
    *,
    level: str | int = INFO,
    stdout: bool = True,
    propagate: bool = False,
) -> None

Configure logging for pyvesync library.

Parameters:

Name Type Description Default
log_file str | Path | None

The name of the file to log to. If None, logs will only be printed to the console.

required
level str | int

The log level to set the logger to, can be in form of enum logging.DEBUG or string DEBUG.

INFO
stdout bool

If True, log messages will also be printed to stdout.

True
propagate bool

If True, log messages will propagate to the root logger.

False
Note

This method configures the pyvesync base logger and sets propagation of log messages to the root logger based on the propagate parameter.

error_device_response_code classmethod ↲

error_device_response_code(
    logger: Logger,
    device: VeSyncBaseDevice,
    method_name: str,
    code: int | str,
    msg: str,
) -> None

Log an error response from a device API call.

Use this log message to indicate that a device API call returned a response with an error.

Parameters:

Name Type Description Default
logger Logger

module logger

required
device VeSyncBaseDevice

device instance

required
method_name str

device method name

required
code int | str

error code returned

required
msg str

error message

required

error_device_response_content classmethod ↲

error_device_response_content(
    logger: Logger,
    device: VeSyncBaseDevice,
    method: str,
    msg: str | None = None,
) -> None

Log an error parsing API response.

Use this log message to indicate that the API response is not in the expected format.

Parameters:

Name Type Description Default
logger Logger

module logger

required
device VeSyncBaseDevice

device instance

required
method str

method that caused the error

required
msg str | None

optional description of error

None

error_mashumaro_response classmethod ↲

error_mashumaro_response(
    logger: Logger,
    method_name: str,
    resp_dict: dict,
    exc: MissingField
    | InvalidFieldValue
    | UnserializableField,
    device: VeSyncBaseDevice | None = None,
) -> None

Log an error parsing API response.

Use this log message to indicate that the API response is not in the expected format.

Parameters:

Name Type Description Default
logger Logger

module logger

required
method_name str

device name

required
resp_dict dict

API response dictionary

required
exc MissingField | InvalidFieldValue | UnserializableField

mashumaro exception caught

required
device VeSyncBaseDevice | None

device if a device method was called

None

is_json staticmethod ↲

is_json(data: str | bytes | None) -> bool

Check if the data is JSON formatted.

log_api_call classmethod ↲

log_api_call(
    logger: Logger,
    response: ClientResponse,
    response_body: bytes | None = None,
    request_headers: dict | None = None,
    request_body: str | dict | None = None,
) -> None

Log API calls in debug mode.

Logs an API call with a specific format that includes the endpoint, JSON-formatted headers, request body (if any) and response body.

Parameters:

Name Type Description Default
logger Logger

The logger instance to use.

required
response ClientResponse

Requests response object from the API call.

required
response_body bytes

The response body to log.

None
request_headers dict

The request headers to log.

None
request_body dict | str

The request body to log.

None
Notes

This is a method used for the logging of API calls when the debug flag is enabled. The method logs the endpoint, method, request headers, request body (if any), response headers, and response body (if any).

log_api_exception classmethod ↲

log_api_exception(
    logger: Logger,
    *,
    exception: ClientResponseError,
    request_body: dict | None,
) -> None

Log asyncio response exceptions.

Logs an API call with a specific format that includes the endpoint, JSON-formatted headers, request body (if any) and response body.

Parameters:

Name Type Description Default
logger Logger

The logger instance to use.

required
exception ClientResponseError

KW only, The request body to log.

required
request_body dict | None

KW only, The request body.

required

log_api_status_error classmethod ↲

log_api_status_error(
    logger: Logger, *, response: ClientResponse
) -> None

Log API response with non-200 status codes.

Parameters:

Name Type Description Default
logger Logger

The logger instance to use.

required
response ClientResponse

KW only, dictionary containing the request information.

required

log_device_return_code classmethod ↲

log_device_return_code(
    logger: Logger,
    method: str,
    device_name: str,
    device_type: str,
    error_info: ResponseInfo,
) -> None

Log return code from device API call.

When API responds with JSON, if the code key is not 0, it indicates an error has occurred.

Parameters:

Name Type Description Default
logger Logger

module logger instance

required
method str

method that caused the error

required
device_name str

device name

required
device_type str

device type

required
error_info ResponseInfo

response info dataclass

required

redactor classmethod ↲

redactor(stringvalue: str) -> str

Redact sensitive strings from debug output.

This method searches for specific sensitive keys in the input string and replaces their values with '##REDACTED##'. The keys that are redacted include:

  • token
  • authorizeCode
  • password
  • email
  • tk
  • accountId
  • authKey
  • uuid
  • cid

Parameters:

Name Type Description Default
stringvalue str

The input string potentially containing sensitive information.

required

Returns:

Name Type Description
str str

The redacted string with sensitive information replaced by '##REDACTED##'.

set_log_level staticmethod ↲

set_log_level(level: str | int = WARNING) -> None

Set log level for logger to INFO.

try_json_loads staticmethod ↲

try_json_loads(data: str | bytes | None) -> dict | None

Try to load JSON data.

Gracefully handle errors and return None if loading fails.

Parameters:

Name Type Description Default
data str | bytes | None

JSON data to load.

required

Returns:

Type Description
dict | None

dict | None: Parsed JSON data or None if loading fails.

Enabling Debug Logging↲

Debug logging can be enabled through the VeSync manager or directly via Python's logging module:

import logging
from pyvesync import VeSync

# Option 1: Set the pyvesync logger level directly
vs_logger = logging.getLogger("pyvesync")
vs_logger.setLevel(logging.DEBUG)

# Option 2: Use the manager's debug property
async with VeSync(username="EMAIL", password="PASSWORD") as manager:
    manager.debug = True

Logging to a File↲

For verbose debugging, the manager provides a helper to log to a file:

async with VeSync(username="EMAIL", password="PASSWORD") as manager:
    manager.log_to_file("debug.log", stdout=True)
    # stdout=True will also print to the console

Redacting Sensitive Information↲

By default, the library redacts sensitive information (tokens, account IDs) from log output. This can be controlled via the redact parameter on the VeSync constructor or the redact property:

# Redaction is enabled by default
async with VeSync(username="EMAIL", password="PASSWORD", redact=True) as manager:
    manager.redact = False  # Disable redaction for debugging