@oneminutelogs/express
v1.0.2
Published
Express.js SDK for OneMinuteLogs
Downloads
14
Maintainers
Readme
@oneminutelogs/express
The official Express.js/Node.js SDK for OneMinuteLogs.
This package provides a lightweight, type-safe way to send structured logs to your OneMinuteLogs dashboard. It includes Express.js middleware for automatic request logging and a standalone logger for manual instrumentation.
Official Documentation: oneminutestack.com/docs/express
Features
- Express Middleware: Automatically log request duration, status codes, and user context.
- Type-Safe: Full TypeScript support with comprehensive type definitions.
- Structured Logging: Well-defined schemas for Errors, Warnings, Info, Audits, and Metrics.
- Security Context: Built-in support for tracking auth status, suspicious activities, and security tags.
- Node.js Optimized: Uses native
fetchandReadableStream(Node 18+ required). - Log Retrieval: Query historical logs programmatically.
Installation
npm install @oneminutelogs/express
# or
yarn add @oneminutelogs/express
# or
pnpm add @oneminutelogs/expressQuick Start
1. Register Middleware
Add the withOneMinuteLogs middleware to your Express app. This will automatically log every incoming request.
import express from "express";
import { withOneMinuteLogs } from "@oneminutelogs/express";
const app = express();
app.use(withOneMinuteLogs({
apiKey: process.env.ONE_MINUTE_LOGS_API_KEY!,
appName: "my-express-api",
environment: process.env.NODE_ENV || "development"
}));
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(3000);2. Manual Logging
Use the attached req.logger to send structured logs from your route handlers.
app.post("/login", async (req, res) => {
try {
const { username, password } = req.body;
// ... auth logic ...
// Log a security audit event
await req.logger.audit({
message: "User logged in successfully",
security: {
auth_status: "success",
user_id: username
},
track: {
ip: req.ip
}
});
res.json({ token: "..." });
} catch (error) {
// Log an error
await req.logger.error({
message: "Login failed",
importance: "high",
security: {
auth_status: "failed"
}
});
res.status(401).send("Unauthorized");
}
});3. Standalone Usage
You can also create a logger instance independently of Express (e.g., for background jobs or scripts).
import { createLogger } from "@oneminutelogs/express";
const logger = createLogger({
apiKey: process.env.OML_API_KEY!,
appName: "worker-process"
});
await logger.info({ message: "Job started" });Configuration
The withOneMinuteLogs middleware and createLogger function accept a configuration object:
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| apiKey | string | Yes | Your OneMinuteLogs API Key. |
| appName | string | No | Name of your application (defaults to "default"). |
| environment| string | No | Environment name. Defaults to process.env.NODE_ENV. |
Middleware Options
withOneMinuteLogs(config, options) accepts a second argument:
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| autoLogRequests | boolean | true | If true, automatically logs every request on response finish. |
Usage Guide
Basic Logging methods
// Information
await logger.info({ message: "User profile updated" });
// Warnings
await logger.warning({ message: "Rate limit approaching" });
// Errors
await logger.error({ message: "Payment processing failed" });
// Success
await logger.success({ message: "Email sent" });
// Debug
await logger.debug({ message: "Payload parsed", subsystem: "network" });Advanced Logging
Security Audits
Track security-related events like login attempts or permission changes.
await logger.audit({
message: "Failed login attempt",
security: {
auth_status: "failed",
suspicious: true,
tags: ["brute-force", "login"]
},
track: {
ip: "203.0.113.42",
user_agent: "Mozilla/5.0..."
}
});Performance Metrics
await logger.metric({
message: "API Request processed",
metrics: {
latency_ms: 145,
db_query_count: 3
},
subsystem: "network"
});Retrieving Logs
Query historical logs programmatically using getLogs or logger.get.
import { getLogs } from "@oneminutelogs/express";
const result = await getLogs(
{ apiKey: "..." },
{ type: "error", limit: 5 }
);
console.log(result);Real-time Stream
Subscribe to logs via Server-Sent Events (SSE).
import { getStream } from "@oneminutelogs/express";
const { body } = getStream({ apiKey: "..." }, { type: "info" });
if (body) {
// body is a ReadableStream<Uint8Array>
const reader = body.getReader();
// ... read stream ...
}Type Definitions
The package exports all necessary types for TypeScript users:
LoggerConfigLogPayloadLogTypeImportanceSubsystem
import type { LogPayload } from "@oneminutelogs/express";Support
If you have any questions or need assistance, please contact us at [email protected].
