Advanced Usage
Learn about advanced features of the VedaTrace SDK for JavaScript and TypeScript.
Custom Transports
The VedaTrace SDK comes with a console transport and an HTTP transport. You can also create your own custom transports.
import { VedaTraceHttpTransport, VedaTraceConsoleTransport } from 'vedatrace/transports'
const logger = vedatrace({
transports: [
new VedaTraceHttpTransport({ apiKey: '...' }),
new VedaTraceConsoleTransport({ format: 'pretty' })
]
})Manual Flush
In some cases, you may want to manually flush the logs to ensure they are sent before the process exits.
// Flush all pending logs
await logger.flush()
// Use in request handlers
app.post('/webhook', async (req, res) => {
logger.info('Webhook received')
await logger.flush() // Ensure sent before responding
res.json({ ok: true })
})Serverless Flush (Cloudflare Workers)
In serverless environments like Cloudflare Workers, the runtime terminates the worker shortly after returning a Response. Any in-flight HTTP requests — including log delivery — are cancelled.
VedaTrace provides three ways to ensure logs are delivered before termination:
Option 1: waitUntil config (recommended)
Pass the waitUntil function from cloudflare:workers in your config:
import { waitUntil } from 'cloudflare:workers'
const logger = vedatrace({
apiKey: '...',
service: 'my-worker',
waitUntil, // Extends worker lifetime during log flushing
})Logs flush automatically after each logger.info(), logger.error(), etc. — no manual flush() call needed.
Option 2: Execution context via .withContext(ctx)
logger.withContext(ctx)VedaTrace stores the ctx object and calls ctx.waitUntil(flushPromise) internally.
Option 3: Manual ctx.waitUntil(logger.flush())
ctx.waitUntil(logger.flush())Graceful Shutdown
The SDK uses a background timer to flush logs. For short-lived scripts or when you need to explicitly clean up, you can stop the timer.
const logger = vedatrace({ apiKey: '...' })
logger.info('Processing...')
// For short-lived scripts
await logger.flush()
logger.stop() // Stop background timerThe SDK timer uses unref() so the process will exit automatically when there's nothing else to do. Call stop() if you need explicit cleanup.
Error Handling
The VedaTrace SDK will never throw an error. Instead, it will emit an error event that you can listen for.
const logger = vedatrace({
apiKey: '...',
onError: (err) => {
// Handle transport errors
console.error('VedaTrace error:', err)
}
})Edge Runtime Support
VedaTrace automatically detects edge runtimes (Cloudflare Workers, Deno, Bun) and adjusts its behavior accordingly. See the Edge Runtimes guide for detailed information.
