or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-logging.mdindex.mdinstrumentation.mdintegrations.mdmetrics.mdspans-tracing.md

core-logging.mddocs/

0

# Core Logging Methods

1

2

Essential logging functionality providing structured event recording with multiple severity levels, exception tracking, and rich context through attributes and tags. These methods form the foundation of Logfire's observability capabilities.

3

4

## Capabilities

5

6

### Log Level Methods

7

8

Standard logging methods that record events at different severity levels. All methods support message templating with attributes, tag assignment, and exception information capture.

9

10

```python { .api }

11

def trace(msg_template: str, /, *, _tags: Sequence[str] | None = None,

12

_exc_info: bool = False, **attributes) -> None:

13

"""

14

Log a trace level message for detailed debugging information.

15

16

Parameters:

17

- msg_template: Message template with {} placeholders for attributes

18

- _tags: Optional sequence of tags to apply to this log entry

19

- _exc_info: Whether to capture current exception information

20

- **attributes: Key-value pairs for structured data and template substitution

21

"""

22

23

def debug(msg_template: str, /, *, _tags: Sequence[str] | None = None,

24

_exc_info: bool = False, **attributes) -> None:

25

"""

26

Log a debug level message for diagnostic information.

27

28

Parameters: Same as trace()

29

"""

30

31

def info(msg_template: str, /, *, _tags: Sequence[str] | None = None,

32

_exc_info: bool = False, **attributes) -> None:

33

"""

34

Log an info level message for general information.

35

36

Parameters: Same as trace()

37

"""

38

39

def notice(msg_template: str, /, *, _tags: Sequence[str] | None = None,

40

_exc_info: bool = False, **attributes) -> None:

41

"""

42

Log a notice level message for significant but normal events.

43

44

Parameters: Same as trace()

45

"""

46

47

def warning(msg_template: str, /, *, _tags: Sequence[str] | None = None,

48

_exc_info: bool = False, **attributes) -> None:

49

"""

50

Log a warning level message for potentially harmful situations.

51

52

Parameters: Same as trace()

53

"""

54

55

# Alias for warning

56

warn = warning

57

58

def error(msg_template: str, /, *, _tags: Sequence[str] | None = None,

59

_exc_info: bool = False, **attributes) -> None:

60

"""

61

Log an error level message for error events that don't stop execution.

62

63

Parameters: Same as trace()

64

"""

65

66

def fatal(msg_template: str, /, *, _tags: Sequence[str] | None = None,

67

_exc_info: bool = False, **attributes) -> None:

68

"""

69

Log a fatal level message for very severe error events.

70

71

Parameters: Same as trace()

72

"""

73

74

def exception(msg_template: str, /, *, _tags: Sequence[str] | None = None,

75

_exc_info: bool = True, **attributes) -> None:

76

"""

77

Log an exception with traceback information (error level with exc_info=True by default).

78

79

Parameters: Same as trace(), but _exc_info defaults to True

80

"""

81

```

82

83

**Usage Examples:**

84

85

```python

86

import logfire

87

88

# Basic logging

89

logfire.info('User logged in')

90

logfire.error('Database connection failed')

91

92

# Message templating

93

logfire.info('User {user_id} performed {action}', user_id=123, action='login')

94

95

# With tags

96

logfire.warning('Rate limit exceeded', _tags=['security', 'rate-limiting'],

97

user_id=456, attempts=10)

98

99

# Exception logging

100

try:

101

result = 1 / 0

102

except ZeroDivisionError:

103

logfire.exception('Division by zero error', operation='calculate')

104

```

105

106

### Generic Log Method

107

108

Flexible logging method that allows dynamic level specification and comprehensive parameter control.

109

110

```python { .api }

111

def log(level: LevelName | int, msg_template: str,

112

attributes: dict[str, Any] | None = None,

113

tags: Sequence[str] | None = None,

114

exc_info: bool = False,

115

console_log: bool | None = None) -> None:

116

"""

117

Generic log method with full parameter control.

118

119

Parameters:

120

- level: Log level name ('trace', 'debug', 'info', 'notice', 'warning', 'error', 'fatal') or integer

121

- msg_template: Message template string

122

- attributes: Dictionary of attributes for structured data

123

- tags: Sequence of tags to apply

124

- exc_info: Whether to capture exception information

125

- console_log: Override console logging setting for this message

126

"""

127

```

