@devms/applog-client
v0.3.1
Published
Application log client for the Monitoring platform. Buffered, batched delivery with retry. Works standalone or as a NestJS module. Pair with @devms/livetail for WebSocket log streaming.
Maintainers
Readme
@devms/applog-client
Application log client for the Monitoring platform. Send structured business logs (auth, payments, orders, notifications) with buffered, batched delivery, retry, and duration tracking.
Works as a standalone Node.js client or as a NestJS module with automatic HTTP request logging, non-HTTP exception capture, process-level crash handlers, and optional Telegram error alerts.
Looking for Live Tail (real-time WebSocket log streaming and raw console capture)? It now lives in its own package:
@devms/livetail.
Install
pnpm add @devms/applog-clientQuick Start
Standalone (Express, Fastify, any Node.js app)
import { createAppLogClient } from '@devms/applog-client';
const appLog = createAppLogClient({
apiUrl: 'https://monitor.example.com',
clientId: process.env.MONITOR_CLIENT_ID!,
clientSecret: process.env.MONITOR_CLIENT_SECRET!,
});
// Simple logging
appLog.info('auth', 'user.login', {
message: 'User logged in',
userId: 'user-123',
metadata: { method: 'oauth', provider: 'google' },
tags: ['web'],
});
appLog.error('payment', 'charge.failed', {
message: 'Card declined',
userId: 'user-123',
metadata: { reason: 'insufficient_funds', amount: 99.99 },
});
// Duration tracking
const end = appLog.startTimer('payment', 'payment.charge');
await processPayment(order);
end({ userId: order.userId, metadata: { orderId: order.id } });
// Shutdown (flushes remaining buffer)
process.on('SIGTERM', async () => {
await appLog.shutdown();
process.exit(0);
});NestJS Module
// app.module.ts
import {
AppLogModule,
AppLogInterceptor,
AppLogExceptionFilter,
} from '@devms/applog-client';
import { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core';
@Module({
imports: [
AppLogModule.register({
apiUrl: process.env.MONITOR_API_URL,
clientId: process.env.APPLOG_CLIENT_ID,
clientSecret: process.env.APPLOG_CLIENT_SECRET,
// HTTP interceptor options
excludePaths: ['/api/health', '/api/health/system'],
logBodies: true,
logHeaders: true,
maxBodySize: 10240,
// Crash capture (defaults shown)
captureCrashes: true,
}),
],
providers: [
// HTTP request/response logger
{ provide: APP_INTERCEPTOR, useClass: AppLogInterceptor },
// Catch-all filter — logs non-HTTP errors (ws / rpc / runtime)
{ provide: APP_FILTER, useClass: AppLogExceptionFilter },
],
})
export class AppModule {}Make sure
app.enableShutdownHooks()is called inmain.tsso buffered logs are flushed onSIGTERM/ graceful shutdown.
With ConfigService (async)
AppLogModule.registerAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
apiUrl: config.get('MONITOR_API_URL'),
clientId: config.get('APPLOG_CLIENT_ID'),
clientSecret: config.get('APPLOG_CLIENT_SECRET'),
defaultCategory: 'my-service',
defaultTags: ['production'],
excludePaths: ['/api/health'],
logBodies: true,
logHeaders: true,
}),
});Inject and use in services
import { AppLogNestService } from '@devms/applog-client';
@Injectable()
export class PaymentService {
constructor(private readonly appLog: AppLogNestService) {}
async charge(order: Order) {
const end = this.appLog.startTimer('payment', 'payment.charge', {
userId: order.userId,
});
try {
const result = await this.stripe.charge(order);
end({
message: `Charged $${order.total}`,
metadata: { orderId: order.id },
});
return result;
} catch (err) {
this.appLog.error('payment', 'payment.charge.failed', {
message: err.message,
userId: order.userId,
metadata: { orderId: order.id, error: err.message },
});
throw err;
}
}
}HTTP Interceptor
The AppLogInterceptor automatically logs every HTTP request with full context:
- Method, path, status code, duration
- Request bodies (with configurable size limit)
- Response payloads — opt-in per path via
logResponseBodyPaths(not saved by default) - Request headers (content-type, user-agent, origin)
- Client IP and user-agent
- Query parameters
- Error messages and stack traces (for failed requests)
- User ID extracted from
request.user.idorrequest.user.sub - Controller and handler names as context
Sensitive Field Redaction
Request/response bodies are automatically sanitized. The following fields are redacted:
password, token, accessToken, refreshToken, authorization, secret, creditCard, cardNumber, cvv, ssn
Path Exclusion
Use excludePaths to skip logging for health checks or other noisy endpoints:
AppLogModule.register({
// ...credentials
excludePaths: ['/api/health', '/metrics', '/api/docs'],
});Exclude Body Logging
Use excludeLogBodies to skip body capture for specific paths while still logging the request itself (useful for auth endpoints or file uploads):
AppLogModule.register({
// ...credentials
logBodies: true,
excludeLogBodies: ['/api/auth/login', '/api/upload', '/api/users/register'],
});Response Payload Capture (opt-in)
Response payloads are not saved by default. To save them for specific
API paths, list the paths in logResponseBodyPaths (prefix match):
AppLogModule.register({
// ...credentials
logResponseBodyPaths: ['/api/orders', '/api/payments'],
});Only requests whose path starts with one of these prefixes will have
responseBody stored in the log metadata. Paths in excludeLogBodies
and the global logBodies: false switch still take precedence.
Disabled Mode
When disabled: true, the interceptor still logs to the NestJS console (method, path, status, duration) but does not send logs to the monitoring API.
Capturing Errors Outside HTTP Requests
HTTP errors are covered by AppLogInterceptor. Everything else — queue consumers, scheduled jobs, event emitters, WebSocket gateways, microservice handlers, and truly uncaught errors — is covered by two additional layers.
1. AppLogExceptionFilter — non-HTTP Nest errors
A catch-all exception filter that logs errors from WebSocket (ws) / RPC / microservice contexts. HTTP errors are deliberately skipped to avoid double-logging with the interceptor. It extends BaseExceptionFilter, so the normal Nest error response still runs (HTTP clients get their JSON error, WS clients get an error event, etc.).
Register once globally:
import { APP_FILTER } from '@nestjs/core';
import { AppLogExceptionFilter } from '@devms/applog-client';
providers: [{ provide: APP_FILTER, useClass: AppLogExceptionFilter }];Logs appear as category=runtime, action=<transport>.exception.
2. Process-level crash handlers — uncaughtException / unhandledRejection
Installed automatically when AppLogNestService boots (opt out with captureCrashes: false). Fires for:
unhandledRejection→ logserror/category=process, action=unhandledRejectionuncaughtException→ logsfatal/category=process, action=uncaughtException, then flushes the buffer (bounded byflushTimeoutMs, default 2 s) and exits with code 1warning→ optional, logswarn/category=process, action=warning
These are the safety net for errors that never reach Nest — e.g. a BullMQ worker callback that throws, an EventEmitter handler rejection, a native module crash.
Tune via config:
AppLogModule.register({
// ...credentials
captureCrashes: true, // default
crashHandlerOptions: {
unhandledRejection: true, // default
uncaughtException: true, // default
processWarnings: false, // default
exitOnUncaught: true, // default — exit(1) after flush
flushTimeoutMs: 2000, // default — max ms to wait for flush on crash
},
});Standalone (non-Nest) crash handlers
For Express/Fastify/plain Node apps, call installCrashHandlers yourself:
import { createAppLogClient, installCrashHandlers } from '@devms/applog-client';
const appLog = createAppLogClient({
/* ... */
});
const dispose = installCrashHandlers(appLog, { exitOnUncaught: true });
// ...later, if you need to detach (e.g. in tests):
dispose();Queue / event-emitter errors (explicit wiring)
Third-party libraries like BullMQ don't throw into Nest's filter chain. Wire their error events directly:
// BullMQ worker
worker.on('failed', (job, err) => {
this.appLog.error('queue', 'job.failed', {
message: err.message,
metadata: { jobId: job?.id, jobName: job?.name, errorStack: err.stack },
});
});
worker.on('error', (err) => {
this.appLog.error('queue', 'worker.error', {
message: err.message,
metadata: { errorStack: err.stack },
});
});
// EventEmitter2 / @OnEvent
eventEmitter.on('error', (err) => {
this.appLog.error('event', 'handler.error', {
message: err.message,
metadata: { errorStack: err.stack },
});
});Any async handler that leaks an unhandled rejection will still be caught by the process-level handler as a last resort.
Telegram Error Alerts
Send formatted error alerts to a Telegram group whenever an exception is caught by AppLogInterceptor (HTTP) or AppLogExceptionFilter (non-HTTP). Alerts are fire-and-forget and never block the request path.
Required config
botToken— from @BotFathergroupId— the Telegram chat / group ID to post alerts in
When either is missing, Telegram alerts are a silent no-op.
Install the peer dependency
telegraf is loaded lazily, so you only need it in apps that enable alerts:
pnpm add telegraf
pnpm add ua-parser-js # optional — enriches alerts with browser / OS / deviceEnable
AppLogModule.registerAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
apiUrl: config.get('MONITOR_API_URL'),
clientId: config.get('APPLOG_CLIENT_ID'),
clientSecret: config.get('APPLOG_CLIENT_SECRET'),
telegram: {
botToken: config.get('TELEGRAM_BOT_TOKEN'),
groupId: config.get('TELEGRAM_BOT_ERROR_GROUP'),
appName: 'My App',
environment: config.get('NODE_ENV'),
enabledEnvironments: ['uat', 'production', 'local'],
skipStatusCodes: [401],
excludePaths: ['/api/health', '/api/jobs/poll'],
dedupTtlMs: 2 * 60 * 1000,
redactBodyPaths: ['/auth/login'],
},
}),
});Alert format
Alerts mirror the layout used by our legacy TelegramExceptionsFilter — severity emoji, error summary, request details, user info, client (browser/OS/device), request body, error details, and stack trace. Status-based severity emojis are used, and production alerts use a more muted styling.
Behaviour
- Deduped — identical payloads within
dedupTtlMs(default 2 min) are dropped. - Environment-gated — when
enabledEnvironmentsis set, alerts are skipped if the current env isn't in the list. - Status-code skipping —
skipStatusCodes(default[401]) silences noisy auth errors. - Path exclusion — HTTP errors on paths listed in
excludePaths(prefix match) never alert; they are still logged to the monitoring API. - Body redaction — request body is omitted for paths listed in
redactBodyPaths(default['/auth/login']). - Self-healing — if a
sendMessagecall fails, the service tries once more to send the error itself, then gives up and logs.
Manual sends
Inject TelegramAlertService anywhere to send an ad-hoc alert:
import { TelegramAlertService } from '@devms/applog-client';
@Injectable()
export class PaymentsService {
constructor(private readonly alert: TelegramAlertService) {}
async charge(order: Order) {
try {
// ...
} catch (err) {
await this.alert.sendException(err); // full formatted alert
// or: await this.alert.send('<b>Raw HTML message</b>');
throw err;
}
}
}Send custom messages
TelegramAlertService is exported by AppLogModule (which is global), so any
app that installs @devms/applog-client can inject it and send its own
messages through the configured bot — not just error alerts:
import { TelegramAlertService } from '@devms/applog-client';
@Injectable()
export class DeployService {
constructor(private readonly telegram: TelegramAlertService) {}
async notify() {
// HTML message to the configured group/topic
await this.telegram.sendMessage('<b>Deploy finished</b> ✅');
// Plain text (auto-escaped, safe for user input)
await this.telegram.sendMessage('1 < 2 & 3 > 2', { escape: true });
// Different chat / topic, or another parse mode
await this.telegram.sendMessage('report ready', {
chatId: '-1001234567890',
topicId: 7,
parseMode: 'MarkdownV2',
});
}
}sendMessage(text, options?) returns { ok, error? } and never throws.
When Telegram isn't configured it resolves { ok: false, error: 'telegram_not_configured' },
so calls are safe in every environment. Messages longer than Telegram's
limit are truncated automatically.
| Option | Type | Default | Description |
| ----------- | ------- | ------------------ | ----------------------------------------- |
| chatId | string | telegram.groupId | Destination chat |
| topicId | number | telegram.topicId | Topic / thread within the chat |
| parseMode | string | 'HTML' | 'HTML', 'Markdown', or 'MarkdownV2' |
| escape | boolean | false | Escape HTML entities (plain-text sending) |
Telegram config reference
| Option | Type | Default | Description |
| --------------------- | -------- | ---------------------- | --------------------------------------------- |
| botToken | string | — | Bot token from @BotFather (required) |
| groupId | string | — | Chat / group ID to receive alerts (required) |
| appName | string | 'Application' | Shown in the alert header |
| environment | string | process.env.NODE_ENV | Environment label |
| enabledEnvironments | string[] | — (all enabled) | Only send when environment is in this list |
| skipStatusCodes | number[] | [401] | HTTP status codes to skip |
| excludePaths | string[] | [] | Request paths to skip alerting (prefix match) |
| dedupTtlMs | number | 120000 | Dedup window for identical errors |
| redactBodyPaths | string[] | ['/auth/login'] | Paths whose body is omitted from the alert |
Live Tail (real-time log streaming)
Live Tail — the WebSocket gateway that streams structured logs and raw
stdout/stderr to the Monitoring dashboard — moved to its own package:
@devms/livetail. Register it alongside this module:
import { AppLogModule } from '@devms/applog-client';
import { LiveTailModule } from '@devms/livetail';
@Module({
imports: [
AppLogModule.register({
/* ...credentials */
}),
LiveTailModule.register({
captureConsole: { token: process.env.LIVETAIL_CONSOLE_TOKEN },
}),
],
})
export class AppModule {}See the @devms/livetail README for configuration, the WebSocket protocol, and console capture.
API
Log Methods
appLog.debug(category, action, options?)
appLog.info(category, action, options?)
appLog.warn(category, action, options?)
appLog.error(category, action, options?)
appLog.fatal(category, action, options?)Options
| Field | Type | Description |
| ------------ | -------- | ---------------------------------- |
| message | string | Human-readable log message |
| metadata | object | Any structured data (JSON) |
| userId | string | User identifier |
| duration | number | Duration in milliseconds |
| tags | string[] | Searchable tags |
| method | string | HTTP method (GET, POST, etc.) |
| path | string | Request path / URL |
| statusCode | number | HTTP status code |
| context | string | Log context (e.g. controller name) |
| pid | number | Process ID |
Timer
const end = appLog.startTimer(category, action, options?);
// ... do work ...
end(extraOptions?); // logs with duration automaticallyLow-level
appLog.push(payload); // Push a raw AppLogPayload
appLog.flush(); // Force flush buffer
appLog.shutdown(); // Stop timer + flush
appLog.bufferSize; // Current buffer lengthConfiguration
| Option | Type | Default | Description |
| ---------------------- | -------- | ------- | --------------------------------------------------------------------------- |
| apiUrl | string | — | Monitoring API base URL (required) |
| clientId | string | — | Environment client ID (required) |
| clientSecret | string | — | Environment client secret (required) |
| batchSize | number | 50 | Auto-flush when buffer reaches this size |
| flushInterval | number | 5000 | Flush interval in ms |
| maxBufferSize | number | 1000 | Max buffer size (oldest logs dropped when full) |
| timeout | number | 10000 | HTTP request timeout in ms |
| maxRetries | number | 3 | Retry attempts with exponential backoff |
| defaultCategory | string | — | Default category when none specified |
| defaultTags | string[] | [] | Tags added to every log |
| disabled | boolean | false | Disable API logging (console logging still works) |
| logger | object | console | Custom logger { debug, warn, error } |
| excludePaths | string[] | [] | Paths to skip in the HTTP interceptor |
| logBodies | boolean | true | Capture request bodies |
| logHeaders | boolean | true | Capture request headers |
| maxBodySize | number | 10240 | Max body size to capture (characters) |
| excludeLogBodies | string[] | [] | Paths to skip body capture (request still logged) |
| logResponseBodyPaths | string[] | [] | Paths allowed to save response payloads (not saved by default) |
| captureCrashes | boolean | true | Install process-level crash handlers (NestJS) |
| crashHandlerOptions | object | — | Options forwarded to installCrashHandlers |
| telegram | object | — | Telegram alert config — see Telegram Error Alerts |
crashHandlerOptions
| Option | Type | Default | Description |
| -------------------- | ------- | ------- | ---------------------------------------------- |
| unhandledRejection | boolean | true | Log unhandled promise rejections |
| uncaughtException | boolean | true | Log uncaught exceptions |
| processWarnings | boolean | false | Log Node process warnings |
| exitOnUncaught | boolean | true | Call process.exit(1) after flushing on crash |
| flushTimeoutMs | number | 2000 | Max ms to wait for the flush before exiting |
Category & Action Conventions
| Category | Example Actions |
| -------------- | ------------------------------------------------------------- |
| http | Controller.handler (auto-logged by interceptor) |
| auth | user.login, user.logout, user.register, token.refresh |
| payment | payment.charge, payment.refund, subscription.create |
| order | order.create, order.update, order.cancel, order.ship |
| notification | email.send, sms.send, push.send |
| file | file.upload, file.download, file.delete |
| admin | user.ban, config.update, data.export |
| integration | webhook.receive, api.call, sync.complete |
How It Works
- Logs are buffered in memory
- Buffer is flushed when it reaches
batchSizeor everyflushIntervalms - Logs are sent as a batch POST to
/api/app-logs/ingestwith Basic Auth - On failure, retries with exponential backoff (200ms, 400ms, 800ms)
- Failed batches are re-added to the buffer if space is available
- Buffer has a hard cap (
maxBufferSize) — oldest logs are dropped when full - On shutdown, remaining buffer is flushed
- On
uncaughtException, the crash log is pushed and the buffer is flushed with a bounded timeout beforeprocess.exit(1)
License
MIT
