0
# Format Composition
1
2
Utilities for combining and organizing multiple formats into powerful transformation pipelines.
3
4
## Capabilities
5
6
### Combine Format
7
8
Combines multiple formats into a single format that applies transformations in sequence.
9
10
```javascript { .api }
11
/**
12
* Combines multiple formats into a single format pipeline
13
* @param {...Format} formats - Variable number of format instances to combine
14
* @returns {Format} Combined format instance
15
*/
16
function combine(...formats);
17
```
18
19
The combine function creates a pipeline where each format's transform method is called in sequence. If any format returns a falsy value, the pipeline stops and the log entry is filtered out.
20
21
**Usage Examples:**
22
23
```javascript
24
const { format } = require('logform');
25
26
// Basic combination
27
const combinedFormat = format.combine(
28
format.timestamp(),
29
format.label({ label: 'my-app' }),
30
format.colorize(),
31
format.simple()
32
);
33
34
const result = combinedFormat.transform({
35
level: 'info',
36
message: 'Hello world'
37
});
38
39
// Complex combination with filtering
40
const productionFormat = format.combine(
41
format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
42
format.errors({ stack: true }),
43
format.splat(),
44
format.json()
45
);
46
47
// Development format with colors
48
const developmentFormat = format.combine(
49
format.colorize(),
50
format.timestamp(),
51
format.align(),
52
format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
53
);
54
55
// Conditional formatting
56
const conditionalFormat = format.combine(
57
format.timestamp(),
58
format((info) => {
59
if (info.level === 'debug' && process.env.NODE_ENV === 'production') {
60
return false; // Filter out debug logs in production
61
}
62
return info;
63
}),
64
format.json()
65
);
66
```
67
68
### Format Pipeline Behavior
69
70
The combine format implements a cascade pattern where:
71
72
1. Each format is applied in the order specified
73
2. The output of one format becomes the input to the next
74
3. If any format returns `false` or other falsy value, the pipeline stops
75
4. The final result is returned, or `false` if filtered
76
77
**Pipeline Examples:**
78
79
```javascript
80
const { format } = require('logform');
81
82
// Pipeline with filtering
83
const filteringPipeline = format.combine(
84
format.timestamp(),
85
format((info) => {
86
// Filter out sensitive information
87
if (info.message.includes('password')) {
88
return false;
89
}
90
return info;
91
}),
92
format.json()
93
);
94
95
// Error handling pipeline
96
const errorPipeline = format.combine(
97
format.errors({ stack: true }),
98
format.timestamp(),
99
format.printf(info => {
100
if (info.stack) {
101
return `${info.timestamp} ERROR: ${info.message}\n${info.stack}`;
102
}
103
return `${info.timestamp} ${info.level.toUpperCase()}: ${info.message}`;
104
})
105
);
106
107
// Metadata organization pipeline
108
const metadataPipeline = format.combine(
109
format.splat(),
110
format.metadata({ fillExcept: ['level', 'message', 'timestamp'] }),
111
format.timestamp(),
112
format.json()
113
);
114
```
115
116
### Cascade Function
117
118
The internal cascade function that implements the pipeline logic.
119
120
```javascript { .api }
121
/**
122
* Creates a cascade function that applies formats in sequence
123
* @param {Format[]} formats - Array of format instances
124
* @returns {Function} Cascade function that processes info objects
125
*/
126
function cascade(formats);
127
```
128
129
The cascade function validates that all provided formats have a `transform` method and creates a function that applies each transformation in sequence.
130
131
**Internal Usage:**
132
133
```javascript
134
// Internal implementation example
135
function cascade(formats) {
136
return (info) => {
137
let obj = info;
138
for (let i = 0; i < formats.length; i++) {
139
obj = formats[i].transform(obj, formats[i].options);
140
if (!obj) {
141
return false; // Stop pipeline if format returns falsy
142
}
143
}
144
return obj;
145
};
146
}
147
```
148
149
### Format Validation
150
151
The combine function includes validation to ensure all provided arguments are valid format instances.
152
153
```javascript { .api }
154
/**
155
* Validates that an object is a valid format instance
156
* @param {any} format - Object to validate
157
* @returns {boolean} True if valid format
158
* @throws {Error} If format is invalid
159
*/
160
function isValidFormat(format);
161
```
162
163
Valid formats must have:
164
- A `transform` method that is a function
165
- Optional `options` property for configuration
166
167
**Validation Examples:**
168
169
```javascript
170
const { format } = require('logform');
171
172
// Valid format instances
173
const validFormats = [
174
format.timestamp(),
175
format.json(),
176
format.colorize({ level: true })
177
];
178
179
// Invalid format examples that would throw errors
180
try {
181
format.combine(
182
format.timestamp(),
183
{ transform: 'not a function' }, // Invalid - transform is not a function
184
format.json()
185
);
186
} catch (error) {
187
console.error('Invalid format detected:', error.message);
188
}
189
```
190
191
## Advanced Composition Patterns
192
193
### Conditional Formatting
194
195
```javascript
196
const { format } = require('logform');
197
198
const conditionalFormat = format.combine(
199
format.timestamp(),
200
format((info) => {
201
// Apply different formatting based on log level
202
if (info.level === 'error') {
203
info.urgent = true;
204
}
205
return info;
206
}),
207
format.printf(info => {
208
const prefix = info.urgent ? '🚨 ' : '';
209
return `${prefix}${info.timestamp} [${info.level}]: ${info.message}`;
210
})
211
);
212
```
213
214
### Environment-Based Formatting
215
216
```javascript
217
const { format } = require('logform');
218
219
const environmentFormat = format.combine(
220
format.timestamp(),
221
process.env.NODE_ENV === 'development'
222
? format.combine(
223
format.colorize(),
224
format.simple()
225
)
226
: format.combine(
227
format.errors({ stack: true }),
228
format.json()
229
)
230
);
231
```
232
233
### Multi-Transport Formatting
234
235
```javascript
236
const { format } = require('logform');
237
238
// Base format for all transports
239
const baseFormat = format.combine(
240
format.timestamp(),
241
format.errors({ stack: true }),
242
format.splat()
243
);
244
245
// Console-specific format
246
const consoleFormat = format.combine(
247
baseFormat,
248
format.colorize(),
249
format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
250
);
251
252
// File-specific format
253
const fileFormat = format.combine(
254
baseFormat,
255
format.json()
256
);
257
```