128

129

**Usage Example:**

130

131

```python

132

# Dynamic level logging

133

log_level = 'error' if has_error else 'info'

134

logfire.log(log_level, 'Operation completed',

135

attributes={'duration': 1.5, 'success': not has_error})

136

```

137

138

### Configuration

139

140

Main configuration function for setting up Logfire with comprehensive options for service identification, output destinations, and observability features.

141

142

```python { .api }

143

def configure(*,

144

send_to_logfire: bool | Literal['if-token-present'] | None = None,

145

token: str | None = None,

146

service_name: str | None = None,

147

service_version: str | None = None,

148

environment: str | None = None,

149

console: ConsoleOptions | False | None = None,

150

config_dir: Path | str | None = None,

151

data_dir: Path | str | None = None,

152

min_level: int | LevelName | None = None,

153

sampling: SamplingOptions | None = None,

154

scrubbing: ScrubbingOptions | False | None = None,

155

inspect_arguments: bool | None = None,

156

metrics: MetricsOptions | False | None = None,

157

code_source: CodeSource | None = None,

158

distributed_tracing: bool | None = None,

159

advanced: AdvancedOptions | None = None,

160

additional_span_processors: Sequence[SpanProcessor] | None = None,

161

add_baggage_to_attributes: bool = True,

162

local: bool = False) -> Logfire:

163

"""

164

Configure Logfire with comprehensive options.

165

166

Parameters:

167

- send_to_logfire: Whether to send data to logfire.dev ('if-token-present', True, False)

168

- token: Project token for logfire.dev

169

- service_name: Name of your service/application

170

- service_version: Version of your service

171

- environment: Environment name (dev, staging, prod, etc.)

172

- console: Console output configuration or False to disable

173

- config_dir: Directory for configuration files

174

- data_dir: Directory for local data storage

175

- min_level: Minimum log level to record

176

- sampling: Sampling configuration for traces

177

- scrubbing: Data scrubbing/redaction configuration

178

- inspect_arguments: Enable f-string magic for automatic attribute extraction

179

- metrics: Metrics collection configuration

180

- code_source: Source code location configuration

181

- distributed_tracing: Enable distributed tracing headers

182

- advanced: Advanced configuration options

183

- additional_span_processors: Custom OpenTelemetry span processors

184

- add_baggage_to_attributes: Add OpenTelemetry baggage as span attributes

185

- local: Create local instance instead of configuring global instance

186

187

Returns: Configured Logfire instance

188

"""

189

```

190

191

**Usage Examples:**

192

193

```python

194

# Basic configuration

195

logfire.configure()

196

197

# Production configuration

198

logfire.configure(

199

service_name='my-web-app',

200

service_version='1.2.0',

201

environment='production',

202

send_to_logfire=True,

203

min_level='info'

204

)

205

206

# Development configuration with custom console options

207

logfire.configure(

208

service_name='my-web-app',

209

environment='development',

210

console=logfire.ConsoleOptions(

211

colors='always',

212

include_timestamps=True,

213

verbose=True

214

),

215

send_to_logfire='if-token-present'

216

)

217

```

218

219

### Configuration Classes

220

221

Supporting configuration classes for customizing Logfire behavior.

222

223

