Coverage for jutil/logs.py: 36%

# Coverage for jutil/logs.py : 36%

## 16 statements

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1 import json

2 import logging

3 from typing import Optional, Dict, Any, Union

4 from django.http.request import HttpRequest

5 from rest_framework.request import Request

6 from jutil.request import get_ip

7

8

9 logger = logging.getLogger(__name__)

10

11

12 def log_event(name: str, request: Optional[Union[HttpRequest, Request]] = None,

13 data: Optional[Dict[str, Any]] = None, ip: str = ''):

14 """

15 Logs consistent event for easy parsing/analysis.

16 Format: EVENT_<UPPERCASE_NAME>: <JSON object>

17 :param name: Name of the event. Will be logged as EVENT_XXX with XXX in capitals.

18 :param request: Django REST framework Request (optional)

19 :param data: Even data (optional)

20 :param ip: Even IP (optional)

21 """

22 log_data: Dict[str, Any] = {}

23 if not ip and request:

24 ip = get_ip(request)[0]

25 if ip:

26 log_data['ip'] = ip

27 if data:

28 log_data['data'] = data

29 logger.info('EVENT_%s: %s', name.upper(), json.dumps(log_data))