or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

colors.mdformatters.mdindex.mdlogging-functions.md

formatters.mddocs/

0

# Colored Formatters

1

2

Core formatting classes that add color support to log messages. These formatters extend Python's standard logging.Formatter with ANSI color codes for enhanced terminal output.

3

4

## Capabilities

5

6

### ColoredFormatter

7

8

Main formatter class that allows colors to be placed in the format string. Extends logging.Formatter with color support through ANSI escape codes.

9

10

```python { .api }

11

from typing import IO, Dict, Mapping, Any, Optional, Literal

12

13

class ColoredFormatter(logging.Formatter):

14

def __init__(

15

self,

16

fmt: Optional[str] = None,

17

datefmt: Optional[str] = None,

18

style: Literal["%", "{", "$"] = "%",

19

log_colors: Optional[LogColors] = None,

20

reset: bool = True,

21

secondary_log_colors: Optional[SecondaryLogColors] = None,

22

validate: bool = True,

23

stream: Optional[IO[str]] = None,

24

no_color: bool = False,

25

force_color: bool = False,

26

defaults: Optional[Dict[str, Any]] = None,

27

):

28

"""

29

Set the format and colors the ColoredFormatter will use.

30

31

Parameters:

32

- fmt: Format string to use (uses default if None)

33

- datefmt: Date format string

34

- style: Format style ('%', '{', or '$')

35

- log_colors: Mapping of log level names to color names

36

- reset: Implicitly append color reset to all records

37

- secondary_log_colors: Map secondary log_color attributes

38

- validate: Validate the format string

39

- stream: Stream for TTY detection and color control

40

- no_color: Disable color output

41

- force_color: Enable color output (overrides no_color)

42

- defaults: Default values mapping (Python 3.10+)

43

"""

44

45

def formatMessage(self, record: logging.LogRecord) -> str:

46

"""Format a message from a record object."""

47

```

48

49

**Usage Example:**

50

```python

51

import colorlog

52

import logging

53

54

formatter = colorlog.ColoredFormatter(

55

'%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s',

56

log_colors={

57

'DEBUG': 'cyan',

58

'INFO': 'green',

59

'WARNING': 'yellow',

60

'ERROR': 'red',

61

'CRITICAL': 'red,bg_white',

62

}

63

)

64

65

handler = logging.StreamHandler()

66

handler.setFormatter(formatter)

67

logger = logging.getLogger('example')

68

logger.addHandler(handler)

69

```

70

71

### LevelFormatter

72

73

Extension of ColoredFormatter that uses per-level format strings. Allows different formatting for each log level.

74

75

```python { .api }

76

from typing import Dict, Any, Mapping

77

78

class LevelFormatter:

79

def __init__(self, fmt: Mapping[str, str], **kwargs: Any):

80

"""

81

Configure a ColoredFormatter with its own format string for each log level.

82

83

Parameters:

84

- fmt: Mapping of log levels to format strings

85

- **kwargs: Additional arguments passed to ColoredFormatter

86

"""

87

88

def format(self, record: logging.LogRecord) -> str:

89

"""Format a record using the appropriate level-specific formatter."""

90

```

91

92

**Usage Example:**

93

```python

94

import colorlog

95

96

formatter = colorlog.LevelFormatter(

97

fmt={

98

"DEBUG": "%(log_color)s%(message)s (%(module)s:%(lineno)d)",

99

"INFO": "%(log_color)s%(message)s",

100

"WARNING": "%(log_color)sWRN: %(message)s (%(module)s:%(lineno)d)",

101

"ERROR": "%(log_color)sERR: %(message)s (%(module)s:%(lineno)d)",

102

"CRITICAL": "%(log_color)sCRT: %(message)s (%(module)s:%(lineno)d)",

103

},

104

log_colors={

105

'DEBUG': 'white',

106

'INFO': 'green',

107

'WARNING': 'yellow',

108

'ERROR': 'red',

109

'CRITICAL': 'bold_red',

110

}

111

)

112

```

113

114

### TTYColoredFormatter

115

116

Backward compatibility alias for ColoredFormatter. The features provided by this subclass are now included directly in the ColoredFormatter class.

117

118

```python { .api }

119

TTYColoredFormatter = ColoredFormatter

120

```

121

122

## Format String Variables

123

124

When using ColoredFormatter, these variables are available in format strings:

125

126

- `%(log_color)s`: Color associated with the record's level

127

- `%(reset)s`: Color reset code

128

- `%(<name>_log_color)s`: Secondary colors based on secondary_log_colors configuration

129

- All standard logging format variables: `%(levelname)s`, `%(name)s`, `%(message)s`, etc.

130

131

## Secondary Log Colors

132

133

Secondary log colors allow multiple color attributes based on log level. Each key in secondary_log_colors adds a `{key}_log_color` attribute.

134

135

**Example:**

136

```python

137

formatter = colorlog.ColoredFormatter(

138

"%(log_color)s%(levelname)-8s%(reset)s %(message_log_color)s%(message)s",

139

secondary_log_colors={

140

'message': {

141

'ERROR': 'red',

142

'CRITICAL': 'red'

143

}

144

}

145

)

146

```

147

148

## Color Control

149

150

The formatter automatically detects terminal capabilities and environment variables:

151

152

- **FORCE_COLOR**: Environment variable to force color output

153

- **NO_COLOR**: Environment variable to disable color output

154

- **TTY Detection**: Automatically disables colors for non-TTY streams

155

- **Windows Support**: Automatic colorama integration on Windows

156

157

## Types

158

159

```python { .api }

160

# Type aliases used in formatter signatures

161

from typing import Mapping

162

163

EscapeCodes = Mapping[str, str]

164

LogColors = Mapping[str, str]

165

SecondaryLogColors = Mapping[str, LogColors]

166

```