Coverage for /Users/les/Projects/crackerjack/crackerjack/services/logging.py: 0%

81 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-03 15:39 -0700

1import logging 

2import sys 

3import time 

4import typing as t 

5import uuid 

6from contextvars import ContextVar 

7from pathlib import Path 

8from types import TracebackType 

9from typing import Any 

10 

11import structlog 

12 

13correlation_id: ContextVar[str | None] = ContextVar("correlation_id", default=None) 

14 

15 

16def set_correlation_id(cid: str) -> None: 

17 correlation_id.set(cid) 

18 

19 

20def get_correlation_id() -> str: 

21 cid = correlation_id.get() 

22 if cid is None: 

23 cid = str(uuid.uuid4())[:8] 

24 correlation_id.set(cid) 

25 return cid 

26 

27 

28def add_correlation_id(_: Any, __: Any, event_dict: dict[str, Any]) -> dict[str, Any]: 

29 event_dict["correlation_id"] = get_correlation_id() 

30 return event_dict 

31 

32 

33def add_timestamp(_: Any, __: Any, event_dict: dict[str, Any]) -> dict[str, Any]: 

34 event_dict["timestamp"] = ( 

35 time.strftime("% Y - % m-% dT % H: % M: % S.% f")[:-3] + "Z" 

36 ) 

37 return event_dict 

38 

39 

40def setup_structured_logging( 

41 level: str = "INFO", 

42 json_output: bool = True, 

43 log_file: Path | None = None, 

44) -> None: 

45 processors = [ 

46 structlog.stdlib.filter_by_level, 

47 add_timestamp, 

48 add_correlation_id, 

49 structlog.stdlib.add_logger_name, 

50 structlog.stdlib.add_log_level, 

51 structlog.stdlib.PositionalArgumentsFormatter(), 

52 structlog.processors.StackInfoRenderer(), 

53 structlog.processors.format_exc_info, 

54 ] 

55 

56 if json_output: 

57 processors.append(structlog.processors.JSONRenderer()) 

58 else: 

59 processors.append(structlog.dev.ConsoleRenderer(colors=True)) 

60 

61 structlog.configure( 

62 processors=processors, 

63 wrapper_class=structlog.stdlib.BoundLogger, 

64 logger_factory=structlog.stdlib.LoggerFactory(), 

65 cache_logger_on_first_use=True, 

66 ) 

67 

68 log_level = getattr(logging, level.upper()) 

69 

70 console_handler = logging.StreamHandler(sys.stdout) 

71 console_handler.setLevel(log_level) 

72 

73 handlers = [console_handler] 

74 

75 if log_file: 

76 log_file.parent.mkdir(parents=True, exist_ok=True) 

77 file_handler = logging.FileHandler(log_file) 

78 file_handler.setLevel(log_level) 

79 handlers.append(file_handler) 

80 

81 logging.basicConfig( 

82 level=log_level, 

83 handlers=handlers, 

84 format="%(message)s", 

85 ) 

86 

87 

88def get_logger(name: str) -> structlog.BoundLogger: 

89 return structlog.get_logger(name) 

90 

91 

92class LoggingContext: 

93 def __init__(self, operation: str, **kwargs: Any) -> None: 

94 self.operation = operation 

95 self.kwargs = kwargs 

96 self.correlation_id = str(uuid.uuid4())[:8] 

97 self.logger = get_logger("crackerjack.context") 

98 self.start_time = time.time() 

99 

100 def __enter__(self) -> str: 

101 set_correlation_id(self.correlation_id) 

102 self.logger.info("Operation started", operation=self.operation, **self.kwargs) 

103 return self.correlation_id 

104 

105 def __exit__( 

106 self, 

107 exc_type: type[BaseException] | None, 

108 exc_val: BaseException | None, 

109 _: TracebackType | None, 

110 ) -> None: 

111 duration = time.time() - self.start_time 

112 

113 if exc_type is None: 

114 self.logger.info( 

115 "Operation completed", 

116 operation=self.operation, 

117 duration_seconds=round(duration, 3), 

118 **self.kwargs, 

119 ) 

120 else: 

121 self.logger.error( 

122 "Operation failed", 

123 operation=self.operation, 

124 duration_seconds=round(duration, 3), 

125 error=str(exc_val), 

126 error_type=exc_type.__name__ if exc_type else None, 

127 **self.kwargs, 

128 ) 

129 

130 

131def log_performance( 

132 operation: str, 

133 **kwargs: Any, 

134) -> t.Callable[[t.Callable[..., t.Any]], t.Callable[..., t.Any]]: 

135 def decorator(func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]: 

136 def wrapper(*args: t.Any, **func_kwargs: t.Any) -> t.Any: 

137 logger = get_logger(f"crackerjack.perf.{func.__name__}") 

138 start_time = time.time() 

139 

140 try: 

141 result = func(*args, **func_kwargs) 

142 duration = time.time() - start_time 

143 logger.info( 

144 "Function completed", 

145 operation=operation, 

146 function=func.__name__, 

147 duration_seconds=round(duration, 3), 

148 success=True, 

149 **kwargs, 

150 ) 

151 return result 

152 except Exception as e: 

153 duration = time.time() - start_time 

154 logger.exception( 

155 "Function failed", 

156 operation=operation, 

157 function=func.__name__, 

158 duration_seconds=round(duration, 3), 

159 success=False, 

160 error=str(e), 

161 error_type=type(e).__name__, 

162 **kwargs, 

163 ) 

164 raise 

165 

166 return wrapper 

167 

168 return decorator 

169 

170 

171hook_logger = get_logger("crackerjack.hooks") 

172test_logger = get_logger("crackerjack.tests") 

173config_logger = get_logger("crackerjack.config") 

174cache_logger = get_logger("crackerjack.cache") 

175security_logger = get_logger("crackerjack.security") 

176performance_logger = get_logger("crackerjack.performance")