or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

container-management.mddefault-logger.mdexception-rejection-handling.mdformats.mdindex.mdlogger-management.mdprofiling.mdtransports.md

container-management.mddocs/

0

# Container Management

1

2

Container class for managing multiple named logger instances with shared configurations and lifecycle management.

3

4

## Capabilities

5

6

### Container Class

7

8

The Container class provides an inversion of control pattern for managing multiple Winston logger instances by string identifiers.

9

10

```javascript { .api }

11

/**

12

* Container for managing multiple named logger instances

13

*/

14

class Container {

15

constructor(options?: LoggerOptions);

16

17

/** Map of logger instances by ID */

18

loggers: Map<string, Logger>;

19

/** Default options for new loggers */

20

options: LoggerOptions;

21

}

22

23

interface LoggerOptions {

24

/** Custom logging levels configuration */

25

levels?: object;

26

/** Suppress all logging output */

27

silent?: boolean;

28

/** Log message formatting configuration */

29

format?: Format;

30

/** Minimum logging level */

31

level?: string;

32

/** Controls process exit behavior on error */

33

exitOnError?: Function | boolean;

34

/** Default metadata to include with all log messages */

35

defaultMeta?: any;

36

/** Transport or array of transports for log output */

37

transports?: Transport[] | Transport;

38

/** Automatically handle uncaught exceptions */

39

handleExceptions?: boolean;

40

/** Automatically handle unhandled promise rejections */

41

handleRejections?: boolean;

42

/** Transports specifically for exception handling */

43

exceptionHandlers?: any;

44

/** Transports specifically for rejection handling */

45

rejectionHandlers?: any;

46

}

47

```

48

49

**Usage Examples:**

50

51

```javascript

52

const winston = require('winston');

53

54

// Create container with default options

55

const container = new winston.Container({

56

level: 'info',

57

format: winston.format.json(),

58

transports: [

59

new winston.transports.Console()

60

]

61

});

62

63

// Create container with shared transports

64

const sharedContainer = new winston.Container({

65

transports: [

66

new winston.transports.File({ filename: 'shared.log' })

67

]

68

});

69

```

70

71

### Logger Management

72

73

Methods for adding, retrieving, and managing logger instances within the container.

74

75

```javascript { .api }

76

/**

77

* Add or create a logger instance with the specified ID

78

* @param id - Unique identifier for the logger

79

* @param options - Optional configuration overriding container defaults

80

* @returns Logger instance

81

*/

82

add(id: string, options?: LoggerOptions): Logger;

83

84

/**

85

* Get a logger instance by ID, creating if it doesn't exist

86

* @param id - Unique identifier for the logger

87

* @param options - Optional configuration overriding container defaults

88

* @returns Logger instance

89

*/

90

get(id: string, options?: LoggerOptions): Logger;

91

92

/**

93

* Check if a logger with the specified ID exists

94

* @param id - Logger identifier to check

95

* @returns True if logger exists

96

*/

97

has(id: string): boolean;

98

99

/**

100

* Close and remove logger(s) from the container

101

* @param id - Optional logger ID to close (omit to close all)

102

*/

103

close(id?: string): void;

104

```

105

106

**Usage Examples:**

107

108

```javascript

109

const winston = require('winston');

110

111

const container = new winston.Container({

112

format: winston.format.json(),

113

transports: [

114

new winston.transports.Console()

115

]

116

});

117

118

// Add/create loggers

119

const apiLogger = container.add('api', {

120

level: 'debug',

121

defaultMeta: { service: 'api' }

122

});

123

124

const dbLogger = container.add('database', {

125

level: 'warn',

126

defaultMeta: { service: 'database' },

127

transports: [

128

new winston.transports.File({ filename: 'db.log' })

129

]

130

});

131

132

// Get existing logger (same as add if already exists)

133

const sameApiLogger = container.get('api');

134

console.log(apiLogger === sameApiLogger); // true

135

136

// Check existence

137

if (container.has('api')) {

138

const logger = container.get('api');

139

logger.info('API logger exists');

140

}

141

142

// Close specific logger

143

container.close('api');

144

145

// Close all loggers

146

container.close();

147

```

148

149

### Default Container Instance

150

151

Winston provides a default container instance accessible via `winston.loggers` for convenient multi-logger management.

152

153

