Quick Start with ByteHide Logger
Prerequisites
Before you begin, make sure you have:
- A ByteHide account and project token
- Node.js 16+ for server-side applications or a modern browser for client-side applications
Quick Start Guide
- Install ByteHide Logger in your project
- Configure the logger with your settings
- Set your project token for cloud logging
- Start logging with simple API calls
- View logs in the ByteHide web panel
- Explore advanced features as needed
Step 1: Installation
Add the ByteHide Logger package to your project:
npm install @bytehide/logger
Step 2: Basic Setup
Initialize the logger in your application startup:
Node.js Application
import { Log } from '@bytehide/logger';
// Step 1: Configure the logger
Log.configure({
minimumLevel: 'debug',
consoleEnabled: true,
maskSensitiveData: ['password', 'token'],
duplicateSuppressionWindowMs: 1000,
// File logging for Node.js
persist: true,
filePath: 'logs/app.log',
rollingInterval: 'day'
});
// Step 2: Set your project token
Log.setProjectToken('your-project-token');
// Step 3: Add global metadata
Log.addMetaContext('AppVersion', '1.2.3');
Log.addMetaContext('Environment', 'Development');
// Your application code
runApplication();
function runApplication() {
Log.info('Application started successfully!');
try {
// Simulate some work
processOrder('ORD-001', 'CUST-123');
} catch (error) {
Log.critical('Application error occurred', { tags: ['critical'] }, error);
} finally {
Log.info('Application finished');
}
}
function processOrder(orderId, customerId) {
const correlationId = generateCorrelationId();
Log.info('Processing order', {
correlationId,
tags: ['orders', 'processing'],
metadata: { orderId, customerId }
});
// Simulate processing time
setTimeout(() => {
Log.info('Order processed successfully', {
correlationId,
tags: ['orders', 'success'],
metadata: { orderId, processingTime: '1.2s' }
});
}, 1000);
}
function generateCorrelationId() {
return Math.random().toString(36).substring(2, 15);
}
Browser Application
<!DOCTYPE html>
<html>
<head>
<title>ByteHide Logger Demo</title>
</head>
<body>
<h1>ByteHide Logger Quick Start</h1>
<button onclick="testLogging()">Test Logging</button>
<script type="module">
import { Log } from '@bytehide/logger';
// Configure for browser
Log.configure({
minimumLevel: 'info',
consoleEnabled: true,
maskSensitiveData: ['password', 'token', 'sessionId']
});
Log.setProjectToken('your-project-token');
Log.addMetaContext('AppVersion', '1.0.0');
Log.addMetaContext('Platform', 'Browser');
Log.info('Web application loaded');
window.testLogging = function() {
Log.info('Button clicked', {
tags: ['ui', 'interaction'],
metadata: { buttonId: 'test-button', timestamp: new Date().toISOString() }
});
};
</script>
</body>
</html>
Step 3: Basic Logging
Use the simple logging API throughout your application:
import { Log } from '@bytehide/logger';
// Simple logging
Log.info('User logged in');
Log.warn('API rate limit approaching');
Log.error('Database connection failed');
// Logging with context
Log.info('User action performed', {
tags: ['user', 'action'],
metadata: { userId: '12345', action: 'profile_update' }
});
// Logging with correlation ID
const correlationId = 'req-abc123';
Log.debug('Processing request', {
correlationId,
tags: ['api', 'request'],
metadata: { endpoint: '/api/users' }
});
// Error logging with exception
try {
// Some operation that might fail
throw new Error('Something went wrong');
} catch (error) {
Log.error('Operation failed', {
tags: ['error', 'operation'],
metadata: { operation: 'user_update' }
}, error);
}
Step 4: Advanced Features
User Identification
// Identify user for all subsequent logs
Log.identify('john.doe', 'john@example.com', 'user-token-123');
// All logs after this will include user information
Log.info('User performed action');
Log.warn('User attempted unauthorized action');
Correlation IDs for Request Tracking
// Generate correlation ID for request tracking
const correlationId = crypto.randomUUID();
Log.info('Request started', {
correlationId,
tags: ['api', 'request'],
metadata: { method: 'POST', endpoint: '/api/orders' }
});
Log.info('Validating request data', {
correlationId,
tags: ['validation']
});
Log.info('Request completed', {
correlationId,
tags: ['api', 'response'],
metadata: { statusCode: 200, duration: '150ms' }
});
Data Masking in Action
// Sensitive data will be automatically masked
Log.info('User login attempt', {
metadata: {
username: 'john.doe',
password: 'secret123', // Will be masked as ***
token: 'abc123xyz', // Will be masked as ***
email: 'john@example.com' // Will not be masked
}
});
Duplicate Suppression
// These duplicate messages will be suppressed
for (let i = 0; i < 10; i++) {
Log.warn('Database connection slow'); // Only first occurrence logged
}
// Different messages are not suppressed
Log.warn('API rate limit reached');
Log.warn('Memory usage high');
Step 5: View Your Logs
After your application runs, you can view logs in multiple places:
Console Output (Development)
[2024-01-15 10:30:15] [INFO] Application started successfully! {AppVersion: "1.2.3", Environment: "Development"}
[2024-01-15 10:30:15] [INFO] Processing order {correlationId: "abc123", orderId: "ORD-001", customerId: "CUST-123"}
[2024-01-15 10:30:16] [INFO] Order processed successfully {correlationId: "abc123", orderId: "ORD-001", processingTime: "1.2s"}
Log Files (Node.js)
Check your configured log file path (e.g., logs/app.log
):
2024-01-15 10:30:15.123 [INFO] Application started successfully! AppVersion=1.2.3 Environment=Development
2024-01-15 10:30:15.456 [INFO] Processing order correlationId=abc123 orderId=ORD-001 customerId=CUST-123
2024-01-15 10:30:16.789 [INFO] Order processed successfully correlationId=abc123 orderId=ORD-001 processingTime=1.2s
ByteHide Web Panel
- Log in to ByteHide Cloud
- Select your Logs project
- View real-time logs, search, filter, and analyze
Dynamic Logging Control
// Disable logging temporarily
Log.disable();
Log.info('This will not be logged');
// Re-enable logging
Log.enable();
Log.info('Logging is active again');
// Reset all configuration
Log.reset();
// Reconfigure
Log.configure({
minimumLevel: 'warn',
consoleEnabled: true
});
Best Practices
JavaScript Logging Best Practices
- Configure early: Set up logging at application startup
- Use correlation IDs: Track requests across async operations
- Tag consistently: Establish tagging conventions for your team
- Mask sensitive data: Always include PII and credentials in masking
- Environment-specific config: Use different settings for dev/prod
- File logging: Only use in Node.js, not in browsers
Next Steps
Now that you have basic logging working: