1 import logging

2 import os

3

4 import structlog

5

6

7 def configure_structlog():

8 if os.getenv("PRETTY_PRINT_LOG", default="false").lower() in ["true", "1", "yes"]:

9 processors = [

10 structlog.contextvars.merge_contextvars,

11 structlog.processors.add_log_level,

12 structlog.processors.StackInfoRenderer(),

13 structlog.dev.set_exc_info,

14 structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S", utc=False),

15 structlog.dev.ConsoleRenderer(),

16 ]

17 else:

18 processors = [

19 structlog.contextvars.merge_contextvars,

20 structlog.processors.add_log_level,

21 structlog.processors.StackInfoRenderer(),

22 structlog.dev.set_exc_info,

23 structlog.processors.JSONRenderer(),

24 ]

25 structlog.configure(

26 processors=processors,

27 wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),

28 context_class=dict,

29 logger_factory=structlog.PrintLoggerFactory(),

30 cache_logger_on_first_use=False,

31 )

32

33

34 def setup_logging():

35 LOGGING = {

36 "version": 1,

37 "disable_existing_loggers": False,

38 "formatters": {

39 "json_formatter": {

40 "()": structlog.stdlib.ProcessorFormatter,

41 "processor": structlog.processors.JSONRenderer(),

42 },

43 "plain_console": {

44 "()": structlog.stdlib.ProcessorFormatter,

45 "processor": structlog.dev.ConsoleRenderer(),

46 },

47 "key_value": {

48 "()": structlog.stdlib.ProcessorFormatter,

49 "processor": structlog.processors.KeyValueRenderer(

50 key_order=["timestamp", "level", "event", "logger"]

51 ),

52 },

53 },

54 "handlers": {

55 "console": {

56 "class": "logging.StreamHandler",

57 "formatter": "plain_console"

58 if os.getenv("PRETTY_PRINT_LOG", "false").lower()

59 in ["true", "1", "yes"]

60 else "json_formatter",

61 },

62 },

63 "loggers": {

64 "django": {

65 "handlers": ["console"],

66 "level": "INFO",

67 },

68 "django.server": {

69 "handlers": ["console"],

70 "level": "INFO",

71 },

72 "django.db.backends": {

73 "handlers": ["console"],

74 "level": "INFO",

75 },

76 },

77 }

78 return LOGGING