Skip to content

Commit 94b6fd4

Browse files
author
Arun Persaud
committed
Replace print statements with proper logging throughout library
1 parent 8cceb36 commit 94b6fd4

File tree

5 files changed

+70
-9
lines changed

5 files changed

+70
-9
lines changed

.coverage

52 KB
Binary file not shown.

Readme.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,53 @@ time.sleep(1)
3131
laser.off()
3232
```
3333

34+
## Logging Configuration
35+
36+
The vortran library uses Python's standard logging module. By default, no log messages are shown. To see log output, configure logging in your application:
37+
38+
### Basic Logging Setup
39+
40+
```python
41+
import logging
42+
import vortran
43+
44+
# Show INFO level and above (device discovery, connections)
45+
logging.basicConfig(level=logging.INFO)
46+
47+
# Or show DEBUG level for detailed USB communication
48+
logging.basicConfig(level=logging.DEBUG)
49+
50+
lasers = vortran.get_lasers() # Will now show log messages
51+
```
52+
53+
### Advanced Logging Configuration
54+
55+
```python
56+
import logging
57+
import vortran
58+
59+
# Configure specific logger levels
60+
logging.getLogger('vortran.usb').setLevel(logging.INFO) # USB device discovery
61+
logging.getLogger('vortran.laser').setLevel(logging.DEBUG) # Laser operations
62+
logging.getLogger('vortran.usb_connection').setLevel(logging.WARNING) # Only errors
63+
64+
# Custom formatter
65+
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
66+
handler = logging.StreamHandler()
67+
handler.setFormatter(formatter)
68+
69+
logger = logging.getLogger('vortran')
70+
logger.addHandler(handler)
71+
logger.setLevel(logging.DEBUG)
72+
```
73+
74+
### Log Levels
75+
76+
- **DEBUG**: Detailed USB communication, retry attempts
77+
- **INFO**: Device discovery, connection status
78+
- **WARNING**: Parse errors, failed operations with retries
79+
- **ERROR**: Connection failures, USB communication errors
80+
3481
## Configuration
3582

3683
### USB Library Configuration (Windows only)

src/vortran/laser.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
from enum import IntFlag
22
from typing import Any
3+
import logging
34

45
from .usb_connection import USB_ReadWrite
56
from .usb import get_usb_ports, VortranDevice
67
from .parser import parse_output, verify_result
78

9+
logger = logging.getLogger(__name__)
10+
811

912
class LaserStatus(IntFlag):
1013
EMISSION_ACTIVE = 0
@@ -197,7 +200,7 @@ def send_query(self, command: str, alt_list: list[str] = []) -> str | None:
197200
if (result is not None) and (verify_result(result, verify_list) == True):
198201
data = result
199202
else: # if result is None or not verified, ask again
200-
print("trying second query")
203+
logger.debug("Query failed, trying second attempt for command: %s", command)
201204
second_try = self.send_usb(command)
202205
if (second_try is not None) and (
203206
verify_result(second_try, verify_list) == True
@@ -225,7 +228,7 @@ def get_lasers() -> list[Laser]:
225228
manager = device
226229
else:
227230
lasers.append(device)
228-
print("Attaching Endpoint", device)
231+
logger.info("Found laser device: %s", device)
229232

230233
my_timeout = 500
231234
my_retries = 0

src/vortran/usb.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from pathlib import Path
44
import os
55
import site
6+
import logging
67

78
# Note: these are imports from pyusb
89
import usb.core
@@ -11,6 +12,8 @@
1112
import re
1213
import platform
1314

15+
logger = logging.getLogger(__name__)
16+
1417

1518
@dataclass
1619
class VortranDevice:
@@ -193,13 +196,13 @@ def parse_bus_and_address(text: str) -> tuple[int | None, int | None]:
193196
try:
194197
bus = int(tmp_match_bus.groups()[0])
195198
except ValueError:
196-
print("Unable to get a bus in utility get_usb_ports")
199+
logger.warning("Failed to parse bus number from USB string: %s", text)
197200

198201
if tmp_match_address:
199202
if len(tmp_match_address.groups()) == 1:
200203
try:
201204
address = int(tmp_match_address.groups()[0])
202205
except ValueError:
203-
print("Unable to get a bus in utility get_usb_ports")
206+
logger.warning("Failed to parse address from USB string: %s", text)
204207

205208
return bus, address

src/vortran/usb_connection.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111

1212
from .usb import VortranDevice, get_usb_backend
1313

14+
logger = logging.getLogger(__name__)
15+
1416

1517
class USB_ReadWrite:
1618
SET_CMD_QUERY = bytes([0xA0])
@@ -104,23 +106,29 @@ def open_connection(self) -> bool:
104106
self.logger.log.info(msg_out)
105107

106108
except Exception as e:
107-
print(repr(e))
109+
logger.error("USB connection failed: %s", repr(e))
108110
if self.logger:
109111
self.logger.log.error(repr(e))
110112

111113
num_attempts += 1
112114
if num_attempts <= self.retries:
113-
msg_out = "Retrying connection to USB Vendor_ID={self.vendor_id}, Product_ID={self.product_id}. Attempt {num_attempts} of {self.retries}"
114-
print(msg_out)
115+
logger.warning(
116+
"Retrying USB connection (Vendor=%04x, Product=%04x). Attempt %d of %d",
117+
self.vendor_id,
118+
self.product_id,
119+
num_attempts,
120+
self.retries,
121+
)
115122
if self.logger:
123+
msg_out = f"Retrying connection to USB Vendor_ID={self.vendor_id}, Product_ID={self.product_id}. Attempt {num_attempts} of {self.retries}"
116124
self.logger.log.warning(msg_out)
117125
return is_connection_open
118126

119127
def read_usb(self, timeout: int, include_first_byte: bool = False) -> str | None:
120128
try:
121129
data = self.connection.read(0x81, 64, timeout)
122130
except usb.core.USBError as e:
123-
print(f"Error reading response: {e.args}: {str(timeout)}")
131+
logger.error("USB read error (timeout=%s): %s", timeout, e.args)
124132
return None
125133

126134
if include_first_byte:
@@ -180,4 +188,4 @@ def send_usb(self, cmd: str, writeOnly: bool = False) -> str | None:
180188
return response
181189

182190
except usb.core.USBError as e:
183-
print(repr(e.args))
191+
logger.error("USB communication error: %s", repr(e.args))

0 commit comments

Comments
 (0)