or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-python-json-logger

JSON formatter for Python's built-in logging package that enables structured, machine-readable log output

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/python-json-logger@3.3.x

To install, run

npx @tessl/cli install tessl/pypi-python-json-logger@3.3.0

0

# Python JSON Logger

1

2

A JSON formatter for Python's built-in logging package that enables structured, machine-readable log output. Python JSON Logger integrates seamlessly with Python's standard logging framework and supports multiple JSON serialization backends for optimal performance and compatibility.

3

4

## Package Information

5

6

- **Package Name**: python-json-logger

7

- **Language**: Python

8

- **Installation**: `pip install python-json-logger`

9

10

## Core Imports

11

12

```python

13

import pythonjsonlogger

14

from pythonjsonlogger.json import JsonFormatter

15

```

16

17

Common alternative imports for specific formatters:

18

19

```python

20

# Standard JSON formatter

21

from pythonjsonlogger.json import JsonFormatter

22

23

# High-performance orjson formatter (optional dependency)

24

from pythonjsonlogger.orjson import OrjsonFormatter

25

26

# High-performance msgspec formatter (optional dependency)

27

from pythonjsonlogger.msgspec import MsgspecFormatter

28

```

29

30

**Deprecated imports (still functional but issue warnings):**

31

32

```python

33

# Deprecated - use pythonjsonlogger.json instead

34

from pythonjsonlogger.jsonlogger import JsonFormatter, JsonEncoder

35

```

36

37

## Basic Usage

38

39

```python

40

import logging

41

from pythonjsonlogger.json import JsonFormatter

42

43

# Set up JSON logging

44

logger = logging.getLogger()

45

logger.setLevel(logging.DEBUG)

46

47

# Create console handler with JSON formatter

48

handler = logging.StreamHandler()

49

formatter = JsonFormatter('%(levelname)s %(name)s %(message)s')

50

handler.setFormatter(formatter)

51

logger.addHandler(handler)

52

53

# Log messages are now JSON formatted

54

logger.info("This is a test message", extra={"user_id": 123, "action": "login"})

55

# Output: {"levelname": "INFO", "name": "root", "message": "This is a test message", "user_id": 123, "action": "login"}

56

57

# Log structured data directly

58

logger.info({"event": "user_action", "user_id": 456, "action": "logout"})

59

# Output: {"event": "user_action", "user_id": 456, "action": "logout"}

60

```

61

62

## Architecture

63

64

Python JSON Logger extends Python's standard logging framework with JSON serialization capabilities:

65

66

- **BaseJsonFormatter**: Abstract base class providing core JSON logging functionality and configuration

67

- **Formatter Implementations**: Concrete formatters using different JSON backends (json, orjson, msgspec)

68

- **Type Handling System**: Extensible default functions for serializing complex Python types

69

- **Configuration Options**: Field renaming, static fields, timestamp handling, and custom serialization

70

71

The modular design allows choosing optimal JSON backends while maintaining consistent logging behavior across applications.

72

73

## Capabilities

74

75

### Standard JSON Formatting

76

77

JSON formatting using Python's built-in json module with custom encoder support for extended type handling.

78

79

```python { .api }

80

class JsonFormatter(BaseJsonFormatter):

81

def __init__(

82

self,

83

*args,

84

json_default: OptionalCallableOrStr = None,

85

json_encoder: OptionalCallableOrStr = None,

86

json_serializer: Union[Callable, str] = json.dumps,

87

json_indent: Optional[Union[int, str]] = None,

88

json_ensure_ascii: bool = True,

89

**kwargs

90

): ...

91

92

class JsonEncoder(json.JSONEncoder):

93

def default(self, o: Any) -> Any: ...

94

def format_datetime_obj(self, o: datetime.time | datetime.date | datetime.datetime) -> str: ...

95

```

96

97

[Standard JSON Formatting](./json-formatting.md)

98

99

### High-Performance Formatting

100

101

Alternative JSON formatters using orjson and msgspec for improved performance in high-throughput applications.

102

103

```python { .api }

104

class OrjsonFormatter(BaseJsonFormatter):

105

def __init__(

106

self,

107

*args,

108

json_default: OptionalCallableOrStr = orjson_default,

109

json_indent: bool = False,

110

**kwargs

111

): ...

112

113

class MsgspecFormatter(BaseJsonFormatter):

114

def __init__(

115

self,

116

*args,

117

json_default: OptionalCallableOrStr = msgspec_default,

118

**kwargs

119

): ...

120

```

121

122

[High-Performance Formatting](./performance-formatting.md)

123

124

### Core Configuration

125

126

Base formatter class and configuration options for customizing JSON log output including field management, formatting, and serialization control.

127

128

```python { .api }

129

class BaseJsonFormatter(logging.Formatter):

130

def __init__(

131

self,

132

fmt: Optional[str] = None,

133

datefmt: Optional[str] = None,

134

style: str = "%",

135

validate: bool = True,

136

*,

137

prefix: str = "",

138

rename_fields: Optional[Dict[str, str]] = None,

139

rename_fields_keep_missing: bool = False,

140

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

141

reserved_attrs: Optional[Sequence[str]] = None,

142

timestamp: Union[bool, str] = False,

143

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

144

exc_info_as_array: bool = False,

145

stack_info_as_array: bool = False

146

): ...

147

```

148

149

[Core Configuration](./core-configuration.md)

150

151

### Type Handling

152

153

Functions for serializing complex Python types including datetimes, exceptions, dataclasses, enums, UUIDs, bytes, and custom objects.

154

155

```python { .api }

156

def unknown_default(obj: Any) -> str: ...

157

def datetime_any(obj: datetime.time | datetime.date | datetime.datetime) -> str: ...

158

def time_default(obj: datetime.time) -> str: ...

159

def date_default(obj: datetime.date) -> str: ...

160

def datetime_default(obj: datetime.datetime) -> str: ...

161

def exception_default(obj: BaseException) -> str: ...

162

def traceback_default(obj: TracebackType) -> str: ...

163

def dataclass_default(obj) -> dict[str, Any]: ...

164

def enum_default(obj: enum.Enum | enum.EnumMeta) -> Any | list[Any]: ...

165

def uuid_default(obj: uuid.UUID) -> str: ...

166

def bytes_default(obj: bytes | bytearray, url_safe: bool = True) -> str: ...

167

def type_default(obj: type) -> str: ...

168

```

169

170

[Type Handling](./type-handling.md)

171

172

### Utilities

173

174

Helper functions for package management and compatibility checking.

175

176

```python { .api }

177

def package_is_available(

178

name: str,

179

*,

180

throw_error: bool = False,

181

extras_name: str | None = None

182

) -> bool: ...

183

```

184

185

[Utilities](./utilities.md)

186

187

## Types

188

189

```python { .api }

190

from typing import Optional, Union, Callable, List, Dict, Container, Any, Sequence

191

192

# Type aliases

193

OptionalCallableOrStr = Optional[Union[Callable, str]]

194

LogRecord = Dict[str, Any]

195

196

# Exception classes

197

class PythonJsonLoggerError(Exception):

198

"""Generic base class for all Python JSON Logger exceptions"""

199

200

class MissingPackageError(ImportError, PythonJsonLoggerError):

201

"""A required package is missing"""

202

def __init__(self, name: str, extras_name: str | None = None) -> None: ...

203

204

# Constants

205

RESERVED_ATTRS: List[str] # Default reserved LogRecord attributes

206

ORJSON_AVAILABLE: bool # Whether orjson is available

207

MSGSPEC_AVAILABLE: bool # Whether msgspec is available

208

```