npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

loggy-winston-transport

v0.1.0

Published

Winston transport for sending logs to Loggy backend

Readme

loggy-winston-transport

Winston transport для отправки логов в Loggy backend.

Установка

npm install loggy-winston-transport winston

Использование

Базовый пример

import winston from 'winston';
import { LoggyTransport } from 'loggy-winston-transport';

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.Console(),
    new LoggyTransport({
      url: 'http://localhost:3000',
      projectToken: 'your-project-token-uuid',
    }),
  ],
});

logger.info('Application started');
logger.error('Something went wrong', { error: 'Error details' });

С кастомной конфигурацией

import winston from 'winston';
import { LoggyTransport } from 'loggy-winston-transport';

const logger = winston.createLogger({
  level: 'debug',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.errors({ stack: true }),
    winston.format.json()
  ),
  transports: [
    new winston.transports.Console(),
    new LoggyTransport({
      url: process.env.LOGGY_URL || 'http://localhost:3000',
      projectToken: process.env.LOGGY_PROJECT_TOKEN!,
      endpoint: '/api/logs', // по умолчанию
      timeout: 10000, // 10 секунд
      maxRetries: 3, // количество попыток
      retryDelay: 1000, // задержка между попытками (мс)
      includeStackTrace: true, // включать stack trace в metadata
      
      // Кастомный маппинг уровней
      levelMapping: {
        error: 'error',
        warn: 'warn',
        info: 'info',
        http: 'info', // маппинг http на info
        debug: 'debug',
        verbose: 'verbose',
        silly: 'debug',
      },
      
      // Кастомная функция для извлечения тегов
      extractTags: (info) => {
        return info.tags || [];
      },
      
      // Кастомная функция для извлечения метаданных
      extractMetadata: (info) => {
        // Исключаем служебные поля Winston
        const { message, level, timestamp, tags, ...metadata } = info;
        return Object.keys(metadata).length > 0 ? metadata : undefined;
      },
    }),
  ],
});

// Использование с метаданными и тегами
logger.info('Payment processed', {
  tags: ['payment', 'success'],
  userId: 'user-123',
  amount: 1000,
  request: {
    id: 'req-123',
    method: 'POST',
    path: '/api/payment',
  },
});

logger.error('Payment failed', {
  tags: ['payment', 'error', 'critical'],
  error: {
    message: 'Insufficient funds',
    code: 'INSUFFICIENT_FUNDS',
  },
});

Использование в NestJS

// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as winston from 'winston';
import { LoggyTransport } from 'loggy-winston-transport';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    logger: winston.createLogger({
      level: process.env.LOG_LEVEL || 'info',
      format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.errors({ stack: true }),
        winston.format.json()
      ),
      transports: [
        new winston.transports.Console({
          format: winston.format.simple(),
        }),
        new LoggyTransport({
          url: process.env.LOGGY_URL || 'http://localhost:3000',
          projectToken: process.env.LOGGY_PROJECT_TOKEN!,
        }),
      ],
    }),
  });

  await app.listen(3000);
}
bootstrap();

Конфигурация

LoggyTransportOptions

| Опция | Тип | Обязательная | По умолчанию | Описание | |-------|-----|--------------|--------------|----------| | url | string | ✅ | - | URL Loggy backend (например, http://localhost:3000) | | projectToken | string | ✅ | - | Токен проекта для авторизации | | endpoint | string | ❌ | '/api/logs' | Путь к API endpoint | | timeout | number | ❌ | 5000 | Таймаут запроса в миллисекундах | | maxRetries | number | ❌ | 3 | Максимальное количество попыток при ошибке | | retryDelay | number | ❌ | 1000 | Задержка между попытками в миллисекундах | | includeStackTrace | boolean | ❌ | true | Включать stack trace в метаданные при ошибках | | levelMapping | LevelMapping | ❌ | См. ниже | Кастомный маппинг уровней Winston → Loggy | | extractTags | function | ❌ | См. ниже | Функция для извлечения тегов из metadata | | extractMetadata | function | ❌ | См. ниже | Функция для извлечения метаданных |

Маппинг уровней

По умолчанию уровни маппятся так:

  • errorerror
  • warnwarn
  • infoinfo
  • debugdebug
  • verboseverbose
  • sillydebug
  • httpinfo

Можно переопределить через опцию levelMapping:

new LoggyTransport({
  // ...
  levelMapping: {
    error: 'error',
    warn: 'warn',
    info: 'info',
    customLevel: 'debug', // кастомный уровень
  },
})

Извлечение тегов

По умолчанию теги извлекаются из поля tags в metadata Winston:

logger.info('Message', { tags: ['tag1', 'tag2'] });

Можно настроить кастомную функцию:

new LoggyTransport({
  // ...
  extractTags: (info) => {
    // Извлечь теги из любого поля
    return info.labels || info.categories || [];
  },
})

Извлечение метаданных

По умолчанию все поля из metadata Winston (кроме служебных) отправляются как метаданные:

logger.info('Payment', {
  userId: 'user-123',
  amount: 1000,
  request: { id: 'req-123' },
});

Можно настроить кастомную функцию:

new LoggyTransport({
  // ...
  extractMetadata: (info) => {
    // Включить только нужные поля
    return {
      service: info.service,
      hostname: info.hostname,
      request: info.request,
    };
  },
})

Формат данных

Transport отправляет данные в следующем формате:

{
  "level": "error",
  "message": "Payment failed",
  "timestamp": "2024-01-01T12:00:00.000Z",
  "tags": ["payment", "error"],
  "metadata": {
    "userId": "user-123",
    "error": {
      "message": "Insufficient funds",
      "code": "INSUFFICIENT_FUNDS"
    },
    "request": {
      "id": "req-123",
      "method": "POST",
      "path": "/api/payment"
    }
  }
}

Обработка ошибок

Transport автоматически обрабатывает ошибки:

  • Retry логика: При ошибке сети делается до 3 попыток с экспоненциальной задержкой
  • Client errors (4xx): Не повторяются (кроме 429 - rate limit)
  • Silent failures: Ошибки не крашат приложение, логируются в console.error
  • Timeout: Запросы имеют таймаут (по умолчанию 5 секунд)

Переменные окружения

Рекомендуется использовать переменные окружения:

LOGGY_URL=http://localhost:3000
LOGGY_PROJECT_TOKEN=your-project-token-uuid
new LoggyTransport({
  url: process.env.LOGGY_URL!,
  projectToken: process.env.LOGGY_PROJECT_TOKEN!,
})

Лицензия

MIT