@tgtone/logger
v1.2.0
Published
Debug logger utility for TGT One projects
Readme
@tgtone/logger
Debug logger utility for TGT One projects with environment-based control
Features
- ✅ Environment-aware: Control via
VITE_LOG_LEVELS(browser) orLOG_LEVELS(Node.js) - ✅ Browser & Node.js compatible: Works in both environments without polyfills
- ✅ Multiple log levels: debug, info, warn, error
- ✅ Namespace support: Organize logs by module/service
- ✅ Child loggers: Create nested loggers that inherit configuration
- ✅ Timestamp support: Optional ISO timestamp in each log
- ✅ Production-safe: Control exactly which levels to show
- ✅ Zero dependencies: Lightweight and fast
- ✅ TypeScript: Fully typed
- ✅ Vite-ready: No
defineconfig needed
Installation
npm install @tgtone/loggerQuick Start
Basic Usage
import { debug, info, warn, error } from '@tgtone/logger';
debug('🐛 Debug information'); // Shows if 'debug' in VITE_LOG_LEVELS
info('ℹ️ Important information'); // Shows if 'info' in VITE_LOG_LEVELS
warn('⚠️ Warning message'); // Shows if 'warn' in VITE_LOG_LEVELS
error('❌ Error occurred'); // Shows if 'error' in VITE_LOG_LEVELSWith Namespace
import { Logger } from '@tgtone/logger';
const logger = new Logger({ namespace: 'AuthService' });
logger.debug('Token validation started');
// 🐛 [AuthService] Token validation started
logger.info('User logged in:', user.email);
// ℹ️ [AuthService] User logged in: [email protected]With Timestamp
import { Logger } from '@tgtone/logger';
const logger = new Logger({ namespace: 'API', timestamp: true });
logger.debug('Request received');
// [2024-01-15T10:30:00.000Z] 🐛 [API] Request receivedChild Loggers
const authLogger = new Logger({ namespace: 'Auth' });
const jwtLogger = authLogger.child('JWT');
jwtLogger.debug('Verifying token');
// 🐛 [Auth:JWT] Verifying tokenConfiguration
Environment Variables
Control log levels via environment variables:
| Variable | Environment | Example |
|----------|-------------|---------|
| VITE_LOG_LEVELS | Browser (Vite) | VITE_LOG_LEVELS=debug,info |
| LOG_LEVELS | Node.js | LOG_LEVELS=warn,error |
Log Level Values
| Valor | Resultado |
|-------|-----------|
| * o no definido | Todos los niveles habilitados |
| debug,info,warn | Solo debug, info y warn |
| error | Solo errores |
| none | Deshabilita todos los niveles |
Browser Usage (React/Vue/Svelte with Vite)
# .env.local
VITE_LOG_LEVELS=* # Todos los niveles (desarrollo)
VITE_LOG_LEVELS=error # Solo errores (producción)
VITE_LOG_LEVELS=debug,info # Solo debug e infoimport { Logger } from '@tgtone/logger';
// El logger lee automáticamente VITE_LOG_LEVELS
const logger = new Logger({ namespace: 'MyApp' });
logger.debug('This shows if debug is enabled');Node.js Usage (Backend/NestJS/Express)
# Development
LOG_LEVELS=* npm run start
# Production
LOG_LEVELS=error npm run start:prodimport { Logger } from '@tgtone/logger';
// El logger lee automáticamente LOG_LEVELS
const logger = new Logger({ namespace: 'AuthService' });Programmatic Config
import { Logger, LogLevel } from '@tgtone/logger';
const logger = new Logger({
namespace: 'MyService', // Add namespace prefix
emojis: true, // Enable emojis (default: true)
timestamp: true, // Show ISO timestamp (default: false)
minLevel: LogLevel.INFO, // Minimum log level (fallback)
allowedLevels: [LogLevel.DEBUG, LogLevel.INFO], // Specific levels
});Log Levels
import { LogLevel } from '@tgtone/logger';
LogLevel.DEBUG // 🐛 Debug information
LogLevel.INFO // ℹ️ General information
LogLevel.WARN // ⚠️ Warnings
LogLevel.ERROR // ❌ Errors
LogLevel.NONE // 🚫 Disable all logsAPI Reference
Logger
class Logger {
constructor(config?: LoggerConfig)
debug(...args: any[]): void
info(...args: any[]): void
warn(...args: any[]): void
error(...args: any[]): void
child(namespace: string): Logger
isDebugEnabled(): boolean
}LoggerConfig
interface LoggerConfig {
namespace?: string; // Prefix for all logs
emojis?: boolean; // Show emojis (default: true)
timestamp?: boolean; // Show ISO timestamp (default: false)
minLevel?: LogLevel; // Minimum level (default: DEBUG)
allowedLevels?: LogLevel[]; // Specific allowed levels
}Helper Functions
import { debug, info, warn, error, defaultLogger } from '@tgtone/logger';
// Use default logger directly
debug('Message');
info('Message');
warn('Message');
error('Message');
// Or access the default logger instance
defaultLogger.debug('Message');Use Cases
NestJS Services
import { Logger } from '@tgtone/logger';
export class AuthService {
private logger = new Logger({ namespace: 'AuthService' });
async login(email: string, password: string) {
this.logger.debug('Login attempt:', email);
// ... authentication logic
this.logger.info('User logged in:', email);
}
}React Components
import { Logger } from '@tgtone/logger';
const logger = new Logger({ namespace: 'useAuth' });
export function useAuth() {
const login = async (email: string) => {
logger.debug('Login attempt:', email);
// ...
};
return { login };
}API Client
import { Logger } from '@tgtone/logger';
const logger = new Logger({ namespace: 'API', timestamp: true });
async function fetchData(url: string) {
logger.debug('Fetching:', url);
try {
const response = await fetch(url);
logger.info('Response:', response.status);
return response;
} catch (error) {
logger.error('Fetch failed:', error);
throw error;
}
}Migration from console.log
Before:
console.log('🔍 Token found:', token);
console.log('📋 Payload:', payload);After:
import { debug } from '@tgtone/logger';
debug('Token found:', token);
debug('Payload:', payload);Production Behavior
With VITE_LOG_LEVELS=error or LOG_LEVELS=error:
- ✅
error()→ shown - ❌
debug(),info(),warn()→ suppressed
Development Behavior
With VITE_LOG_LEVELS=* or not defined:
- ✅ All log levels shown
Changelog
1.2.0
- ✨ Added
timestampoption for ISO timestamp in logs - ✨ Added
LOG_LEVEL_PRIORITYfor level hierarchy - 🐛 Fixed
child()to properly passallowedLevels - 🐛 Fixed
isDebugEnabled()to be consistent withshouldLog() - 🔥 Removed deprecated
debugEnabledproperty - 🎨 Changed debug emoji from
🔍to🐛
1.1.0
- Initial release with VITE_LOG_LEVELS support
License
MIT
Author
TGT Technology
