or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-koa-logger

Logging middleware for koa

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/koa-logger@4.0.x

To install, run

npx @tessl/cli install tessl/npm-koa-logger@4.0.0

0

# koa-logger

1

2

Development-style logging middleware for Koa.js applications that provides colorized HTTP request and response logging with customizable output formatting.

3

4

## Package Information

5

6

- **Package Name**: koa-logger

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install koa-logger`

10

11

## Core Imports

12

13

```javascript

14

const logger = require('koa-logger');

15

```

16

17

For ES modules:

18

19

```javascript

20

import logger from 'koa-logger';

21

```

22

23

## Basic Usage

24

25

```javascript

26

const logger = require('koa-logger');

27

const Koa = require('koa');

28

29

const app = new Koa();

30

31

// Basic logging with default console output

32

app.use(logger());

33

34

// The middleware will log requests and responses like:

35

// <-- GET /users

36

// --> GET /users 200 125ms 1.2kb

37

```

38

39

## Architecture

40

41

koa-logger is built around several key components that work together to provide comprehensive HTTP request/response logging:

42

43

- **Middleware Factory**: Main `koaLogger()` function that configures and returns the actual middleware

44

- **Print System**: Configurable output transport that handles both console logging and custom transporters

45

- **Color Mapping**: Status code color system using chalk for terminal output (1xx/2xx=green, 3xx=cyan, 4xx=yellow, 5xx=red, etc.)

46

- **Timing Engine**: Request timing measurement with support for legacy `request-received` integration

47

- **Stream Counter**: Length calculation for streaming responses using passthrough-counter when Content-Length is unavailable

48

- **Response Monitoring**: Uses `on-finished` to detect response completion, close events, and downstream errors

49

- **Error Handler**: Catches and logs middleware errors while preserving original error propagation

50

51

The middleware wraps all downstream middleware to capture request start time, logs the incoming request immediately, then waits for response completion to log the final result with timing and size information.

52

53

## Capabilities

54

55

### Logger Middleware Factory

56

57

Creates a Koa middleware function that logs HTTP requests and responses with colored output format.

58

59

```javascript { .api }

60

/**

61

* Creates a logging middleware for Koa applications.

62

* @param {Function|Object} [options] - Either a transporter function or options object

63

* @returns {Function} - Koa middleware function with signature async (ctx, next) => {}

64

*/

65

function logger(options);

66

```

67

68

**Parameters:**

69

70

- `options` (optional): Can be either:

71

- **Function**: Custom transporter function `(str, args) => void`

72

- **Object**: Configuration object with `transporter` property

73

74

**Options Object:**

75

76

```javascript { .api }

77

interface LoggerOptions {

78

/** Custom transport function for redirecting log output */

79

transporter?: (str: string, args: any[]) => void;

80

}

81

```

82

83

**Transporter Function:**

84

85

```javascript { .api }

86

/**

87

* Custom transport function for handling log output

88

* @param {string} str - Formatted output string with ANSI colors

89

* @param {Array} args - Raw arguments array [format, method, url, status, time, length]

90

*/

91

type TransporterFunction = (str: string, args: any[]) => void;

92

```

93

94

**Returns:** Async middleware function with signature `async (ctx, next) => Promise<void>`

95

96

**Usage Examples:**

97

98

```javascript

99

const logger = require('koa-logger');

100

const Koa = require('koa');

101

102

const app = new Koa();

103

104

// Basic usage with default console.log output

105

app.use(logger());

106

107

// Custom transporter function (direct function parameter)

108

app.use(logger((str, args) => {

109

// str contains formatted string with colors

110

// args contains [format, method, url, status, time, length]

111

console.log('Custom:', str);

112

// Log to file, external service, etc.

113

}));

114

115

// Custom transporter using options object

116

app.use(logger({

117

transporter: (str, args) => {

118

// Custom logging logic

119

fs.appendFileSync('access.log', str + '\n');

120

}

121

}));

122

```

123

124

## Log Output Format

125

126

The logger produces two types of output:

127

128

### Request Logging

129

Shows incoming requests with format: `<-- METHOD URL`

130

131

```

132

<-- GET /api/users

133

<-- POST /api/login

134

```

135

136

### Response Logging

137

Shows completed responses with format: `INDICATOR METHOD URL STATUS TIME LENGTH`

138

139

```

140

--> GET /api/users 200 45ms 2.1kb

141

--> POST /api/login 401 12ms 156b

142

xxx GET /api/error 500 234ms - (for errors)

143

-x- GET /api/timeout 200 5000ms 1kb (for closed connections)

144

```

145

146

**Status Code Color Coding:**

147

- **1xx, 2xx**: Green (success)

148

- **3xx**: Cyan (redirection)

149

- **4xx**: Yellow (client error)

150

- **5xx**: Red (server error)

151

- **7xx**: Magenta (non-standard)

152

- **8xx+**: Yellow (fallback)

153

154

**Response Indicators:**

155

- `-->`: Normal response completion (gray)

156

- `xxx`: Error occurred during processing (red)

157

- `-x-`: Connection was closed before completion (yellow)

158

159

## Advanced Features

160

161

### Stream Length Calculation

162

The middleware automatically calculates content length for streaming responses by intercepting streams with a counter, providing accurate byte counts even when `Content-Length` header is not set.

163

164

### Error Handling

165

Catches and logs downstream middleware errors while preserving the original error for upstream handling. Errors are displayed with `xxx` indicator and red coloring.

166

167

### Request Timing Compatibility

168

Supports deprecated `request-received` timing injection for more accurate performance measurements (shows deprecation warning when used).

169

170

### Timing Display Format

171

- **< 10 seconds**: Displayed in milliseconds (e.g., `245ms`)

172

- **≥ 10 seconds**: Displayed in seconds (e.g., `15s`)

173

174

### Content Length Formatting

175

- Uses human-readable byte formatting (e.g., `1.2kb`, `156b`, `2.1mb`)

176

- Shows empty string for 204, 205, 304 status codes (no content)

177

- Shows `-` when length cannot be determined (errors, closed connections)

178

179

## Compatibility

180

181

- **Node.js**: >= 18

182

- **Koa**: Compatible with Koa v3.0.0+

183

- **request-received**: Legacy timing compatibility (deprecated)

184

185

## Usage Notes

186

187

- Recommended to use this middleware near the top of your middleware stack to wrap all subsequent middleware

188

- The middleware uses `on-finished` to detect response completion, ensuring accurate timing even for streaming responses

189

- All log output includes ANSI color codes for terminal display

190

- Custom transporters receive both the formatted color string and raw argument array for flexible processing