or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mdlogger-context-management.mdservlet-integration.mdweb-specific-features.md

servlet-integration.mddocs/

0

# Servlet Integration

1

2

Core servlet lifecycle components that manage Log4j startup, shutdown, and per-request context binding. These components ensure proper Log4j integration with servlet containers across different environments and configuration patterns.

3

4

## Capabilities

5

6

### Log4jServletContextListener

7

8

Context listener responsible for initializing and deinitializing Log4j in servlet environments, particularly for pre-Servlet 3.0 containers or when automatic initialization is disabled.

9

10

```java { .api }

11

/**

12

* ServletContextListener for managing Log4j lifecycle in web applications.

13

* Handles startup initialization and shutdown cleanup of Log4j logging context.

14

*/

15

public class Log4jServletContextListener implements ServletContextListener {

16

17

/** ServletContext attribute for tracking start count */

18

static final String START_COUNT_ATTR =

19

"org.apache.logging.log4j.web.Log4jServletContextListener.START_COUNT";

20

21

/** Default shutdown timeout in seconds */

22

private static final int DEFAULT_STOP_TIMEOUT = 30;

23

24

/** Default timeout time unit */

25

private static final TimeUnit DEFAULT_STOP_TIMEOUT_TIMEUNIT = TimeUnit.SECONDS;

26

27

/** Context parameter key for shutdown timeout */

28

private static final String KEY_STOP_TIMEOUT = "log4j.stop.timeout";

29

30

/** Context parameter key for timeout time unit */

31

private static final String KEY_STOP_TIMEOUT_TIMEUNIT = "log4j.stop.timeout.timeunit";

32

33

/**

34

* Initializes Log4j when the servlet context starts.

35

* Sets up LoggerContext and prepares logging infrastructure.

36

* Implements reference counting to handle multiple registrations.

37

*

38

* @param event ServletContextEvent containing the ServletContext

39

* @throws IllegalStateException if auto-shutdown is disabled or initialization fails

40

*/

41

public void contextInitialized(ServletContextEvent event);

42

43

/**

44

* Shuts down Log4j when the servlet context is destroyed.

45

* Cleanly stops the LoggerContext with configurable timeout.

46

* Uses reference counting to ensure proper shutdown timing.

47

*

48

* @param event ServletContextEvent containing the ServletContext

49

* @throws IllegalStateException if shutdown fails

50

*/

51

public void contextDestroyed(ServletContextEvent event);

52

}

53

```

54

55

**Configuration in web.xml:**

56

57

```xml

58

<listener>

59

<listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>

60

</listener>

61

```

62

63

**Usage Notes:**

64

- Use only when `isLog4jAutoShutdownDisabled` is false

65

- For shutdown-only scenarios, use `Log4jShutdownOnContextDestroyedListener` instead

66

- Supports configurable shutdown timeout via `log4j.stop.timeout` context parameter

67

68

### Log4jServletFilter

69

70

Per-request filter that manages LoggerContext binding for individual HTTP requests. Ensures proper logging context isolation and cleanup for concurrent request processing.

71

72

```java { .api }

73

/**

74

* Filter that manages LoggerContext on a per-request basis.

75

* Sets context before request processing and clears after completion.

76

* Implements once-per-request filtering to handle multiple dispatch types.

77

*/

78

public class Log4jServletFilter implements Filter {

79

80

/**

81

* Initializes the filter with servlet context reference.

82

* Clears logger context to indicate application startup completion.

83

*

84

* @param filterConfig FilterConfig containing initialization parameters

85

* @throws ServletException if initialization fails

86

*/

87

public void init(FilterConfig filterConfig) throws ServletException;

88

89

/**

90

* Processes each request with proper LoggerContext binding.

91

* Sets context before chain execution, clears after completion.

92

* Uses request attribute to prevent duplicate processing.

93

*

94

* @param request ServletRequest being processed

95

* @param response ServletResponse for the request

96

* @param chain FilterChain for continuing request processing

97

* @throws IOException if I/O error occurs during filtering

98

* @throws ServletException if servlet processing error occurs

99

*/

100

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

101

throws IOException, ServletException;

102

103

/**

104

* Cleans up filter resources and sets LoggerContext for shutdown.

105

* Called when filter is taken out of service.

106

*

107

* @throws IllegalStateException if filter destroyed before initialization

108

*/

109

public void destroy();

110

}

111

```

