Documentation

SDK reference

In-depth reference for @logship/logger: init, configuration, instance methods, types, transports, and error handling.

Install

npm install @logship/logger

init(config)

Description: Creates a logger instance. Events are buffered in memory and flushed to the ingestion API (or custom transports) in batches.

Parameters: config: LoggerConfig (see table below). apiKey is required when using the default HTTP transport.

Returns: LoggerInstance with methods debug, info, warn, error, and flush.

Errors: If apiKey is missing and no custom transports are provided, init() throws. If the endpoint is unreachable, sends are best-effort; failed events may be dropped after the transport attempts delivery.

LoggerConfig

All options passed to init():

OptionTypeDefaultDescription
apiKeystringRequired for default HTTP transport. From dashboard.
endpointstringbuilt-in Logship URLCustom ingestion API base URL (yours or ours). Override with this or LOGGER_API_URL for self-hosted or local.
minLevelLogLevel'debug'Events below this level are dropped.
minLevelByEnvRecord<string, LogLevel>Override minLevel by environment name.
sampleRatenumber1Global sampling (0–1).
sampleRateByLevelPartial<Record<LogLevel, number>>Per-level sampling.
defaultMetadataRecord<string, unknown>Merged into every event.
envstringEnvironment name for minLevelByEnv.
batchSizenumber50Max events per batch.
flushIntervalMsnumber5000Auto-flush interval in ms; 0 = disabled.
transportsTransport[][httpTransport] when apiKey setCustom transports.

Instance methods

  • logger.debug(message, metadata?) – Enqueue event at level debug. Subject to minLevel and sampling.
  • logger.info(message, metadata?) – Same for info.
  • logger.warn(message, metadata?) – Same for warn.
  • logger.error(message, metadata?) – Same for error.
  • logger.flush() – Flush the buffer immediately. Returns Promise<void>. Call before process exit to drain the buffer.

Types

  • LogLevel: 'debug' | 'info' | 'warn' | 'error'
  • LogEvent: id, level, message, metadata?, timestamp (ISO 8601), env?, source?
  • Transport: { name: string; send(events: LogEvent[]): Promise<void> }
  • LoggerInstance: Interface with debug, info, warn, error, flush

Transports

When apiKey is set, batches are sent via HTTP to endpoint/v1/logs with Authorization: Bearer <apiKey>. You can pass custom transports (e.g. noopTransport to drop events, or createHttpTransport(options) for a custom HTTP transport). Implement the Transport interface and pass an array to init(). Failures in one transport do not block others (best-effort).

Error handling

Missing apiKey: init() throws if apiKey is missing and no custom transports are provided.

Network/API errors on send: Transports send in batches; failed events may be dropped after the transport attempts delivery. For critical logs, use a fallback (e.g. console or file) or handle errors in your app.

What if the API is down? The SDK buffers and flushes on an interval; failed sends are best-effort. Call logger.flush() before process exit to drain the buffer. For critical logs, consider a custom transport (e.g. write to file).

How do I debug missing logs? Check minLevel, sampleRate, and env; ensure dashboard project and environment match; verify API key (Live vs Sandbox) and network/API status.

Reference: test-backend (every example)

The examples/test-backend app in the repo is a minimal Node server that uses @logship/logger. Below are every relevant snippet from src/index.ts so you can copy exactly what you need.

1. Init and config

examples/test-backend – init
const logger = init({
  apiKey: API_KEY,
  endpoint: API_URL,
  minLevel: 'debug',
  defaultMetadata: { service: 'logship-ingestion-test', version: '0.1.0' },
});

logger.info('Logship ingestion test server starting', { port: PORT, apiUrl: API_URL });

2. /ping – simple request log

examples/test-backend – /ping
if (url === '/ping' || url === '/') {
  logger.info('Request received', { path: url, method });
  return { status: 200, body: 'OK. Check dashboard Logs for this event.\n' };
}

3. /log-sample – all levels + flush

examples/test-backend – /log-sample
if (url === '/log-sample') {
  logger.debug('Debug sample');
  logger.info('Info sample', { foo: 'bar' });
  logger.warn('Warn sample');
  logger.error('Error sample', { code: 500 });
  await logger.flush();
  return { status: 200, body: 'Logged 4 events. Flushed. Check dashboard.\n' };
}

4. /flush – flush buffer only

examples/test-backend – /flush
if (url === '/flush') {
  await logger.flush();
  return { status: 200, body: 'Buffer flushed.\n' };
}

5. Server setup (createServer + listen)

examples/test-backend – main()
const server = http.createServer(async (req, res) => {
  const url = req.url ?? '/';
  const method = req.method ?? 'GET';
  const { status, body } = await handleRequest(url, method);
  res.writeHead(status, { 'Content-Type': 'text/plain' });
  res.end(body);
});

server.listen(PORT, () => {
  console.log(`Logship ingestion test: http://localhost:${PORT}`);
  console.log('  /ping      – send one log, respond OK');
  console.log('  /log-sample – send debug/info/warn/error, flush');
  console.log('  /flush     – flush buffer');
});

6. Graceful shutdown (flush before exit)

examples/test-backend – shutdown
const shutdown = (): void => {
logger.info('Shutting down');
logger.flush().then(() => {
server.close();
process.exit(0);
});
};
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);

Use shutdown so that on Ctrl+C or SIGTERM the buffer is flushed before the process exits and no logs are lost.

More examples

Minimal

import { init } from '@logship/logger';

const logger = init({
  apiKey: process.env.LOGGER_API_KEY!,
  minLevel: 'info',
  defaultMetadata: { service: 'api' },
});

logger.info('Server started');
logger.error('Payment failed', { orderId: 'ord_123' });

Flush on exit (Node app)

const logger = init({ apiKey: process.env.LOGGER_API_KEY! });

process.on('beforeExit', async () => {
  await logger.flush();
});

Express middleware (optional)

const logger = init({
  apiKey: process.env.LOGGER_API_KEY!,
  defaultMetadata: { service: 'api' },
});

app.use((req, res, next) => {
  const start = Date.now();
  res.on('finish', () => {
    const level = res.statusCode >= 500 ? 'error' : res.statusCode >= 400 ? 'warn' : 'info';
    logger[level]('Request', {
      method: req.method,
      path: req.path,
      status: res.statusCode,
      durationMs: Date.now() - start,
    });
  });
  next();
});

For the full runnable app, clone the repo and run examples/test-backend (see Getting started).