or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

browser.mdchild-loggers.mdindex.mdlogger-configuration.mdlogger-methods.mdserializers.mdstreams.mdtransports.md

logger-configuration.mddocs/

0

# Logger Configuration

1

2

Comprehensive configuration system for customizing logger behavior, output format, and performance characteristics. The pino constructor accepts an options object to control all aspects of logging behavior.

3

4

## Capabilities

5

6

### Logger Constructor

7

8

Create a logger instance with optional configuration and destination stream.

9

10

```typescript { .api }

11

/**

12

* Create a new logger instance

13

* @param options - Configuration options for the logger

14

* @param stream - Optional destination stream for log output

15

* @returns Configured logger instance

16

*/

17

function pino(options?: LoggerOptions): Logger;

18

function pino(options: LoggerOptions, stream?: DestinationStream): Logger;

19

function pino(stream?: DestinationStream): Logger;

20

```

21

22

**Usage Examples:**

23

24

```javascript

25

// Basic logger with defaults

26

const logger = pino();

27

28

// Logger with custom level

29

const logger = pino({ level: 'debug' });

30

31

// Logger with custom stream

32

const logger = pino(pino.destination('./logs/app.log'));

33

34

// Logger with options and stream

35

const logger = pino({

36

name: 'my-app',

37

level: 'info'

38

}, pino.destination('./logs/app.log'));

39

```

40

41

### Logger Options Interface

42

43

Complete configuration interface for logger behavior.

44

45

```typescript { .api }

46

interface LoggerOptions {

47

/** Minimum log level (default: 'info') */

48

level?: string;

49

50

/** Logger name to include in log records */

51

name?: string;

52

53

/** Timestamp configuration (default: epochTime) */

54

timestamp?: boolean | TimeFn;

55

56

/** Custom object serializers */

57

serializers?: { [key: string]: SerializerFn };

58

59

/** Data redaction configuration */

60

redact?: string[] | RedactOptions;

61

62

/** Transport configuration for log processing */

63

transport?: TransportSingleOptions | TransportMultiOptions | TransportPipelineOptions;

64

65

/** Output formatting functions */

66

formatters?: FormattersOptions;

67

68

/** Custom logging levels */

69

customLevels?: { [level: string]: number };

70

71

/** Use only custom levels, omit default levels */

72

useOnlyCustomLevels?: boolean;

73

74

/** Level comparison function for custom sorting */

75

levelComparison?: "ASC" | "DESC" | ((current: number, expected: number) => boolean);

76

77

/** Mixin function for adding dynamic data */

78

mixin?: MixinFn;

79

80

/** Mixin merge strategy function */

81

mixinMergeStrategy?: MixinMergeStrategyFn;

82

83

/** Message key name in log output (default: 'msg') */

84

messageKey?: string;

85

86

/** Error key name in log output (default: 'err') */

87

errorKey?: string;

88

89

/** Nested key for wrapping log data */

90

nestedKey?: string;

91

92

/** Enable/disable logging (default: true) */

93

enabled?: boolean;

94

95

/** Base properties added to all log records */

96

base?: { [key: string]: any } | null;

97

98

/** Hook functions for customization */

99

hooks?: HooksOptions;

100

101

/** Message prefix for all log messages */

102

msgPrefix?: string;

103

104

/** Use CRLF line endings instead of LF */

105

crlf?: boolean;

106

107

/** Object serialization depth limit (default: 5) */

108

depthLimit?: number;

109

110

/** Object serialization breadth limit (default: 100) */

111

edgeLimit?: number;

112

113

/** Child logger creation callback */

114

onChild?: OnChildCallback;

115

116

/** Browser-specific options */

117

browser?: BrowserOptions;

118

119

/** Avoid error causes by circular references (default: true) */

120

safe?: boolean;

121

122

/** Custom level numeric value when defining custom level via level */

123

levelVal?: number;

124

125

/** Output level as string instead of integer */

126

useLevelLabels?: boolean;

127

}

128

```

129

130

## Core Configuration Options

131

132

### Level Configuration

133

134

Control which log messages are output based on severity level.

135

136

```typescript { .api }

137

interface LoggerOptions {

138

/** Minimum log level: 'fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent' */

139

level?: string;

140

}

141

```

142

143

**Usage Examples:**

144

145

```javascript

146

// Development logging

147

const logger = pino({ level: 'debug' });

148

149

// Production logging

150

const logger = pino({ level: 'warn' });

151

152

// Disable all logging

153

const logger = pino({ level: 'silent' });

154

```