112

113

**Configuration in web.xml:**

114

115

```xml

116

<filter>

117

<filter-name>log4jServletFilter</filter-name>

118

<filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>

119

</filter>

120

<filter-mapping>

121

<filter-name>log4jServletFilter</filter-name>

122

<url-pattern>/*</url-pattern>

123

<dispatcher>REQUEST</dispatcher>

124

<dispatcher>FORWARD</dispatcher>

125

<dispatcher>INCLUDE</dispatcher>

126

<dispatcher>ERROR</dispatcher>

127

</filter-mapping>

128

```

129

130

**Filter Constants:**

131

132

```java { .api }

133

public class Log4jServletFilter implements Filter {

134

/** Request attribute name to prevent duplicate filtering */

135

static final String ALREADY_FILTERED_ATTRIBUTE =

136

Log4jServletFilter.class.getName() + ".FILTERED";

137

}

138

```

139

140

### Log4jServletContainerInitializer

141

142

Servlet 3.0+ container initializer that automatically configures Log4j without requiring manual web.xml configuration. Provides zero-configuration setup for modern servlet containers.

143

144

```java { .api }

145

/**

146

* ServletContainerInitializer for automatic Log4j setup in Servlet 3.0+ environments.

147

* Automatically registers listeners and filters without web.xml configuration.

148

*/

149

public class Log4jServletContainerInitializer implements ServletContainerInitializer {

150

151

/**

152

* Automatically configures Log4j components during container startup.

153

* Registers Log4jServletFilter and optionally Log4jServletContextListener.

154

* Only activates in Servlet 3.0+ when auto-initialization is enabled.

155

*

156

* @param classes Set of classes found during annotation scanning (unused)

157

* @param servletContext ServletContext for registration and configuration

158

* @throws ServletException if automatic configuration fails

159

*/

160

public void onStartup(Set<Class<?>> classes, ServletContext servletContext)

161

throws ServletException;

162

}

163

```

164

165

**Automatic Registration Process:**

166

1. Verifies Servlet 3.0+ environment

167

2. Checks that auto-initialization is enabled

168

3. Registers `Log4jServletFilter` with async support

169

4. Maps filter to all URLs with all dispatcher types

170

5. Optionally registers `Log4jServletContextListener` for shutdown handling

171

172

**Disabling Auto-Configuration:**

173

174

```xml

175

<context-param>

176

<param-name>isLog4jAutoInitializationDisabled</param-name>

177

<param-value>true</param-value>

178

</context-param>

179

```

180

181

### Log4jShutdownOnContextDestroyedListener

182

183

Specialized context listener for shutdown-only scenarios when automatic shutdown is disabled. Used when application manually manages Log4j initialization but needs automatic cleanup.

184

185

```java { .api }

186

/**

187

* ServletContextListener for Log4j shutdown when auto-shutdown is disabled.

188

* Validates Log4j setup during initialization, performs cleanup during shutdown.

189

*/

190

public class Log4jShutdownOnContextDestroyedListener implements ServletContextListener {

191

192

/**

193

* Validates that Log4j WebLifeCycle is properly initialized.

194

* Does not perform initialization, only verification.

195

*

196

* @param event ServletContextEvent containing the ServletContext

197

* @throws IllegalStateException if Log4jWebLifeCycle is not found

198

*/

199

public void contextInitialized(ServletContextEvent event);

200

201

/**

202

* Performs Log4j shutdown with configurable timeout.

203

* Clears LoggerContext and stops logging infrastructure.

204

*

205

* @param event ServletContextEvent containing the ServletContext

206

*/

207

public void contextDestroyed(ServletContextEvent event);

208

}

209

```

