Coverage for src/srunx/logging.py: 35%

1"""Centralized logging configuration for srunx."""

2

3 import sys

4

5 from loguru import logger

6 from loguru._logger import Logger

7

8

9 def configure_logging(

10 level: str = "INFO",

11 format_string: str | None = None,

12 show_time: bool = True,

13 show_level: bool = True,

14 colorize: bool = True,

15) -> None:

16 """Configure loguru logging for srunx.

17

18 Args:

19 level: Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL).

20 format_string: Custom format string. If None, uses default format.

21 show_time: Whether to show timestamp in logs.

22 show_level: Whether to show log level in logs.

23 colorize: Whether to colorize the output.

24 """

25 # Remove default logger

26 logger.remove()

27

28 # Build format string

29 if format_string is None:

30 format_parts = []

31 if show_time:

32 format_parts.append("<green>{time:YYYY-MM-DD HH:mm:ss}</green>")

33 if show_level:

34 format_parts.append("<level>{level: <8}</level>")

35 format_parts.append(

36 "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan>"

37 )

38 format_parts.append("<level>{message}</level>")

39 format_string = " | ".join(format_parts)

40

41 # Add stderr handler

42 logger.add(

43 sys.stderr,

44 format=format_string,

45 level=level,

46 colorize=colorize,

47 backtrace=True,

48 diagnose=True,

49 )

50

51

52 def configure_cli_logging(level: str = "INFO", quiet: bool = False) -> None:

53 """Configure logging specifically for CLI usage.

54

55 Args:

56 level: Logging level.

57 quiet: If True, only show WARNING and above.

58 """

59 if quiet:

60 level = "WARNING"

61

62 # Simple format for CLI

63 format_string = "<level>{level: <8}</level> | <level>{message}</level>"

64

65 configure_logging(

66 level=level,

67 format_string=format_string,

68 show_time=False,

69 show_level=True,

70 colorize=True,

71 )

72

73

74 def configure_workflow_logging(level: str = "INFO") -> None:

75 """Configure logging for workflow execution.

76

77 Args:

78 level: Logging level.

79 """

80 # Detailed format for workflows

81 format_string = (

82 "<green>{time:HH:mm:ss}</green> | "

83 "<level>{level: <8}</level> | "

84 "<level>{message}</level>"

85 )

86

87 configure_logging(

88 level=level,

89 format_string=format_string,

90 show_time=True,

91 show_level=True,

92 colorize=True,

93 )

94

95

96 def get_logger(name: str) -> Logger:

97 """Get a logger instance for a module.

98

99 Args:

100 name: Module name (usually __name__).

101

102 Returns:

103 Logger instance.

104 """

105 return logger.bind(name=name) # type: ignore

106

107

108# Export logger for convenience

109 __all__ = [

110 "logger",

111 "configure_logging",

112 "configure_cli_logging",

113 "configure_workflow_logging",

114 "get_logger",

115]