```javascript { .api }

154

/**

155

* Default container instance available on winston module

156

*/

157

const loggers: Container;

158

```

159

160

**Usage Examples:**

161

162

```javascript

163

const winston = require('winston');

164

165

// Use default container

166

const userLogger = winston.loggers.get('user', {

167

level: 'info',

168

format: winston.format.simple(),

169

transports: [

170

new winston.transports.Console(),

171

new winston.transports.File({ filename: 'user.log' })

172

]

173

});

174

175

const authLogger = winston.loggers.get('auth', {

176

level: 'debug',

177

format: winston.format.json(),

178

transports: [

179

new winston.transports.File({ filename: 'auth.log' })

180

]

181

});

182

183

// Use loggers

184

userLogger.info('User registered', { userId: 123 });

185

authLogger.debug('Authentication attempt', { username: 'john' });

186

187

// In another file, get same logger instance

188

const sameUserLogger = winston.loggers.get('user');

189

sameUserLogger.info('User login'); // Uses same configuration

190

```

191

192

### Advanced Container Patterns

193

194

**Service-based logger organization:**

195

196

```javascript

197

const winston = require('winston');

198

199

// Create service-specific container

200

const serviceContainer = new winston.Container({

201

format: winston.format.combine(

202

winston.format.timestamp(),

203

winston.format.errors({ stack: true }),

204

winston.format.json()

205

),

206

transports: [

207

new winston.transports.File({ filename: 'services.log' })

208

]

209

});

210

211

// Create loggers for different services

212

const services = ['auth', 'user', 'payment', 'notification'];

213

const loggers = {};

214

215

services.forEach(service => {

216

loggers[service] = serviceContainer.add(service, {

217

defaultMeta: { service },

218

transports: [

219

new winston.transports.File({

220

filename: `${service}.log`,

221

level: 'info'

222

}),

223

new winston.transports.Console({

224

level: 'debug',

225

format: winston.format.simple()

226

})

227

]

228

});

229

});

230

231

// Use service loggers

232

loggers.auth.info('User authenticated');

233

loggers.payment.error('Payment processing failed');

234

```

235

236

**Environment-specific container configuration:**

237

238

```javascript

239

const winston = require('winston');

240

241

// Create environment-specific container

242

const createContainer = (env) => {

243

const baseConfig = {

244

level: env === 'production' ? 'info' : 'debug',

245

format: winston.format.combine(

246

winston.format.timestamp(),

247

winston.format.json()

248

)

249

};

250

251

if (env === 'production') {

252

baseConfig.transports = [

253

new winston.transports.File({ filename: 'app.log' })

254

];

255

} else {

256

baseConfig.transports = [

257

new winston.transports.Console({

258

format: winston.format.combine(

259

winston.format.colorize(),

260

winston.format.simple()

261

)

262

})

263

];

264

}

265

266

return new winston.Container(baseConfig);

267

};

268

269

const container = createContainer(process.env.NODE_ENV);

270

271

// Create environment-appropriate loggers

272

const appLogger = container.get('application');

273

const errorLogger = container.get('errors', {

274

level: 'error',

275

transports: [

276

new winston.transports.File({ filename: 'error.log' })

277

]

278

});

279

```

280

281

### Container Lifecycle Management

282

283

**Proper cleanup and resource management:**

284

285

```javascript

286

const winston = require('winston');

287

288

class LoggerManager {

289

constructor() {

290

this.container = new winston.Container();

291

this.loggers = new Map();

292

}

293

294

createLogger(name, options = {}) {

295

const logger = this.container.add(name, {

296

format: winston.format.json(),

297

...options

298

});

299

300

this.loggers.set(name, logger);

301

return logger;

302

}

303

304

getLogger(name) {

305

return this.loggers.get(name) || this.container.get(name);

306

}

307

308

removeLogger(name) {

309

this.container.close(name);

310

this.loggers.delete(name);

311

}

312

313

shutdown() {

314

// Close all loggers and clean up resources

315

this.container.close();

316

this.loggers.clear();

317

}

318

}

319

320

// Usage

321

const loggerManager = new LoggerManager();

322

323

const apiLogger = loggerManager.createLogger('api', {

324

level: 'debug',

325

transports: [new winston.transports.Console()]

326

});

327

328

// Graceful shutdown

329

process.on('SIGTERM', () => {

330

loggerManager.shutdown();

331

process.exit(0);

332

});

333

```