210

211

**When to Use:**

212

- Application manually initializes Log4j (e.g., programmatically)

213

- `isLog4jAutoShutdownDisabled` is set to "true"

214

- Need guaranteed cleanup without full lifecycle management

215

216

## Integration Patterns

217

218

### Servlet 3.0+ Automatic (Recommended)

219

220

```java

221

// No configuration needed - automatic registration via SPI

222

// Log4jServletContainerInitializer handles all setup

223

```

224

225

### Pre-Servlet 3.0 Manual Configuration

226

227

```xml

228

<web-app>

229

<listener>

230

<listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>

231

</listener>

232

<filter>

233

<filter-name>log4jServletFilter</filter-name>

234

<filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>

235

</filter>

236

<filter-mapping>

237

<filter-name>log4jServletFilter</filter-name>

238

<url-pattern>/*</url-pattern>

239

</filter-mapping>

240

</web-app>

241

```

242

243

### Custom Initialization with Auto-Shutdown

244

245

```xml

246

<context-param>

247

<param-name>isLog4jAutoInitializationDisabled</param-name>

248

<param-value>true</param-value>

249

</context-param>

250

```

251

252

```java

253

// Custom initialization code

254

Log4jWebLifeCycle initializer = WebLoggerContextUtils.getWebLifeCycle(servletContext);

255

initializer.start();

256

257

// Auto-shutdown still occurs via Log4jServletContainerInitializer

258

```

259

260

### Shutdown-Only Management

261

262

```xml

263

<context-param>

264

<param-name>isLog4jAutoShutdownDisabled</param-name>

265

<param-value>true</param-value>

266

</context-param>

267

<listener>

268

<listener-class>org.apache.logging.log4j.web.Log4jShutdownOnContextDestroyedListener</listener-class>

269

</listener>

270

```

271

272

## Reference Counting

273

274

The `Log4jServletContextListener` implements reference counting to handle scenarios where it might be registered multiple times:

275

276

```java { .api }

277

public class Log4jServletContextListener implements ServletContextListener {

278

/** ServletContext attribute for tracking start count */

279

static final String START_COUNT_ATTR =

280

"org.apache.logging.log4j.web.Log4jServletContextListener.START_COUNT";

281

}

282

```

283

284

This ensures Log4j is initialized only once and shut down only after all registrations are complete.

285

286

## Configuration Constants

287

288

### Timeout Configuration

289

290

Both `Log4jServletContextListener` and `Log4jShutdownOnContextDestroyedListener` support configurable shutdown timeouts:

291

292

```java { .api }

293

public class Log4jServletContextListener implements ServletContextListener {

294

/** Default shutdown timeout in seconds */

295

private static final int DEFAULT_STOP_TIMEOUT = 30;

296

297

/** Default timeout time unit */

298

private static final TimeUnit DEFAULT_STOP_TIMEOUT_TIMEUNIT = TimeUnit.SECONDS;

299

300

/** Context parameter key for shutdown timeout */

301

private static final String KEY_STOP_TIMEOUT = "log4j.stop.timeout";

302

303

/** Context parameter key for timeout time unit */

304

private static final String KEY_STOP_TIMEOUT_TIMEUNIT = "log4j.stop.timeout.timeunit";

305

}

306

```

307

308

**Configuration in web.xml:**

309

310

```xml

311

<context-param>

312

<param-name>log4j.stop.timeout</param-name>

313

<param-value>60</param-value>

314

</context-param>

315

<context-param>

316

<param-name>log4j.stop.timeout.timeunit</param-name>

317

<param-value>SECONDS</param-value>

318

</context-param>

319

```