or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

basic-logging.mdfluent-logging.mdindex.mdmarkers.mdmdc.mdservice-providers.md

index.mddocs/

0

# SLF4J API

1

2

SLF4J (Simple Logging Facade for Java) is a logging facade that serves as an abstraction layer for various Java logging frameworks including java.util.logging, logback, reload4j, log4j 2.x, and logevents. The API allows developers to write logging code independent of any specific logging implementation, enabling runtime pluggability of logging frameworks.

3

4

SLF4J 2.0 introduces a modern fluent API while maintaining full backward compatibility with the traditional 1.x API.

5

6

## Package Information

7

8

- **Package Name**: slf4j-api

9

- **Package Type**: maven

10

- **Language**: Java

11

- **Installation**:

12

```xml

13

<dependency>

14

<groupId>org.slf4j</groupId>

15

<artifactId>slf4j-api</artifactId>

16

<version>2.0.17</version>

17

</dependency>

18

```

19

20

## Core Imports

21

22

```java

23

import org.slf4j.Logger;

24

import org.slf4j.LoggerFactory;

25

import org.slf4j.MDC;

26

import org.slf4j.Marker;

27

import org.slf4j.MarkerFactory;

28

```

29

30

For event-based logging (SLF4J 2.0):

31

```java

32

import org.slf4j.event.Level;

33

import org.slf4j.spi.LoggingEventBuilder;

34

import java.util.function.Supplier;

35

```

36

37

## Basic Usage

38

39

```java

40

import org.slf4j.Logger;

41

import org.slf4j.LoggerFactory;

42

43

public class MyClass {

44

private static final Logger logger = LoggerFactory.getLogger(MyClass.class);

45

46

public void doSomething() {

47

// Traditional logging

48

logger.info("Starting processing");

49

logger.debug("Processing item: {}", item.getName());

50

logger.warn("Issue detected: {}", issue);

51

logger.error("Failed to process", exception);

52

53

// Fluent API (SLF4J 2.0)

54

logger.atInfo()

55

.addArgument(user.getId())

56

.addKeyValue("action", "login")

57

.log("User {} logged in");

58

}

59

}

60

```

61

62

## Architecture

63

64

SLF4J consists of several key components:

65

66

- **LoggerFactory**: Static factory for obtaining Logger instances and managing service providers

67

- **Logger Interface**: Main logging contract with methods for all log levels

68

- **Service Provider Interface**: Pluggable architecture allowing different logging implementations

69

- **MDC (Mapped Diagnostic Context)**: Thread-local storage for contextual information

70

- **Markers**: Named objects for enriching and categorizing log statements

71

- **Fluent API**: Modern chainable logging interface introduced in SLF4J 2.0

72

- **Event System**: Structured logging events with lazy evaluation support

73

74

## Capabilities

75

76

### Basic Logging Operations

77

78

Traditional logging interface with methods for all standard log levels (TRACE, DEBUG, INFO, WARN, ERROR). Includes parameter substitution and exception handling.

79

80

```java { .api }

81

public interface Logger {

82

String getName();

83

84

// Level checking methods

85

boolean isTraceEnabled();

86

boolean isDebugEnabled();

87

boolean isInfoEnabled();

88

boolean isWarnEnabled();

89

boolean isErrorEnabled();

90

boolean isEnabledForLevel(Level level);

91

92

// Basic logging methods

93

void trace(String msg);

94

void debug(String msg);

95

void info(String msg);

96

void warn(String msg);

97

void error(String msg);

98

99

// Parameterized logging methods

100

void info(String format, Object arg);

101

void info(String format, Object arg1, Object arg2);

102

void info(String format, Object... arguments);

103

void info(String msg, Throwable t);

104

105

// Fluent API entry points

106

LoggingEventBuilder atTrace();

107

LoggingEventBuilder atDebug();

108

LoggingEventBuilder atInfo();

109

LoggingEventBuilder atWarn();

110

LoggingEventBuilder atError();

111

LoggingEventBuilder atLevel(Level level);

112

113

// Builder factory method (for SPI implementers)

114

LoggingEventBuilder makeLoggingEventBuilder(Level level);

115

}

116

117

public final class LoggerFactory {

118

public static Logger getLogger(String name);

119

public static Logger getLogger(Class<?> clazz);

120

public static ILoggerFactory getILoggerFactory();

121

}

122

```

123

124

[Basic Logging](./basic-logging.md)

125

126

### Fluent Logging API

127

128

Modern chainable logging interface introduced in SLF4J 2.0. Supports structured logging with key-value pairs, lazy evaluation, and builder pattern for complex log statements.

129

130

```java { .api }

131

public interface Logger {

132

LoggingEventBuilder atTrace();

133

LoggingEventBuilder atDebug();

134

LoggingEventBuilder atInfo();

135

LoggingEventBuilder atWarn();

136

LoggingEventBuilder atError();

137

LoggingEventBuilder atLevel(Level level);

138

}

139

140

public interface LoggingEventBuilder {

141

LoggingEventBuilder setCause(Throwable cause);

142

LoggingEventBuilder addMarker(Marker marker);

143

LoggingEventBuilder addArgument(Object p);

144

LoggingEventBuilder addArgument(Supplier<?> objectSupplier);

145

LoggingEventBuilder addKeyValue(String key, Object value);

146

LoggingEventBuilder addKeyValue(String key, Supplier<Object> valueSupplier);

147

LoggingEventBuilder setMessage(String message);

148

LoggingEventBuilder setMessage(Supplier<String> messageSupplier);

149

void log();

150

void log(String message);

151

void log(String message, Object arg);

152

void log(String message, Object arg0, Object arg1);

153

void log(String message, Object... args);

154

void log(Supplier<String> messageSupplier);

155

}

156

157

public enum Level {

158

ERROR, WARN, INFO, DEBUG, TRACE;

159

160

int toInt();

161

static Level intToLevel(int levelInt);

162

}

163

```