```python { .api }

224

class ConsoleOptions:

225

"""Configuration for console output formatting and display."""

226

colors: Literal['auto', 'always', 'never'] = 'auto'

227

span_style: Literal['simple', 'indented', 'show-parents'] = 'simple'

228

include_timestamps: bool = True

229

include_tags: bool = True

230

verbose: bool = False

231

min_log_level: LevelName = 'trace'

232

show_project_link: bool = True

233

234

class ScrubbingOptions:

235

"""Configuration for data scrubbing and redaction."""

236

callback: ScrubCallback | None = None

237

extra_patterns: Sequence[str] | None = None

238

239

class MetricsOptions:

240

"""Configuration for metrics collection."""

241

additional_readers: Sequence[MetricReader] = ()

242

collect_in_spans: bool = True

243

244

class CodeSource:

245

"""Source code location configuration."""

246

repository: str

247

revision: str

248

root_path: str

249

250

class AdvancedOptions:

251

"""Advanced configuration options."""

252

base_url: str | None = None

253

id_generator: IdGenerator = RandomIdGenerator()

254

ns_timestamp_generator: Callable[[], int] = time.time_ns

255

log_record_processors: Sequence[LogRecordProcessor] = ()

256

257

def generate_base_url(self, token: str) -> str: ...

258

```

259

260

### Type Definitions

261

262

```python { .api }

263

# Log level names

264

LevelName = Literal['trace', 'debug', 'info', 'notice', 'warn', 'warning', 'error', 'fatal']

265

266

# Scrubbing callback signature

267

ScrubCallback = Callable[[ScrubMatch], str]

268

269

class ScrubMatch:

270

"""Information about a potential scrubbing match."""

271

path: JsonPath

272

value: Any

273

pattern_match: re.Match[str]

274

275

# Sampling configuration

276

class SamplingOptions:

277

"""Configuration for trace sampling behavior."""

278

# Implementation details vary based on sampling strategy

279

```

280

281

### Instance Management

282

283

Methods for creating customized Logfire instances and managing settings.

284

285

```python { .api }

286

def with_tags(*tags: str) -> Logfire:

287

"""

288

Create a new Logfire instance with additional tags applied to all operations.

289

290

Parameters:

291

- *tags: Tags to add to the new instance

292

293

Returns: New Logfire instance with additional tags

294

"""

295

296

def with_settings(*,

297

tags: Sequence[str] = (),

298

stack_offset: int | None = None,

299

console_log: bool | None = None,

300

custom_scope_suffix: str | None = None) -> Logfire:

301

"""

302

Create a new Logfire instance with custom settings.

303

304

Parameters:

305

- tags: Additional tags to apply

306

- stack_offset: Stack level offset for source location tracking

307

- console_log: Console output override

308

- custom_scope_suffix: Custom suffix for OpenTelemetry scope

309

310

Returns: New Logfire instance with custom settings

311

"""

312

```

313

314

**Usage Examples:**

315

316

```python

317

# Tagged logger instances

318

auth_logger = logfire.with_tags('auth', 'security')

319

db_logger = logfire.with_tags('database', 'persistence')

320

321

auth_logger.info('User login attempt', user_id=123) # Includes auth, security tags

322

db_logger.error('Query timeout', query='SELECT * FROM users') # Includes database, persistence tags

323

324

# Custom settings

325

verbose_logger = logfire.with_settings(

326

console_log=True,

327

tags=['verbose']

328

)

329

```

330

331

### Lifecycle Management

332

333

Methods for controlling Logfire's runtime behavior and resource cleanup.

334

335

```python { .api }

336

def force_flush(timeout_millis: int = 3000) -> bool:

337

"""

338

Force flush all pending spans and metrics to configured exporters.

339

340

Parameters:

341

- timeout_millis: Maximum time to wait for flush completion

342

343

Returns: True if flush completed within timeout, False otherwise

344

"""

345

346

def shutdown(timeout_millis: int = 30000, flush: bool = True) -> bool:

347

"""

348

Shutdown all tracers and meters, optionally flushing pending data.

349

350

Parameters:

351

- timeout_millis: Maximum time to wait for shutdown completion

352

- flush: Whether to flush pending data before shutdown

353

354

Returns: True if shutdown completed within timeout, False otherwise

355

"""

356

```

357

358

**Usage Examples:**

359

360

```python

361

# Ensure data is sent before application exit

362

logfire.force_flush()

363

364

# Clean shutdown at application termination

365

logfire.shutdown(flush=True, timeout_millis=5000)

366

```