Version: 1.0
Last Updated: December 12, 2024
File: src/services/logger.service.ts
The Logger Service is a centralized, structured logging system that replaces direct console.* calls throughout the application. It provides:
| Feature | console.log | Logger Service |
|---|---|---|
| Structured data | ❌ No | ✅ Yes (metadata) |
| Log levels | ❌ No | ✅ Yes (DEBUG, INFO, WARN, ERROR) |
| Environment aware | ❌ No | ✅ Yes |
| Filterable | ❌ No | ✅ Yes |
| Remote logging | ❌ No | ✅ Yes |
| Service context | ❌ No | ✅ Yes (scoped loggers) |
| Production safe | ❌ No | ✅ Yes |
┌─────────────────────────────────────────────────────────┐ │ Your Application Code │ │ logger.info('User logged in', { userId: '123' }) │ └────────────────────┬────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────┐ │ Logger Service (logger.service.ts) │ │ • Checks log level threshold │ │ • Adds timestamp, service name, metadata │ │ • Stores in buffer (last 100 entries) │ │ • Decides where to output │ └─────┬─────────────────────────┬─────────────────────────┘ │ │ │ Development │ Production ▼ ▼ ┌──────────────────┐ ┌────────────────────────────────┐ │ Browser Console │ │ Remote Logging Service │ │ • Colored logs │ │ • Error tracking │ │ • Full details │ │ • Log aggregation │ │ • Stack traces │ │ • Monitoring dashboard │ └──────────────────┘ └────────────────────────────────┘
logger.info('message', { metadata })This is where you'll see most logs during development.
F12 or Ctrl+Shift+I (Windows) / Cmd+Option+I (Mac)F12 or Ctrl+Shift+K (Windows) / Cmd+Option+K (Mac)Cmd+Option+CLog entries formatted as [LEVEL] timestamp: message followed by metadata on the next line. Errors include stack traces.
By level:
By service: Type service: "UserService" in the console filter box
By text: Type any search term in the console filter box
Access recent logs programmatically in the console.
Import logger from ./src/services/logger.service and call logger.getRecentLogs(10) to get the last N log entries. Each entry contains timestamp, level (numeric), message, metadata, and service name.
In production, logs are sent to a remote service.
F12)fetch or your logging endpoint URLThe payload includes timestamp, level, message, metadata, error details (if applicable), and service name.
For production environments, integrate with monitoring services:
The setup involves configuring the logger's remoteOutput method to forward log entries to the chosen service (e.g., Sentry.captureMessage for Sentry integration).
Import logger from @/config or @/services/logger.service.
Use logger.info(message, metadata) for general information, logger.warn(message, metadata) for warnings, logger.error(message, error, metadata) for errors, and logger.debug(message, metadata) for detailed debugging info (development only).
Open browser console (F12) and you'll see formatted log entries with level, timestamp, message, and metadata.
Create a logger specific to your service/component using createLogger('ServiceName'). This automatically prefixes all log entries with the service name, making logs easy to filter.
Benefits:
Call logger.getRecentLogs(count) to retrieve recent log entries. You can then filter them by level, serialize to JSON, or analyze error patterns.
Use environment checks (env.isDevelopment, env.features.enableLogging) to conditionally log sensitive or verbose information only when appropriate.
The LoggerConfig interface has these fields: minLevel (minimum level to log), enableConsole (boolean), enableRemote (boolean), remoteEndpoint (optional URL), and serviceName (default service name).
In development, minLevel is LogLevel.DEBUG and console logging is enabled. In production, minLevel is LogLevel.INFO and remote logging is enabled when analytics is active.
Call logger.configure(config) at runtime to update settings such as minLevel, enableRemote, or remoteEndpoint.
DEBUG = 0 - Detailed debug information (dev only)INFO = 1 - General informational messagesWARN = 2 - Warning messagesERROR = 3 - Error messagesNONE = 4 - Disable all loggingLevel Hierarchy: If minLevel = LogLevel.WARN, only WARN and ERROR logs are output. DEBUG < INFO < WARN < ERROR < NONE.
const logger = createLogger('MyService')console.* directly — use logger.info insteadCreate a scoped logger as a class property. In each method, log before the operation (with relevant IDs), then log success with result metadata, and catch/log errors with the error object and context before re-throwing.
In useEffect, log mount/unmount events with relevant props. In event handlers, log the action, then success or failure.
Solutions:
Check console filter level — Open Console Settings (gear icon) and ensure "Info" is enabled
Check browser console level — Make sure console is set to "All levels" or "Verbose"
Check logger configuration — Import logger from @/config and call logger.configure({ minLevel: LogLevel.DEBUG, enableConsole: true })
Check environment — Import env from @/config and verify env.features.enableLogging and env.nodeEnv
Expected behavior: Only INFO, WARN, and ERROR logs appear in production (DEBUG is filtered out).
To verify: Check env.nodeEnv (should be 'production') and env.isProduction (should be true).
Solutions:
Increase minimum log level — Call logger.configure({ minLevel: LogLevel.WARN })
Filter in console — Use console filter -service:VerboseService or disable INFO logs by clicking their level indicator
Use scoped loggers and filter — Type service: "ImportantService" in the console filter
Solution: Import logger from @/config (not via createLogger, which returns a scoped logger without getRecentLogs).
A scoped logger created as createLogger('AuthService') is used throughout the AuthService class. On login, it logs the attempt with the email, then on success logs the userId and loginMethod. Sensitive session details are only logged in development. On failure, it logs the error with email, reason, and timestamp before re-throwing. The logout method similarly logs initiation, success, or partial failure.
An ApiClient using createLogger('ApiClient') logs each request attempt with endpoint and method. On each retry it logs a warning with attempt number, error message, and next retry delay. After all retries fail it logs an error with total duration before throwing.
A MaterialSearch component logs mount/unmount events via useEffect. Before searching it logs the query, on completion it logs result count, and on error it logs the failure with the query.
Import logger and createLogger from @/config.
logger.debug(message, metadata) — Dev onlylogger.info(message, metadata) — General infologger.warn(message, metadata) — Warningslogger.error(message, error, metadata) — ErrorsCreate with createLogger('ServiceName') then call methods on the returned logger instance.
logger.getRecentLogs(count) — Get recent logslogger.clearBuffer() — Clear log bufferlogger.configure(config) — Update configurationF12)logger.getRecentLogs() in consoleIf you have questions or issues:
src/services/logger.service.ts implementationMIGRATION_GUIDE.mdLast Updated: December 12, 2024 Version: 1.0 Status: Production Ready ✅