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 🙏

© 2025 – Pkg Stats / Ryan Hefner

log-gateway-client

v3.0.0

Published

TypeScript log gateway client library for centralized logging with Loki and Grafana

Readme

Log Gateway Client

npm version TypeScript License: MIT

A TypeScript-first client library for centralized logging with Loki and Grafana. Zero dependencies, full type safety, and perfect for NestJS applications.

Features

  • 🚀 Zero Dependencies - Uses only Node.js built-in modules
  • 📝 Full TypeScript Support - Native TypeScript with complete type definitions
  • 🎯 Simple API - Easy-to-use methods for all log levels
  • 🔧 NestJS Ready - Perfect integration with NestJS applications
  • 📦 Lightweight - Minimal footprint, maximum performance
  • 🌐 Flexible - Works with any log gateway that accepts JSON
  • Async/Await - Modern Promise-based API

Installation

npm install log-gateway-client
yarn add log-gateway-client
pnpm add log-gateway-client

Quick Start

Basic Usage

import { configure, log } from 'log-gateway-client';

// Configure once at application startup
configure('http://localhost:8080', 'my-app-id', 'your-bearer-token');

// Use anywhere in your application
await log.info({
  msg: "User logged in successfully",
  userId: 123,
  service: "auth-service"
});

await log.warning({
  msg: "High memory usage detected",
  memoryUsage: 85.5,
  threshold: 80
});

await log.error({
  msg: "Payment processing failed",
  errorCode: "PAYMENT_DECLINED",
  orderId: "ORD-123"
});

Client Instance Usage

import { createClient } from 'log-gateway-client';

const logger = createClient('http://localhost:8080', 'my-app-id', 'your-bearer-token');

await logger.info({
  msg: "Service started",
  port: 3000,
  environment: "production"
});

NestJS Integration

// app.module.ts
import { configure } from 'log-gateway-client';

@Module({
  // ... your module config
})
export class AppModule implements OnModuleInit {
  onModuleInit() {
    configure(
      process.env.LOG_GATEWAY_URL,
      process.env.APP_ID,
      process.env.BEARER_TOKEN
    );
  }
}

// user.service.ts
import { log } from 'log-gateway-client';

@Injectable()
export class UserService {
  async createUser(userData: CreateUserDto) {
    try {
      const user = await this.userRepository.save(userData);

      await log.info({
        msg: "User created successfully",
        userId: user.id,
        service: "user-service"
      });

      return user;
    } catch (error) {
      await log.error({
        msg: "Failed to create user",
        error: error.message,
        service: "user-service"
      });
      throw error;
    }
  }
}

Dependency Injection Pattern

import { createClient, LogGatewayClient } from 'log-gateway-client';

@Injectable()
export class LoggerService {
  private readonly logger: LogGatewayClient;

  constructor() {
    this.logger = createClient(
      process.env.LOG_GATEWAY_URL,
      process.env.APP_ID,
      process.env.BEARER_TOKEN
    );
  }

  async logUserAction(userId: number, action: string, metadata?: any) {
    return this.logger.info({
      msg: \`User performed \${action}\`,
      userId,
      action,
      service: "user-tracking",
      ...metadata
    });
  }
}

API Reference

Configuration

configure(endpoint: string, appId: string, bearerToken: string): LogGatewayClient

Configure the global logger instance.

  • endpoint: URL of your log gateway (e.g., 'http://localhost:8080')
  • appId: Your application identifier
  • bearerToken: Bearer token for SSO authentication

Logging Methods

log.info(payload: LogPayload): Promise<LogResponse>

log.warning(payload: LogPayload): Promise<LogResponse>

log.error(payload: LogPayload): Promise<LogResponse>

log.debug(payload: LogPayload): Promise<LogResponse>

Send logs with the specified level.

Client Factory

createClient(endpoint: string, appId: string, bearerToken: string): LogGatewayClient

Create a new client instance for dependency injection or multiple configurations.

Types

interface LogPayload {
  msg: string;                    // Required: Log message
  service?: string;               // Optional: Service name
  timestamp?: string;             // Optional: Custom timestamp
  [key: string]: any;            // Any additional fields
}

interface LogResponse {
  success: boolean;
  ingested: number;
}

interface BatchLogPayload extends LogPayload {
  level: 'info' | 'warn' | 'error' | 'debug';
}

Examples

Structured Logging

// Application metrics
await log.info({
  msg: "API request processed",
  method: "POST",
  endpoint: "/api/users",
  statusCode: 201,
  duration: 145,
  userId: 12345
});

// Error tracking
await log.error({
  msg: "Database connection failed",
  database: "postgresql",
  host: "db.example.com",
  errorCode: "CONNECTION_TIMEOUT",
  retryAttempt: 3
});

// Performance monitoring
await log.warning({
  msg: "Slow query detected",
  query: "SELECT * FROM users WHERE...",
  duration: 2500,
  threshold: 1000,
  table: "users"
});

Custom Service Logging

class PaymentService {
  private logger = createClient(
    process.env.LOG_GATEWAY_URL,
    'payment-service',
    process.env.BEARER_TOKEN
  );

  async processPayment(paymentData: PaymentDto) {
    await this.logger.info({
      msg: "Payment processing started",
      orderId: paymentData.orderId,
      amount: paymentData.amount,
      service: "payment-service"
    });

    try {
      const result = await this.paymentProvider.charge(paymentData);

      await this.logger.info({
        msg: "Payment processed successfully",
        orderId: paymentData.orderId,
        transactionId: result.id,
        service: "payment-service"
      });

      return result;
    } catch (error) {
      await this.logger.error({
        msg: "Payment processing failed",
        orderId: paymentData.orderId,
        error: error.message,
        service: "payment-service"
      });
      throw error;
    }
  }
}

Requirements

  • Node.js >= 16.0.0
  • TypeScript >= 4.5.0 (for TypeScript projects)

License

MIT © t-Oil

Contributing

  1. Fork the repository
  2. Create your feature branch (`git checkout -b feature/amazing-feature`)
  3. Commit your changes (`git commit -m 'Add some amazing feature'`)
  4. Push to the branch (`git push origin feature/amazing-feature`)
  5. Open a Pull Request

Support


Made with ❤️ for the logging community