Skip to content

Commit 039dee5

Browse files
authored
Merge pull request #745 from NHSDigital/DTOSS-11680-completed-event
DTOSS-11680: Standardise completed logging for Commands
2 parents db78ef0 + aa26c22 commit 039dee5

22 files changed

+174
-148
lines changed

manage_breast_screening/notifications/management/commands/create_appointments.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
import pandas
77
from django.core.management.base import BaseCommand
88

9-
from manage_breast_screening.notifications.management.commands.helpers.exception_handler import (
10-
exception_handler,
9+
from manage_breast_screening.notifications.management.commands.helpers.command_handler import (
10+
CommandHandler,
1111
)
1212
from manage_breast_screening.notifications.models import (
1313
ZONE_INFO,
@@ -18,7 +18,7 @@
1818
from manage_breast_screening.notifications.services.blob_storage import BlobStorage
1919

2020
DIR_NAME_DATE_FORMAT = "%Y-%m-%d"
21-
INSIGHTS_ERROR_NAME = "CreateAppointmentsError"
21+
INSIGHTS_JOB_NAME = "CreateAppointments"
2222
logger = getLogger(__name__)
2323

2424

@@ -37,7 +37,7 @@ def add_arguments(self, parser):
3737
)
3838

3939
def handle(self, *args, **options):
40-
with exception_handler(INSIGHTS_ERROR_NAME):
40+
with CommandHandler.handle(INSIGHTS_JOB_NAME):
4141
logger.info("Create Appointments command started")
4242
container_client = BlobStorage().find_or_create_container(
4343
os.getenv("BLOB_CONTAINER_NAME", "")
@@ -63,7 +63,6 @@ def handle(self, *args, **options):
6363
row, clinic
6464
)
6565
logger.info("Processed %s rows from %s", len(data_frame), blob.name)
66-
logger.info("Create Appointments command finished successfully")
6766

6867
def is_not_holding_clinic(self, row):
6968
return row.get("Holding Clinic") != "Y"

manage_breast_screening/notifications/management/commands/create_reports.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,16 @@
55
from django.core.management.base import BaseCommand
66
from django.db import connection
77

8-
from manage_breast_screening.notifications.management.commands.helpers.exception_handler import (
9-
exception_handler,
8+
from manage_breast_screening.notifications.management.commands.helpers.command_handler import (
9+
CommandHandler,
1010
)
1111
from manage_breast_screening.notifications.models import ZONE_INFO
1212
from manage_breast_screening.notifications.queries.helper import Helper
1313
from manage_breast_screening.notifications.services.blob_storage import BlobStorage
1414
from manage_breast_screening.notifications.services.nhs_mail import NhsMail
1515

1616
logger = getLogger(__name__)
17-
INSIGHTS_ERROR_NAME = "CreateReportsError"
17+
INSIGHTS_JOB_NAME = "CreateReports"
1818

1919

2020
class ReportConfig:
@@ -58,7 +58,7 @@ def add_arguments(self, parser):
5858
parser.add_argument("--smoke-test", action="store_true")
5959

6060
def handle(self, *args, **options):
61-
with exception_handler(INSIGHTS_ERROR_NAME):
61+
with CommandHandler.handle(INSIGHTS_JOB_NAME):
6262
logger.info("Create Report Command started")
6363

6464
bso_codes, report_configs = self.configuration(options)
@@ -86,8 +86,6 @@ def handle(self, *args, **options):
8686
NhsMail().send_reports_email(external_reports)
8787
logger.info(f"Reports sent: {', '.join(external_reports.keys())}")
8888

89-
logger.info("Create Report Command finished")
90-
9189
def configuration(self, options: dict) -> tuple[list[str], list[ReportConfig]]:
9290
if options.get("smoke_test", False):
9391
bso_codes = [self.SMOKE_TEST_BSO_CODE]
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from contextlib import contextmanager
2+
3+
from django.core.management.base import CommandError
4+
5+
from manage_breast_screening.notifications.services.application_insights_logging import (
6+
ApplicationInsightsLogging,
7+
)
8+
9+
10+
class CommandHandler:
11+
@contextmanager
12+
@staticmethod
13+
def handle(command_name):
14+
try:
15+
yield
16+
ApplicationInsightsLogging().custom_event_info(
17+
event_name=f"{command_name}Completed",
18+
message=f"{command_name} completed successfully",
19+
)
20+
except Exception as e:
21+
ApplicationInsightsLogging().exception(f"{command_name}Error: {e}")
22+
raise CommandError(e)

manage_breast_screening/notifications/management/commands/helpers/exception_handler.py

Lines changed: 0 additions & 16 deletions
This file was deleted.

manage_breast_screening/notifications/management/commands/helpers/message_batch_helpers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ def mark_batch_as_failed(
6161
response.status_code,
6262
response.text,
6363
)
64-
ApplicationInsightsLogging().custom_event(
64+
ApplicationInsightsLogging().custom_event_warning(
6565
message=log_msg,
6666
event_name="batch_marked_as_failed",
6767
)

manage_breast_screening/notifications/management/commands/retry_failed_message_batch.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44

55
from django.core.management.base import BaseCommand, CommandError
66

7-
from manage_breast_screening.notifications.management.commands.helpers.exception_handler import (
8-
exception_handler,
7+
from manage_breast_screening.notifications.management.commands.helpers.command_handler import (
8+
CommandHandler,
99
)
1010
from manage_breast_screening.notifications.management.commands.helpers.message_batch_helpers import (
1111
MessageBatchHelpers,
@@ -18,7 +18,7 @@
1818
from manage_breast_screening.notifications.services.queue import Queue
1919

2020
logger = getLogger(__name__)
21-
INSIGHTS_ERROR_NAME = "RetryFailedMessageBatchError"
21+
INSIGHTS_JOB_NAME = "RetryFailedMessageBatch"
2222

2323

2424
class Command(BaseCommand):
@@ -28,7 +28,7 @@ class Command(BaseCommand):
2828
"""
2929

3030
def handle(self, *args, **options):
31-
with exception_handler(INSIGHTS_ERROR_NAME):
31+
with CommandHandler.handle(INSIGHTS_JOB_NAME):
3232
logger.info("Retry Failed Message Batch Command started")
3333
queue = Queue.RetryMessageBatches()
3434
logger.debug("Retry queue items: %s", queue.peek())

manage_breast_screening/notifications/management/commands/save_message_status.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
from django.core.exceptions import ValidationError
66
from django.core.management.base import BaseCommand
77

8-
from manage_breast_screening.notifications.management.commands.helpers.exception_handler import (
9-
exception_handler,
8+
from manage_breast_screening.notifications.management.commands.helpers.command_handler import (
9+
CommandHandler,
1010
)
1111
from manage_breast_screening.notifications.models import (
1212
ChannelStatus,
@@ -15,7 +15,7 @@
1515
)
1616
from manage_breast_screening.notifications.services.queue import Queue
1717

18-
INSIGHTS_ERROR_NAME = "SaveMessageStatusError"
18+
INSIGHTS_JOB_NAME = "SaveMessageStatus"
1919
logger = getLogger(__name__)
2020

2121

@@ -26,7 +26,7 @@ class Command(BaseCommand):
2626
"""
2727

2828
def handle(self, *args, **options):
29-
with exception_handler(INSIGHTS_ERROR_NAME):
29+
with CommandHandler.handle(INSIGHTS_JOB_NAME):
3030
logger.info("Save Message Status Command started")
3131
queue = Queue.MessageStatusUpdates()
3232
for item in queue.items():

manage_breast_screening/notifications/management/commands/send_message_batch.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@
22
from logging import getLogger
33

44
from business.calendar import Calendar
5-
from django.core.management.base import BaseCommand, CommandError
5+
from django.core.management.base import BaseCommand
66

7+
from manage_breast_screening.notifications.management.commands.helpers.command_handler import (
8+
CommandHandler,
9+
)
710
from manage_breast_screening.notifications.management.commands.helpers.message_batch_helpers import (
811
MessageBatchHelpers,
912
)
@@ -18,11 +21,8 @@
1821
MessageBatchStatusChoices,
1922
)
2023
from manage_breast_screening.notifications.services.api_client import ApiClient
21-
from manage_breast_screening.notifications.services.application_insights_logging import (
22-
ApplicationInsightsLogging,
23-
)
2424

25-
INSIGHTS_ERROR_NAME = "SendMessageBatchError"
25+
INSIGHTS_JOB_NAME = "SendMessageBatch"
2626
logger = getLogger(__name__)
2727

2828

@@ -33,11 +33,8 @@ class Command(BaseCommand):
3333
"""
3434

3535
def handle(self, *args, **options):
36-
try:
36+
with CommandHandler.handle(INSIGHTS_JOB_NAME):
3737
return self.send_message_batch()
38-
except Exception as e:
39-
ApplicationInsightsLogging().exception(f"{INSIGHTS_ERROR_NAME}: {e}")
40-
raise CommandError(e)
4138

4239
def send_message_batch(self):
4340
logger.info("Send Message Batch Command started")

manage_breast_screening/notifications/management/commands/store_mesh_messages.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,14 @@
33

44
from django.core.management.base import BaseCommand
55

6-
from manage_breast_screening.notifications.management.commands.helpers.exception_handler import (
7-
exception_handler,
6+
from manage_breast_screening.notifications.management.commands.helpers.command_handler import (
7+
CommandHandler,
88
)
99
from manage_breast_screening.notifications.services.blob_storage import BlobStorage
1010
from manage_breast_screening.notifications.services.mesh_inbox import MeshInbox
1111

1212
logger = getLogger(__name__)
13-
INSIGHTS_ERROR_NAME = "StoreMeshMessagesError"
13+
INSIGHTS_JOB_NAME = "StoreMeshMessages"
1414

1515

1616
class Command(BaseCommand):
@@ -20,7 +20,7 @@ class Command(BaseCommand):
2020
"""
2121

2222
def handle(self, *args, **options):
23-
with exception_handler(INSIGHTS_ERROR_NAME):
23+
with CommandHandler.handle(INSIGHTS_JOB_NAME):
2424
logger.info("Store MESH Messages command started")
2525
today_dirname = datetime.today().strftime("%Y-%m-%d")
2626
with MeshInbox() as inbox:
@@ -38,5 +38,3 @@ def handle(self, *args, **options):
3838
inbox.acknowledge(message_id)
3939

4040
logger.info("Message %s acknowledged", message_id)
41-
42-
logger.info("Store MESH Messages command completed successfully")

manage_breast_screening/notifications/services/application_insights_logging.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,20 @@ def getLogger(self):
3333
def exception(self, exception_name: str):
3434
self.logger.exception(exception_name, stack_info=True)
3535

36-
def custom_event(self, message: str, event_name: str):
36+
def custom_event_warning(self, message: str, event_name: str):
3737
self.logger.warning(
3838
message,
3939
extra={
4040
"microsoft.custom_event.name": event_name,
4141
"additional_attrs": message,
4242
},
4343
)
44+
45+
def custom_event_info(self, message: str, event_name: str):
46+
self.logger.info(
47+
message,
48+
extra={
49+
"microsoft.custom_event.name": event_name,
50+
"additional_attrs": message,
51+
},
52+
)

0 commit comments

Comments
 (0)