0
# Layouts and Formatting
1
2
Layouts control how log messages are formatted for output. The compatibility API provides pattern-based formatting, simple layouts, and extensible custom layout capabilities.
3
4
## Base Layout Class
5
6
### Layout Abstract Class
7
8
```java { .api }
9
public abstract class Layout {
10
// Line separator constants
11
public static final String LINE_SEP;
12
public static final int LINE_SEP_LEN;
13
14
// Abstract methods to implement
15
public abstract String format(LoggingEvent event);
16
public abstract boolean ignoresThrowable();
17
18
// Optional methods
19
public String getContentType();
20
public String getHeader();
21
public String getFooter();
22
23
// Lifecycle
24
public void activateOptions();
25
}
26
```
27
28
**Parameters:**
29
- `event` - LoggingEvent to format
30
31
**Returns:**
32
- `String` formatted message, content type, header, or footer
33
- `boolean` indicating if throwable information is ignored
34
35
## Pattern-Based Layout
36
37
### PatternLayout
38
39
```java { .api }
40
public class PatternLayout extends Layout {
41
// Default patterns
42
public static final String DEFAULT_CONVERSION_PATTERN = "%m%n";
43
public static final String TTCC_CONVERSION_PATTERN = "%r [%t] %p %c %x - %m%n";
44
45
// Constructors
46
public PatternLayout();
47
public PatternLayout(String pattern);
48
49
// Pattern management
50
public String getConversionPattern();
51
public void setConversionPattern(String conversionPattern);
52
53
// Layout implementation
54
public String format(LoggingEvent event);
55
public boolean ignoresThrowable();
56
public void activateOptions();
57
}
58
```
59
60
**Parameters:**
61
- `pattern` - String conversion pattern
62
- `conversionPattern` - String pattern to set
63
- `event` - LoggingEvent to format
64
65
**Returns:**
66
- `String` current conversion pattern or formatted message
67
- `boolean` always returns true (ignores throwable)
68
69
### Pattern Conversion Specifiers
70
71
The PatternLayout uses conversion patterns with the following specifiers:
72
73
| Specifier | Description | Example |
74
|-----------|-------------|---------|
75
| `%c` | Category/Logger name | `com.myapp.MyClass` |
76
| `%C` | Fully qualified class name | `com.myapp.MyClass` |
77
| `%d` | Date/time | `2023-10-15 14:30:25,123` |
78
| `%F` | File name | `MyClass.java` |
79
| `%l` | Location information | `com.myapp.MyClass.method(MyClass.java:42)` |
80
| `%L` | Line number | `42` |
81
| `%m` | Application message | `User logged in` |
82
| `%M` | Method name | `loginUser` |
83
| `%n` | Platform-specific line separator | `\n` or `\r\n` |
84
| `%p` | Priority/Level | `INFO`, `ERROR` |
85
| `%r` | Milliseconds since startup | `1234` |
86
| `%t` | Thread name | `main`, `pool-1-thread-1` |
87
| `%x` | NDC (Nested Diagnostic Context) | `operation.subop` |
88
| `%X` | MDC (Mapped Diagnostic Context) | `{userId=123, sessionId=abc}` |
89
90
### Pattern Format Modifiers
91
92
| Modifier | Description | Example |
93
|----------|-------------|---------|
94
| `%-5p` | Left-align in 5 characters | `INFO ` |
95
| `%5p` | Right-align in 5 characters | ` INFO` |
96
| `%.10c` | Truncate to 10 characters | `com.myapp` |
97
| `%20.30c` | Min 20, max 30 characters | Padded or truncated |
98
| `%c{1}` | Show only last component | `MyClass` |
99
| `%c{2}` | Show last 2 components | `myapp.MyClass` |
100
101
### Date Format Patterns
102
103
| Pattern | Description | Example |
104
|---------|-------------|---------|
105
| `%d` | Default format | `15 Oct 2023 14:30:25,123` |
106
| `%d{ISO8601}` | ISO 8601 format | `2023-10-15 14:30:25,123` |
107
| `%d{ABSOLUTE}` | Absolute time | `14:30:25,123` |
108
| `%d{DATE}` | Date format | `15 Oct 2023 14:30:25,123` |
109
| `%d{dd MMM yyyy HH:mm:ss,SSS}` | Custom format | `15 Oct 2023 14:30:25,123` |
110
111
## Simple Layout
112
113
### SimpleLayout
114
115
```java { .api }
116
public class SimpleLayout extends Layout {
117
// Constructor
118
public SimpleLayout();
119
120
// Layout implementation
121
public String format(LoggingEvent event);
122
public boolean ignoresThrowable();
123
}
124
```
125
126
**Parameters:**
127
- `event` - LoggingEvent to format
128
129
**Returns:**
130
- `String` formatted as "LEVEL - message\n"
131
- `boolean` always returns true (ignores throwable)
132
133
## HTML Layout
134
135
### HTMLLayout
136
137
```java { .api }
138
public class HTMLLayout extends Layout {
139
// Constructor
140
public HTMLLayout();
141
142
// Layout implementation
143
public String format(LoggingEvent event);
144
public boolean ignoresThrowable();
145
public String getContentType();
146
public String getHeader();
147
public String getFooter();
148
149
// Configuration
150
public boolean getLocationInfo();
151
public void setLocationInfo(boolean flag);
152
public String getTitle();
153
public void setTitle(String title);
154
}
155
```
156
157
**Parameters:**
158
- `event` - LoggingEvent to format
159
- `flag` - Boolean to enable/disable location info
160
- `title` - String title for HTML document
161
162
**Returns:**
163
- `String` HTML-formatted message, content type, header, or footer
164
- `boolean` always returns true (ignores throwable)
165
166
## XML Layout
167
168
### XMLLayout
169
170
```java { .api }
171
public class XMLLayout extends Layout {
172
// Constructor
173
public XMLLayout();
174
175
// Layout implementation
176
public String format(LoggingEvent event);
177
public boolean ignoresThrowable();
178
public String getContentType();
179
public String getHeader();
180
public String getFooter();
181
182
// Configuration
183
public boolean getLocationInfo();
184
public void setLocationInfo(boolean flag);
185
public boolean getProperties();
186
public void setProperties(boolean flag);
187
}
188
```
189
190
**Parameters:**
191
- `event` - LoggingEvent to format
192
- `flag` - Boolean to enable location info or properties
193
194
**Returns:**
195
- `String` XML-formatted message, content type, header, or footer
196
- `boolean` location info or properties setting
197
198
## TTCCLayout (Legacy)
199
200
### TTCCLayout
201
202
```java { .api }
203
public class TTCCLayout extends DateLayout {
204
// Constructor
205
public TTCCLayout();
206
public TTCCLayout(String dateFormatType);
207
208
// Layout implementation
209
public String format(LoggingEvent event);
210
public boolean ignoresThrowable();
211
212
// Configuration
213
public boolean getThreadPrinting();
214
public void setThreadPrinting(boolean threadPrinting);
215
public boolean getCategoryPrefixing();
216
public void setCategoryPrefixing(boolean categoryPrefixing);
217
public boolean getContextPrinting();
218
public void setContextPrinting(boolean contextPrinting);
219
}
220
```
221
222
**Parameters:**
223
- `dateFormatType` - String date format type
224
- `event` - LoggingEvent to format
225
- `threadPrinting` - Boolean to enable thread printing
226
- `categoryPrefixing` - Boolean to enable category prefixing
227
- `contextPrinting` - Boolean to enable context printing
228
229
**Returns:**
230
- `String` formatted message in TTCC format
231
- `boolean` configuration settings
232
233
## Usage Examples
234
235
### PatternLayout Usage
236
```java
237
import org.apache.log4j.*;
238
239
public class PatternLayoutExample {
240
public void setupPatternLayouts() {
241
Logger logger = Logger.getLogger(PatternLayoutExample.class);
242
243
// Simple pattern
244
PatternLayout simplePattern = new PatternLayout("%d %-5p %c - %m%n");
245
ConsoleAppender console1 = new ConsoleAppender(simplePattern);
246
247
// Detailed pattern with location info
248
PatternLayout detailedPattern = new PatternLayout(
249
"%d{ISO8601} [%t] %-5p %c{1} %M:%L - %m%n"
250
);
251
ConsoleAppender console2 = new ConsoleAppender(detailedPattern);
252
253
// Pattern with MDC and NDC
254
PatternLayout contextPattern = new PatternLayout(
255
"%d{HH:mm:ss,SSS} [%t] %-5p %c - %X{userId} %x - %m%n"
256
);
257
ConsoleAppender console3 = new ConsoleAppender(contextPattern);
258
259
logger.addAppender(console1);
260
}
261
}
262
```
263
264
### Custom Date Patterns
265
```java
266
import org.apache.log4j.*;
267
268
public class DatePatternExample {
269
public void setupDatePatterns() {
270
// ISO 8601 format
271
PatternLayout isoPattern = new PatternLayout("%d{ISO8601} - %m%n");
272
273
// Custom date format
274
PatternLayout customPattern = new PatternLayout(
275
"%d{dd/MM/yyyy HH:mm:ss.SSS} [%p] %c - %m%n"
276
);
277
278
// Absolute time only
279
PatternLayout timeOnlyPattern = new PatternLayout("%d{ABSOLUTE} - %m%n");
280
281
// Multiple appenders with different date formats
282
FileAppender fileAppender = new FileAppender(isoPattern, "app.log");
283
ConsoleAppender consoleAppender = new ConsoleAppender(customPattern);
284
285
Logger logger = Logger.getRootLogger();
286
logger.addAppender(fileAppender);
287
logger.addAppender(consoleAppender);
288
}
289
}
290
```
291
292
### SimpleLayout Usage
293
```java
294
import org.apache.log4j.*;
295
296
public class SimpleLayoutExample {
297
public void setupSimpleLayout() {
298
// Create simple layout
299
SimpleLayout layout = new SimpleLayout();
300
301
// Create appender with simple layout
302
ConsoleAppender appender = new ConsoleAppender(layout);
303
appender.setName("simple-console");
304
305
// Add to logger
306
Logger logger = Logger.getLogger("simple");
307
logger.addAppender(appender);
308
logger.setLevel(Level.INFO);
309
310
// Log messages will appear as: "INFO - Your message"
311
logger.info("This is an info message");
312
logger.error("This is an error message");
313
}
314
}
315
```
316
317
### HTMLLayout Usage
318
```java
319
import org.apache.log4j.*;
320
import java.io.IOException;
321
322
public class HTMLLayoutExample {
323
public void setupHTMLLayout() throws IOException {
324
// Create HTML layout
325
HTMLLayout layout = new HTMLLayout();
326
layout.setTitle("Application Log");
327
layout.setLocationInfo(true);
328
329
// Create file appender with HTML layout
330
FileAppender appender = new FileAppender(layout, "app.html");
331
appender.setName("html-file");
332
333
// Add to logger
334
Logger logger = Logger.getLogger("html");
335
logger.addAppender(appender);
336
logger.setLevel(Level.DEBUG);
337
338
// Messages will be formatted as HTML table rows
339
logger.info("Application started");
340
logger.debug("Debug information");
341
}
342
}
343
```
344
345
### XMLLayout Usage
346
```java
347
import org.apache.log4j.*;
348
import java.io.IOException;
349
350
public class XMLLayoutExample {
351
public void setupXMLLayout() throws IOException {
352
// Create XML layout
353
XMLLayout layout = new XMLLayout();
354
layout.setLocationInfo(true);
355
layout.setProperties(true);
356
357
// Create file appender with XML layout
358
FileAppender appender = new FileAppender(layout, "app.xml");
359
appender.setName("xml-file");
360
361
// Add to logger
362
Logger logger = Logger.getLogger("xml");
363
logger.addAppender(appender);
364
365
// Messages will be formatted as XML elements
366
logger.info("Application event");
367
logger.warn("Warning message");
368
}
369
}
370
```
371
372
### Custom Layout Implementation
373
```java
374
import org.apache.log4j.Layout;
375
import org.apache.log4j.spi.LoggingEvent;
376
import java.text.SimpleDateFormat;
377
import java.util.Date;
378
379
public class CustomLayout extends Layout {
380
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
381
private boolean includeLocation = false;
382
383
public CustomLayout() {
384
super();
385
}
386
387
public CustomLayout(boolean includeLocation) {
388
this.includeLocation = includeLocation;
389
}
390
391
public boolean getIncludeLocation() {
392
return includeLocation;
393
}
394
395
public void setIncludeLocation(boolean includeLocation) {
396
this.includeLocation = includeLocation;
397
}
398
399
@Override
400
public String format(LoggingEvent event) {
401
StringBuilder sb = new StringBuilder();
402
403
// Add timestamp
404
sb.append("[").append(dateFormat.format(new Date(event.timeStamp))).append("] ");
405
406
// Add level
407
sb.append(event.getLevel().toString()).append(" ");
408
409
// Add logger name
410
sb.append(event.getLoggerName()).append(" ");
411
412
// Add location if enabled
413
if (includeLocation && event.getLocationInformation() != null) {
414
sb.append("(").append(event.getLocationInformation().getClassName());
415
sb.append(".").append(event.getLocationInformation().getMethodName());
416
sb.append(":").append(event.getLocationInformation().getLineNumber()).append(") ");
417
}
418
419
// Add message
420
sb.append("- ").append(event.getRenderedMessage());
421
422
// Add line separator
423
sb.append(LINE_SEP);
424
425
return sb.toString();
426
}
427
428
@Override
429
public boolean ignoresThrowable() {
430
return false; // We handle throwables
431
}
432
433
@Override
434
public void activateOptions() {
435
// No options to activate in this simple example
436
}
437
}
438
```
439
440
### Layout Configuration Examples
441
```java
442
import org.apache.log4j.*;
443
444
public class LayoutConfigurationExample {
445
public void setupMultipleLayouts() {
446
Logger logger = Logger.getLogger("multi-layout");
447
448
// Console with simple format
449
PatternLayout consoleLayout = new PatternLayout("%-5p %c{1} - %m%n");
450
ConsoleAppender consoleAppender = new ConsoleAppender(consoleLayout);
451
452
// File with detailed format
453
PatternLayout fileLayout = new PatternLayout(
454
"%d{ISO8601} [%t] %-5p %c %M:%L - %m%n"
455
);
456
FileAppender fileAppender;
457
try {
458
fileAppender = new FileAppender(fileLayout, "detailed.log");
459
logger.addAppender(fileAppender);
460
} catch (Exception e) {
461
System.err.println("Failed to create file appender: " + e.getMessage());
462
}
463
464
// HTML for web viewing
465
HTMLLayout htmlLayout = new HTMLLayout();
466
htmlLayout.setTitle("Application Events");
467
htmlLayout.setLocationInfo(true);
468
469
FileAppender htmlAppender;
470
try {
471
htmlAppender = new FileAppender(htmlLayout, "events.html");
472
logger.addAppender(htmlAppender);
473
} catch (Exception e) {
474
System.err.println("Failed to create HTML appender: " + e.getMessage());
475
}
476
477
logger.addAppender(consoleAppender);
478
logger.setLevel(Level.DEBUG);
479
}
480
}
481
```