Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add optional param for passing a custom logger to ChargePoint #641

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 deletions ocpp/charge_point.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ class ChargePoint:
initiated and received by the Central System
"""

def __init__(self, id, connection, response_timeout=30):
def __init__(self, id, connection, response_timeout=30, logger=LOGGER):
"""

Args:
Expand All @@ -206,7 +206,9 @@ def __init__(self, id, connection, response_timeout=30):
connection: Connection to CP.
response_timeout (int): When no response on a request is received
within this interval, a asyncio.TimeoutError is raised.

logger (logging.Logger): The logger used to log messages. By default, it
logs to the 'ocpp' logger. This can be customized by passing a different
logger instance.
"""
self.id = id

Expand Down Expand Up @@ -234,10 +236,13 @@ def __init__(self, id, connection, response_timeout=30):
# for testing purposes to have predictable unique ids.
self._unique_id_generator = uuid.uuid4

# The logger used to log messages. By default it logs to the 'ocpp'
self.logger = logger

async def start(self):
while True:
message = await self._connection.recv()
LOGGER.info("%s: receive message %s", self.id, message)
self.logger.info("%s: receive message %s", self.id, message)

await self.route_message(message)

Expand All @@ -252,7 +257,7 @@ async def route_message(self, raw_msg):
try:
msg = unpack(raw_msg)
except OCPPError as e:
LOGGER.exception(
self.logger.exception(
"Unable to parse message: '%s', it doesn't seem "
"to be valid OCPP: %s",
raw_msg,
Expand All @@ -264,7 +269,7 @@ async def route_message(self, raw_msg):
try:
await self._handle_call(msg)
except OCPPError as error:
LOGGER.exception("Error while handling request '%s'", msg)
self.logger.exception("Error while handling request '%s'", msg)
response = msg.create_call_error(error).to_json()
await self._send(response)

Expand Down Expand Up @@ -315,7 +320,7 @@ async def _handle_call(self, msg):
if inspect.isawaitable(response):
response = await response
except Exception as e:
LOGGER.exception("Error while handling request '%s'", msg)
self.logger.exception("Error while handling request '%s'", msg)
response = msg.create_call_error(e).to_json()
await self._send(response)

Expand Down Expand Up @@ -362,7 +367,7 @@ async def _handle_call(self, msg):
return response

async def call(
self, payload, suppress=True, unique_id=None, skip_schema_validation=False
self, payload, suppress=True, unique_id=None, skip_schema_validation=False
):
"""
Send Call message to client and return payload of response.
Expand Down Expand Up @@ -423,7 +428,7 @@ async def call(
)

if response.message_type_id == MessageType.CallError:
LOGGER.warning("Received a CALLError: %s'", response)
self.logger.warning("Received a CALLError: %s'", response)
if suppress:
return
raise response.to_exception()
Expand Down Expand Up @@ -454,7 +459,7 @@ async def _get_specific_response(self, unique_id, timeout):
if response.unique_id == unique_id:
return response

LOGGER.error("Ignoring response with unknown unique id: %s", response)
self.logger.error("Ignoring response with unknown unique id: %s", response)
timeout_left = wait_until - time.time()

if timeout_left < 0:
Expand All @@ -463,5 +468,5 @@ async def _get_specific_response(self, unique_id, timeout):
return await self._get_specific_response(unique_id, timeout_left)

async def _send(self, message):
LOGGER.info("%s: send %s", self.id, message)
self.logger.info("%s: send %s", self.id, message)
await self._connection.send(message)
15 changes: 15 additions & 0 deletions tests/test_charge_point.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
from dataclasses import asdict

import pytest
Expand Down Expand Up @@ -472,3 +473,17 @@ def after_boot_notification(self, *args, **kwargs):
assert ChargerA.after_boot_notification_call_count == 1
assert ChargerB.on_boot_notification_call_count == 1
assert ChargerB.after_boot_notification_call_count == 1


def test_custom_logger():
class ChargePoint(cp_201):
pass

# Create a custom logger
custom_logger = logging.getLogger("custom_logger")

# Create a ChargePoint instance with the custom logger
charge_point = ChargePoint(id="123", connection=None, logger=custom_logger)

# Check if the logger of the instance is the custom logger
assert charge_point.logger is custom_logger
Loading