155

156

### Logger Naming

157

158

Add a name field to all log records for identification.

159

160

```typescript { .api }

161

interface LoggerOptions {

162

/** Logger name included in all log records */

163

name?: string;

164

}

165

```

166

167

**Usage Examples:**

168

169

```javascript

170

const logger = pino({ name: 'my-application' });

171

logger.info('Hello world');

172

// Output: {"level":30,"time":1531171074631,"name":"my-application","msg":"hello world",...}

173

174

const apiLogger = pino({ name: 'api-server' });

175

const dbLogger = pino({ name: 'database' });

176

```

177

178

### Timestamp Configuration

179

180

Control timestamp format and inclusion in log records.

181

182

```typescript { .api }

183

interface LoggerOptions {

184

/** Timestamp configuration - boolean or custom function */

185

timestamp?: boolean | TimeFn;

186

}

187

188

type TimeFn = () => string;

189

```

190

191

**Usage Examples:**

192

193

```javascript

194

// Default epoch timestamp

195

const logger = pino({ timestamp: true });

196

197

// No timestamp

198

const logger = pino({ timestamp: false });

199

200

// Custom timestamp format

201

const logger = pino({

202

timestamp: () => `,"time":"${new Date().toISOString()}"`

203

});

204

205

// Use built-in time functions

206

const logger = pino({ timestamp: pino.stdTimeFunctions.isoTime });

207

```

208

209

### Base Properties

210

211

Default properties included in all log records.

212

213

```typescript { .api }

214

interface LoggerOptions {

215

/** Base properties added to all log records (default includes pid and hostname) */

216

base?: { [key: string]: any } | null;

217

}

218

```

219

220

**Usage Examples:**

221

222

```javascript

223

// Custom base properties

224

const logger = pino({

225

base: {

226

service: 'user-api',

227

version: '1.2.3',

228

env: process.env.NODE_ENV

229

}

230

});

231

232

// No base properties

233

const logger = pino({ base: null });

234

235

// Add to default base properties

236

const logger = pino({

237

base: {

238

pid: process.pid,

239

hostname: os.hostname(),

240

service: 'my-app'

241

}

242

});

243

```

244

245

## Advanced Configuration

246

247

### Custom Levels

248

249

Define custom logging levels with numeric priorities.

250

251

```typescript { .api }

252

interface LoggerOptions {

253

/** Custom level definitions */

254

customLevels?: { [level: string]: number };

255

256

/** Use only custom levels, omit default pino levels */

257

useOnlyCustomLevels?: boolean;

258

259

/** Custom level comparison function */

260

levelComparison?: "ASC" | "DESC" | ((current: number, expected: number) => boolean);

261

}

262

```

263

264

**Usage Examples:**

265

266

```javascript

267

// Add custom levels

268

const logger = pino({

269

customLevels: {

270

foo: 35, // Between info (30) and warn (40)

271

bar: 45 // Between warn (40) and error (50)

272

}

273

});

274

275

logger.foo('Custom level message');

276

logger.bar({ data: 'example' }, 'Another custom level');

277

278

// Use only custom levels

279

const logger = pino({

280

level: 'foo',

281

customLevels: { foo: 30, bar: 40, baz: 50 },

282

useOnlyCustomLevels: true

283

});

284

```

285

286

### Mixin Functions

287

288

Add dynamic data to log records using mixin functions.

289

290

```typescript { .api }

291

interface LoggerOptions {

292

/** Function called for each log method to add dynamic data */

293

mixin?: MixinFn;

294

295

/** Strategy for merging mixin data with log data */

296

mixinMergeStrategy?: MixinMergeStrategyFn;

297

}

298

299

type MixinFn = (mergeObject: object, level: number, logger: Logger) => object;

300

type MixinMergeStrategyFn = (mergeObject: object, mixinObject: object) => object;

301

```

302

303

**Usage Examples:**

304

305

```javascript

306

// Add request ID from async context

307

const logger = pino({

308

mixin() {

309

return {

310

requestId: getRequestId(), // From async local storage

311

memoryUsage: process.memoryUsage().heapUsed

312

};

313

}

314

});

315

316

// Custom merge strategy

317

const logger = pino({

318

mixin: () => ({ timestamp: Date.now() }),

319

mixinMergeStrategy: (mergeObject, mixinObject) => {

320

return Object.assign({}, mixinObject, mergeObject);

321

}

322

});

323

```

