-
Notifications
You must be signed in to change notification settings - Fork 0
LOGGING GUIDE
github-actions[bot] edited this page Sep 2, 2026
·
46 revisions
Quick reference for using the production logging system.
import { createLogger } from '@/lib/logger'
const log = createLogger('YourModuleName')// Debug (development only, not shown in production)
log.debug('Detailed debug information', { variable: value })
// Info (general information)
log.info('User logged in successfully', { userId: 'abc123' })
// Warning (non-critical issues)
log.warn('API rate limit approaching', { remaining: 10 })
// Error (critical errors, sent to Sentry in production)
log.error('Database connection failed', error, { operation: 'fetchUsers' })// Performance tracking
const start = Date.now()
// ... your operation
log.perf('User query', Date.now() - start, { query: 'complex' })
// Security events (always logged and sent to Sentry)
log.security('Failed login attempt', {
ip: req.ip,
userId: attemptedUserId,
reason: 'invalid_password',
})
// Audit trails (compliance and tracking)
log.audit('User role changed', currentUserId, {
targetUser: targetUserId,
oldRole: 'member',
newRole: 'admin',
})| Level | Use When | Example |
|---|---|---|
debug |
Development debugging, verbose details | Variable values, function calls |
info |
Important state changes, user actions | User login, file upload complete |
warn |
Recoverable issues, deprecations | API rate limit warning, deprecated feature |
error |
Errors that need investigation | API failures, database errors |
perf |
Performance monitoring | Slow queries, long operations |
security |
Security-related events | Failed auth, suspicious activity |
audit |
Compliance and user actions | Permission changes, data access |
// Include context
log.error('Failed to fetch user', error, {
userId: 'abc123',
endpoint: '/api/users/abc123',
})
// Use scoped loggers
const log = createLogger('AuthService')
log.info('User authenticated', { userId })
// Log performance metrics
log.perf('Database query', duration, { table: 'users', rows: 1000 })
// Log security events
log.security('Suspicious login pattern', { userId, ip, attempts: 5 })// Don't use console.log in production code
console.log('Debug info') // β
// Don't log sensitive data
log.info('User logged in', { password: '...' }) // β
// Don't log without context
log.error('Error occurred') // β (no context)
// Don't over-log in tight loops
for (const item of items) {
log.debug('Processing item', item) // β (too verbose)
}Control logging behavior with environment variables:
# Production
NEXT_PUBLIC_LOG_LEVEL=warn
NEXT_PUBLIC_SENTRY_DSN=your-sentry-dsn
# Development
NEXT_PUBLIC_LOG_LEVEL=debug
NEXT_PUBLIC_SENTRY_DSN= # Optional in dev
# Staging
NEXT_PUBLIC_LOG_LEVEL=info
NEXT_PUBLIC_SENTRY_DSN=your-sentry-dsnAll error, warn, security, and audit logs are automatically sent to Sentry in production.
- β Errors (with stack traces)
- β Warnings (as Sentry messages)
- β Security events (tagged as security)
- β Audit logs (tagged as audit)
- β Debug logs (never sent)
- β Info logs (never sent)
The logger automatically includes:
- Error stack traces
- User context (if available)
- Environment information
- Custom context you provide
import { createLogger } from '@/lib/logger'
const log = createLogger('UserAPI')
export async function GET(req: Request) {
try {
const users = await fetchUsers()
return Response.json(users)
} catch (error) {
log.error('Failed to fetch users', error, {
endpoint: '/api/users',
method: 'GET',
})
return Response.json({ error: 'Internal error' }, { status: 500 })
}
}import { createLogger } from '@/lib/logger'
const log = createLogger('UserProfile')
export function UserProfile({ userId }: Props) {
useEffect(() => {
fetchUser(userId).catch((error) => {
log.error('Failed to load user profile', error, { userId })
})
}, [userId])
// ...
}import { createLogger } from '@/lib/logger'
const log = createLogger('Auth')
async function login(email: string, password: string) {
const user = await authenticateUser(email, password)
if (!user) {
log.security('Failed login attempt', {
email,
ip: getClientIP(),
timestamp: Date.now(),
})
throw new Error('Invalid credentials')
}
log.audit('User login', user.id, {
email: user.email,
loginMethod: 'password',
})
return user
}import { createLogger } from '@/lib/logger'
const log = createLogger('Database')
async function complexQuery(params: QueryParams) {
const start = Date.now()
try {
const results = await db.query(params)
const duration = Date.now() - start
log.perf('Complex query executed', duration, {
table: params.table,
rows: results.length,
filters: Object.keys(params.where).length,
})
return results
} catch (error) {
log.error('Query failed', error, { params })
throw error
}
}console.log('User logged in:', userId)
console.error('Error:', error)
console.warn('Deprecated feature used')import { createLogger } from '@/lib/logger'
const log = createLogger('YourModule')
log.info('User logged in', { userId })
log.error('Operation failed', error, { context: 'details' })
log.warn('Deprecated feature used', { feature: 'oldAPI' })In tests, you can mock the logger:
jest.mock('@/lib/logger', () => ({
createLogger: () => ({
debug: jest.fn(),
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
perf: jest.fn(),
security: jest.fn(),
audit: jest.fn(),
}),
}))- Check
NEXT_PUBLIC_SENTRY_DSNis set - Verify you're in production mode (
NODE_ENV=production) - Ensure error is being logged with
log.error()notconsole.error()
Set NEXT_PUBLIC_LOG_LEVEL=warn to reduce verbosity
Temporarily set NEXT_PUBLIC_LOG_LEVEL=info (not recommended long-term)
-
Logger Implementation:
src/lib/logger.ts -
Cleanup Report:
docs/CLEANUP-REPORT-v0.9.1.md -
Sentry Setup:
docs/Sentry-Setup.md -
Future Enhancements:
docs/future-enhancements.md
Last Updated: February 3, 2026
nself-chat v0.3.0 | GitHub | Issues | Discussions | Demo
Edit this page | MIT License | Β© 2026
(See π Security section below for 2FA, PIN Lock, and security audits.)
(Search lives in π Reference below.)
- π¬ Advanced Messaging
- π E2EE Setup
- π Search Setup
- π Call Management
- πΊ Live Streaming
- π₯οΈ Screen Sharing
- πΉ Video Calling
- ποΈ Voice Calling
- π± Mobile Optimization
- π§ͺ Testing
- π i18n
- π API Overview
- π Complete Reference
- π» API Examples
- π€ Bot API
- π Auth API
- π GraphQL Schema
- π Deployment Overview
- π³ Docker
- βΈοΈ Kubernetes
- β Helm Charts
- β Production Checklist
- π Production Validation
- π’ Multi-Tenant
- ποΈ Architecture
- π Diagrams
- ποΈ Database Schema
- π Project Structure
- π TypeScript Types
- π SPORT Reference
- π 2FA
- π¬ Messaging
- π Call Management
- π Call State Machine
- π E2EE
- πΊ Live Streaming
- π± Mobile Calls
- π PIN Lock
- π Polls
- π₯οΈ Screen Sharing
- π Search
- π Social Media
- ποΈ Voice Calling
- π Security Overview
- π‘οΈ Security Audit
- β‘ Performance
- π Best Practices
- π 2FA
- π PIN Lock
- π E2EE
- π‘οΈ E2EE Audit
v1.0.0 β’ 2026