The Apache Log4j support for web servlet containers
npx @tessl/cli install tessl/maven-org-apache-logging-log4j--log4j-web@2.25.00
# Log4j Web
1
2
Log4j Web provides comprehensive support for integrating Apache Log4j 2 logging framework with Java EE web applications and servlet containers. It handles proper Log4j lifecycle management during web application startup and shutdown, provides web-specific logging utilities, and ensures thread-safe logging contexts in servlet environments.
3
4
## Package Information
5
6
- **Package Name**: log4j-web
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Group ID**: org.apache.logging.log4j
10
- **Artifact ID**: log4j-web
11
- **Installation**: Add to Maven `pom.xml`:
12
13
```xml
14
<dependency>
15
<groupId>org.apache.logging.log4j</groupId>
16
<artifactId>log4j-web</artifactId>
17
<version>2.25.1</version>
18
</dependency>
19
```
20
21
For Gradle:
22
23
```gradle
24
implementation 'org.apache.logging.log4j:log4j-web:2.25.1'
25
```
26
27
## Core Imports
28
29
```java
30
import org.apache.logging.log4j.web.Log4jWebSupport;
31
import org.apache.logging.log4j.web.WebLoggerContextUtils;
32
import org.apache.logging.log4j.web.Log4jServletContextListener;
33
import org.apache.logging.log4j.web.Log4jServletFilter;
34
import org.apache.logging.log4j.web.Log4jServletContainerInitializer;
35
import org.apache.logging.log4j.web.Log4jShutdownOnContextDestroyedListener;
36
import org.apache.logging.log4j.web.ServletRequestThreadContext;
37
import org.apache.logging.log4j.web.WebLookup;
38
import org.apache.logging.log4j.web.appender.ServletAppender;
39
```
40
41
## Basic Usage
42
43
### Automatic Configuration (Servlet 3.0+)
44
45
Log4j Web automatically configures itself in Servlet 3.0+ environments without any manual setup:
46
47
```java
48
// No manual configuration needed - Log4jServletContainerInitializer
49
// automatically registers listeners and filters
50
```
51
52
### Manual Configuration (Pre-Servlet 3.0)
53
54
Add to `web.xml`:
55
56
```xml
57
<listener>
58
<listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
59
</listener>
60
<filter>
61
<filter-name>log4jServletFilter</filter-name>
62
<filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>
63
</filter>
64
<filter-mapping>
65
<filter-name>log4jServletFilter</filter-name>
66
<url-pattern>/*</url-pattern>
67
</filter-mapping>
68
```
69
70
### Async Request Context Management
71
72
```java
73
import org.apache.logging.log4j.web.WebLoggerContextUtils;
74
75
// In async servlets, wrap async tasks with proper logging context
76
ServletContext servletContext = request.getServletContext();
77
Runnable wrappedTask = WebLoggerContextUtils.wrapExecutionContext(
78
servletContext,
79
() -> {
80
// Your async task code here
81
Logger logger = LogManager.getLogger();
82
logger.info("Executing async task with proper logging context");
83
}
84
);
85
```
86
87
## Architecture
88
89
Log4j Web is built around several key components that integrate seamlessly with servlet containers:
90
91
- **Lifecycle Management**: Automatic initialization and shutdown handling via servlet container callbacks
92
- **Context Binding**: Thread-local LoggerContext management for per-request logging isolation
93
- **Web-Specific Features**: Servlet context lookups, request information capture, and servlet appenders
94
- **Container Integration**: Support for both automatic (Servlet 3.0+) and manual configuration patterns
95
- **Async Support**: Proper context propagation for asynchronous request processing
96
97
The design ensures that Log4j is properly initialized before any application code runs and cleanly shut down after the application stops, while providing thread-safe logging contexts for concurrent request processing.
98
99
## Capabilities
100
101
### Servlet Integration Components
102
103
Core servlet lifecycle components including context listeners, filters, and container initializers that manage Log4j startup, shutdown, and per-request context binding.
104
105
```java { .api }
106
public class Log4jServletContextListener implements ServletContextListener {
107
public void contextInitialized(ServletContextEvent event);
108
public void contextDestroyed(ServletContextEvent event);
109
}
110
111
public class Log4jServletFilter implements Filter {
112
public void init(FilterConfig filterConfig) throws ServletException;
113
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException;
114
public void destroy();
115
}
116
117
public class Log4jServletContainerInitializer implements ServletContainerInitializer {
118
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException;
119
}
120
```
121
122
[Servlet Integration](./servlet-integration.md)
123
124
### Logger Context Management
125
126
Utilities for managing LoggerContext instances in web applications, including context retrieval, lifecycle management, and execution wrapping for async operations.
127
128
```java { .api }
129
public final class WebLoggerContextUtils {
130
public static LoggerContext getWebLoggerContext(ServletContext servletContext);
131
public static LoggerContext getRequiredWebLoggerContext(ServletContext servletContext);
132
public static Log4jWebLifeCycle getWebLifeCycle(ServletContext servletContext);
133
public static Runnable wrapExecutionContext(ServletContext servletContext, Runnable runnable);
134
public static ServletContext getServletContext();
135
}
136
137
public interface Log4jWebSupport {
138
void setLoggerContext();
139
void clearLoggerContext();
140
void wrapExecution(Runnable runnable);
141
}
142
```
143
144
[Logger Context Management](./logger-context-management.md)
145
146
### Web-Specific Logging Features
147
148
Web-aware logging components including servlet context lookups for configuration variables, servlet appenders for direct logging to container logs, and thread context utilities for capturing request information.
149
150
```java { .api }
151
@Plugin(name = "web", category = "Lookup")
152
public class WebLookup extends AbstractLookup {
153
public String lookup(LogEvent event, String key);
154
}
155
156
@Plugin(name = "Servlet", category = "Core", elementType = "appender", printObject = true)
157
public final class ServletAppender extends AbstractAppender {
158
public void append(LogEvent event);
159
public static <B extends Builder<B>> B newBuilder();
160
}
161
162
public class ServletRequestThreadContext {
163
public static void put(String key, ServletRequest servletRequest);
164
public static void put(String key, HttpServletRequest servletRequest);
165
}
166
```
167
168
[Web-Specific Features](./web-specific-features.md)
169
170
## Configuration Parameters
171
172
### Context Parameters
173
174
These parameters can be set in `web.xml` or programmatically via `ServletContext.setInitParameter()`:
175
176
- **`log4jContextName`**: Name for the LoggerContext (required for JNDI configurations)
177
- **`log4jConfiguration`**: Location of Log4j configuration file
178
- **`isLog4jContextSelectorNamed`**: Set to "true" to enable JNDI context selector
179
- **`isLog4jAutoInitializationDisabled`**: Set to "true" to disable automatic initialization in Servlet 3.0+
180
- **`isLog4jAutoShutdownDisabled`**: Set to "true" to disable automatic shutdown in Servlet 3.0+
181
- **`log4j.stop.timeout`**: Shutdown timeout in seconds (default: 30)
182
- **`log4j.stop.timeout.timeunit`**: Timeout time unit (default: SECONDS)
183
184
## Error Handling
185
186
Log4j Web handles various error conditions gracefully:
187
188
- **Duplicate Initialization**: Prevents multiple initialization attempts via reference counting
189
- **Missing Context**: Throws `IllegalStateException` when required LoggerContext is missing
190
- **Configuration Errors**: Logs warnings for invalid configurations and falls back to defaults
191
- **Shutdown Timeout**: Supports configurable timeout for graceful shutdown with fallback to forced shutdown
192
193
Common exceptions:
194
- `IllegalStateException`: Thrown when Log4j Web components are in invalid states
195
- `ServletException`: Propagated from underlying servlet container issues