324

325

### Formatters

326

327

Customize the shape of log output using formatter functions.

328

329

```typescript { .api }

330

interface LoggerOptions {

331

/** Output formatting functions */

332

formatters?: FormattersOptions;

333

}

334

335

interface FormattersOptions {

336

/** Changes the shape of the log level in output */

337

level?: (label: string, number: number) => object;

338

339

/** Changes the shape of the bindings in output */

340

bindings?: (bindings: Bindings) => object;

341

342

/** Changes the shape of the log object */

343

log?: (object: Record<string, unknown>) => Record<string, unknown>;

344

}

345

```

346

347

**Usage Examples:**

348

349

```javascript

350

const logger = pino({

351

formatters: {

352

level: (label, number) => {

353

return { severity: label.toUpperCase() };

354

},

355

bindings: (bindings) => {

356

return { context: bindings };

357

},

358

log: (object) => {

359

const { req, res, ...rest } = object;

360

return rest; // Remove req/res from output

361

}

362

}

363

});

364

```

365

366

### Hooks

367

368

Customize internal logger operations with hook functions.

369

370

```typescript { .api }

371

interface LoggerOptions {

372

/** Hook functions for customizing logger behavior */

373

hooks?: HooksOptions;

374

}

375

376

interface HooksOptions {

377

/** Intercept and modify log method calls */

378

logMethod?: (this: Logger, args: Parameters<LogFn>, method: LogFn, level: number) => void;

379

380

/** Modify stringified JSON before writing to stream */

381

streamWrite?: (str: string) => string;

382

}

383

```

384

385

**Usage Examples:**

386

387

```javascript

388

const logger = pino({

389

hooks: {

390

logMethod(args, method, level) {

391

// Add timestamp to first argument if it's an object

392

if (typeof args[0] === 'object' && args[0] !== null) {

393

args[0].loggedAt = new Date().toISOString();

394

}

395

method.apply(this, args);

396

},

397

streamWrite(str) {

398

// Compress or encrypt log data before writing

399

return compress(str);

400

}

401

}

402

});

403

```

404

405

## Key Configuration

406

407

### Message and Error Keys

408

409

Customize field names for messages and errors in log output.

410

411

```typescript { .api }

412

interface LoggerOptions {

413

/** Key name for message field (default: 'msg') */

414

messageKey?: string;

415

416

/** Key name for error field (default: 'err') */

417

errorKey?: string;

418

419

/** Key name for nesting all log data */

420

nestedKey?: string;

421

}

422

```

423

424

**Usage Examples:**

425

426

```javascript

427

// Custom message key

428

const logger = pino({ messageKey: 'message' });

429

logger.info('Hello world');

430

// Output: {"level":30,"time":1531171074631,"message":"hello world",...}

431

432

// Custom error key

433

const logger = pino({ errorKey: 'error' });

434

logger.error(new Error('Failed'), 'Operation failed');

435

436

// Nested data

437

const logger = pino({ nestedKey: 'data' });

438

logger.info({ userId: 123 }, 'User action');

439

// Output: {"level":30,"time":1531171074631,"msg":"User action","data":{"userId":123},...}

440

```

441

442

## Performance Configuration

443

444

### Serialization Limits

445

446

Control object serialization depth and breadth to prevent performance issues.

447

448

```typescript { .api }

449

interface LoggerOptions {

450

/** Maximum object nesting depth (default: 5) */

451

depthLimit?: number;

452

453

/** Maximum number of properties per object (default: 100) */

454

edgeLimit?: number;

455

}

456

```

457

458

**Usage Examples:**

459

460

```javascript

461

// Increase limits for complex objects

462

const logger = pino({

463

depthLimit: 10,

464

edgeLimit: 200

465

});

466

467

// Decrease limits for performance

468

const logger = pino({

469

depthLimit: 3,

470

edgeLimit: 50

471

});

472

```

473

474

### Enable/Disable Logging

475

476

Control whether logging is active without changing log levels.

477

478

```typescript { .api }

479

interface LoggerOptions {

480

/** Enable or disable all logging (default: true) */

481

enabled?: boolean;

482

}

483

```

484

485

**Usage Examples:**

486

487

```javascript

488

// Disable logging entirely

489

const logger = pino({ enabled: false });

490

491

// Conditional logging

492

const logger = pino({

493

enabled: process.env.NODE_ENV !== 'test'

494

});

495

```