164

165

[Fluent Logging](./fluent-logging.md)

166

167

### Marker-Based Logging

168

169

Named objects for enriching and categorizing log statements. Markers can contain references to other markers and are evaluated by underlying logging implementations for filtering and routing.

170

171

```java { .api }

172

public interface Marker {

173

String getName();

174

void add(Marker reference);

175

boolean remove(Marker reference);

176

boolean contains(Marker other);

177

boolean contains(String name);

178

boolean hasReferences();

179

}

180

181

public class MarkerFactory {

182

public static Marker getMarker(String name);

183

public static Marker getDetachedMarker(String name);

184

public static IMarkerFactory getIMarkerFactory();

185

}

186

187

// Logger methods with marker support

188

public interface Logger {

189

void info(Marker marker, String msg);

190

void info(Marker marker, String format, Object arg);

191

void info(Marker marker, String format, Object... arguments);

192

boolean isInfoEnabled(Marker marker);

193

}

194

```

195

196

[Markers](./markers.md)

197

198

### Mapped Diagnostic Context (MDC)

199

200

Thread-local contextual information storage for associating diagnostic data with log statements. Supports both key-value maps and stack-based operations.

201

202

```java { .api }

203

public class MDC {

204

// Basic MDC operations

205

public static void put(String key, String val);

206

public static String get(String key);

207

public static void remove(String key);

208

public static void clear();

209

210

// Context map operations

211

public static Map<String, String> getCopyOfContextMap();

212

public static void setContextMap(Map<String, String> contextMap);

213

214

// Stack operations (SLF4J 2.0)

215

public static void pushByKey(String key, String value);

216

public static String popByKey(String key);

217

public static Deque<String> getCopyOfDequeByKey(String key);

218

219

// Auto-cleanup support

220

public static MDCCloseable putCloseable(String key, String val);

221

}

222

```

223

224

[MDC Operations](./mdc.md)

225

226

### Service Provider Interface

227

228

Pluggable architecture enabling different logging framework implementations. Provides factory interfaces and service provider contracts for extending SLF4J.

229

230

```java { .api }

231

public interface SLF4JServiceProvider {

232

ILoggerFactory getLoggerFactory();

233

IMarkerFactory getMarkerFactory();

234

MDCAdapter getMDCAdapter();

235

String getRequestedApiVersion();

236

void initialize();

237

}

238

239

public interface ILoggerFactory {

240

Logger getLogger(String name);

241

}

242

243

public interface IMarkerFactory {

244

Marker getMarker(String name);

245

boolean exists(String name);

246

Marker getDetachedMarker(String name);

247

}

248

```

249

250

[Service Providers](./service-providers.md)

251

252

## Types

253

254

### Core Types

255

256

```java { .api }

257

// Logger factory interface

258

public interface ILoggerFactory {

259

Logger getLogger(String name);

260

}

261

262

// Marker factory interface

263

public interface IMarkerFactory {

264

Marker getMarker(String name);

265

boolean exists(String name);

266

Marker getDetachedMarker(String name);

267

}

268

269

// MDC adapter interface

270

public interface MDCAdapter {

271

void put(String key, String val);

272

String get(String key);

273

void remove(String key);

274

void clear();

275

Map<String, String> getCopyOfContextMap();

276

void setContextMap(Map<String, String> contextMap);

277

void pushByKey(String key, String value);

278

String popByKey(String key);

279

Deque<String> getCopyOfDequeByKey(String key);

280

}

281

282

// Auto-closeable MDC wrapper

283

public static class MDC.MDCCloseable implements Closeable {

284

public void close();

285

}

286

```

287

288

### Event Types

289

290

```java { .api }

291

// Logging event interface

292

public interface LoggingEvent {

293

Level getLevel();

294

String getLoggerName();

295

String getMessage();

296

List<Object> getArguments();

297

Object[] getArgumentArray();

298

List<Marker> getMarkers();

299

List<KeyValuePair> getKeyValuePairs();

300

Throwable getThrowable();

301

long getTimeStamp();

302

String getThreadName();

303

String getCallerBoundary();

304

}

305

306

// Key-value pair for structured logging

307

public class KeyValuePair {

308

public final String key;

309

public final Object value;

310

311

public KeyValuePair(String key, Object value);

312

public String toString();

313

public boolean equals(Object o);

314

public int hashCode();

315

}

316

```

317

318

## Constants

319

320

```java { .api }

321

// Logger constants

322

public interface Logger {

323

String ROOT_LOGGER_NAME = "ROOT";

324

}

325

326

// Marker constants

327

public interface Marker {

328

String ANY_MARKER = "*";

329

String ANY_NON_NULL_MARKER = "+";

330

}

331

332

// Level integer constants

333

public class EventConstants {

334

public static final int ERROR_INT = 40;

335

public static final int WARN_INT = 30;

336

public static final int INFO_INT = 20;

337

public static final int DEBUG_INT = 10;

338

public static final int TRACE_INT = 0;

339

}

340

```