Environment-Aware Logging
Logluxe automatically adapts to your environment and provides smart logging utilities for different contexts.
Environment Detection
Logluxe automatically detects:
- Node.js vs Browser
- Development vs Production
- CI/CD environments
- TTY vs non-TTY terminals
- Color support level
import { log, env } from 'logluxe';
console.log(env.isNode); // true in Node.js
console.log(env.isBrowser); // true in browsers
console.log(env.isDev); // true if NODE_ENV !== 'production'
console.log(env.isProd); // true if NODE_ENV === 'production'
console.log(env.isCI); // true in CI environments
console.log(env.isTTY); // true if terminal supports TTY
console.log(env.colorLevel); // 0, 1, 2, or 3 (color support)
Environment Detection
ℹℹ env.isNode: true
ℹℹ env.isBrowser: false
ℹℹ env.isDev: true
ℹℹ env.isProd: false
ℹℹ env.isCI: false
ℹℹ env.isTTY: true
ℹℹ env.colorLevel: 3
Development-Only Logging
log.dev(message)
Only logs in development mode:
log.dev('This only appears in development');
log.dev('Debug info:', debugData);
// In production: nothing is logged
// In development: messages appear
Development Mode
●● This only appears in development
●● Debug info: { user: 'john', action: 'login' }
(In production: nothing logged)
Use Cases
// Debug information during development
log.dev(`User ID: ${user.id}`);
log.dev(`Request body:`, req.body);
log.dev(`Query took ${duration}ms`);
// Verbose logging in dev only
log.dev('Entering function processData()');
log.dev('Step 1: Validating input');
log.dev('Step 2: Transforming data');
log.dev('Exiting function processData()');
🎮 Try Development Logging
Production-Only Logging
log.prod(message)
Only logs in production mode:
log.prod('Application started in production mode');
log.prod(`Server listening on port ${PORT}`);
// In development: nothing is logged
// In production: messages appear
Production Mode
ℹℹ Application started in production mode
ℹℹ Server listening on port 3000
(In development: nothing logged)
Use Cases
// Important production events
log.prod('Payment processed successfully');
log.prod(`New user registered: ${user.email}`);
log.prod('Scheduled backup completed');
// Production-specific warnings
log.prod('Rate limit threshold reached');
log.prod('Database connection pool at 80%');
One-Time Logging
log.once(key, message)
Log a message only once, even if called multiple times:
function processItem(item) {
// This warning will only appear once, no matter how many items
log.once('deprecated-field', 'Warning: "oldField" is deprecated, use "newField"');
return process(item);
}
// Call 1000 times
items.forEach(processItem);
// Warning appears only once!
One-Time Logging
⚠⚠ Warning: "oldField" is deprecated, use "newField"
(Logged once, even though called 1000 times)
Use Cases
// Deprecation warnings
function oldMethod() {
log.once('oldMethod-deprecated', 'Warning: oldMethod() is deprecated. Use newMethod() instead.');
return newMethod();
}
// One-time initialization messages
function initialize() {
log.once('init', 'Initializing application...');
// ... initialization code
}
// Feature usage tracking
function experimentalFeature() {
log.once('experimental-used', 'Note: You are using an experimental feature');
// ... feature code
}
🎮 Try One-Time Logging
Conditional Logging
log.if(condition, message)
Log only when a condition is true:
log.if(process.env.VERBOSE, 'Verbose logging enabled');
log.if(user.isAdmin, `Admin ${user.name} accessed sensitive data`);
log.if(response.slow, `Slow response: ${response.time}ms`);
Conditional Logging
ℹℹ Verbose logging enabled
ℹℹ Admin John accessed sensitive data
⚠⚠ Slow response: 2345ms
Use Cases
// Feature flags
log.if(features.newDashboard, 'New dashboard feature enabled');
// Conditional debugging
log.if(DEBUG_SQL, `SQL: ${query}`);
log.if(DEBUG_HTTP, `Request: ${method} ${url}`);
// Threshold alerts
log.if(memory > threshold, `Memory warning: ${memory}MB`);
log.if(responseTime > 1000, `Slow request: ${responseTime}ms`);
CI/CD Detection
Automatic CI Detection
Logluxe detects common CI environments:
import { env } from 'logluxe';
if (env.isCI) {
// Running in CI - adjust behavior
log.info('Running in CI environment');
}
Detected CI environments:
- GitHub Actions
- GitLab CI
- CircleCI
- Travis CI
- Jenkins
- Azure Pipelines
- Bitbucket Pipelines
- And more...
CI-Aware Logging
// Disable colors in CI for cleaner logs
import { createLogger } from 'logluxe';
const log = createLogger({
colors: !env.isCI
});
// Use simpler output in CI
if (env.isCI) {
log.info('[CI] Running tests...');
} else {
log.gradient('Running tests...', ['cyan', 'blue']);
}
CI Environment
ℹℹ [CI] Running tests...
✔✔ [CI] All tests passed
(No colors, simple format for CI logs)
TTY Detection
Smart Terminal Detection
import { env } from 'logluxe';
if (env.isTTY) {
// Interactive terminal - use fancy output
log.rainbow('Welcome!');
} else {
// Piped/redirected - use plain output
console.log('Welcome!');
}
Progress Indicators
function downloadFile(url: string) {
if (env.isTTY) {
// Show animated progress bar
showProgressBar(percentage);
} else {
// Show simple percentage updates
if (percentage % 10 === 0) {
console.log(`Progress: ${percentage}%`);
}
}
}
Color Level Detection
Understanding Color Levels
import { env } from 'logluxe';
// env.colorLevel values:
// 0 - No color support
// 1 - Basic colors (16 colors)
// 2 - 256 colors
// 3 - True color (16 million colors)
if (env.colorLevel >= 3) {
// Use full RGB gradients
log.gradient('Beautiful gradient', ['#ff6b6b', '#feca57', '#48dbfb']);
} else if (env.colorLevel >= 1) {
// Use basic colors
log.color('Colored text', 'cyan');
} else {
// No colors - use plain text
console.log('Plain text');
}
Color Level Support
Color Level 3 (True Color):
Beautiful gradient with millions of colors
Color Level 1 (Basic):
Colored text with basic colors
Color Level 0 (None):
Plain text without colors
Practical Examples
Environment-Aware Logger Configuration
import { createLogger, env } from 'logluxe';
const log = createLogger({
// Disable colors in CI or non-TTY
colors: env.isTTY && !env.isCI,
// Show timestamps in production
timestamp: env.isProd,
// Show debug level only in development
level: env.isDev ? 'debug' : 'info',
// Add environment prefix in production
prefix: env.isProd ? `[${process.env.NODE_ENV}]` : undefined
});
Environment-Aware Config
Development:
●● Debug messages visible
ℹℹ Colors enabled
Production:
[2024-01-15T10:30:45Z] [production]
ℹℹ Info and above only
Smart Error Logging
function handleError(error: Error) {
// Always log the error message
log.error(error.message);
// Only show stack trace in development
log.dev(error.stack);
// In production, send to error tracking
log.prod('Error logged to monitoring service');
if (env.isProd) {
errorTracker.capture(error);
}
}
Smart Error Logging
In Development:
✖✖ Connection timeout
● at Database.connect (db.ts:45:11)
● at App.init (app.ts:23:5)
In Production:
✖✖ Connection timeout
ℹℹ Error logged to monitoring service
🎮 Try Environment-Aware Logging
Request Logging Middleware
function requestLogger(req, res, next) {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
const status = res.statusCode;
// Development: detailed colored logs
if (env.isDev) {
const method = log.paint(req.method).cyan().bold().toString();
const path = log.paint(req.path).white().toString();
const statusStr = status < 400
? log.paint(status).green().toString()
: log.paint(status).red().toString();
const time = log.paint(`${duration}ms`).gray().toString();
console.log(`${method} ${path} ${statusStr} ${time}`);
}
// Production: JSON logs for parsing
if (env.isProd) {
console.log(JSON.stringify({
method: req.method,
path: req.path,
status,
duration,
timestamp: new Date().toISOString()
}));
}
// Alert on slow requests
log.if(duration > 1000, `Slow request: ${req.method} ${req.path} - ${duration}ms`);
});
next();
}
Request Logging
Development:
GET /api/users 200 45ms
POST /api/users 201 89ms
GET /api/heavy 200 1523ms
⚠⚠ Slow request: GET /api/heavy - 1523ms
Production:
{"method":"GET","path":"/api/users","status":200,"duration":45,"timestamp":"..."}
Best Practices
1. Use log.dev() for Debug Info
// Good: Development-only debug info
log.dev(`Processing ${items.length} items`);
// Bad: Always logging debug info
console.log(`Processing ${items.length} items`);
2. Use log.once() for Warnings
// Good: Warning appears once
log.once('deprecated', 'This API is deprecated');
// Bad: Warning appears every call
console.warn('This API is deprecated');
3. Adapt to CI Environments
// Good: Adapt to environment
const useColors = env.isTTY && !env.isCI;
// Bad: Always use colors
log.rainbow('This breaks CI logs!');
4. Structured Logs in Production
// Good: Structured for log aggregation
if (env.isProd) {
console.log(JSON.stringify({ level: 'info', message, timestamp }));
}
// Bad: Unstructured production logs
console.log('Something happened');
Next: Error Formatting →