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 🙏

© 2024 – Pkg Stats / Ryan Hefner

logstash-winston-3

v2.1.3

Published

This NPM module provides a LogService class for centralized logging in microservices. It uses Winston library to format and send logs to Logstash for further processing by Elasticsearch. This class can be used in your microservices to centralize and stand

Downloads

17

Readme

License: MIT npm version npm downloads

Table of Contents

LogService 📝

LogService is an npm package that simplifies log management for your application using the winston module. It supports sending logs to a logstash server and also provides methods for logging errors, warnings, debugging, and info messages.

Installation 🚀

npm install --save logstash-winston-3

Usage 🤖

Initial Configuration

To use LogService, you need to create an instance of the LogService class by providing it with the required parameters.

import { LogService } from "logstash-winston-3";

const logger = LogService.getInstance({
  serviceName: "my-app",
  logstashHost: "localhost",
  logstashPort: 5000,
});

Logging

Once you have created an instance of LogService, you can use its methods to log messages. The available log levels are "error", "warn", "info", and "debug". You can also add additional data to your logs using the optional "meta" argument.

logger.info("Hello World");
logger.error("An error occurred", { errorCode: 500 });

Log Configuration

You can customize the log configuration using the following methods:

logger.setLevel("debug"); // Changes the current log level
logger.setSilent(true); // Disables all logging
logger.setPrettyPrint(true); // Makes logs more readable
logger.setJsonStringify(true); // Enables JSON serialization of logs

Logging Unhandled Errors

To log unhandled errors in your application, you can use the "logUnhandledErrors" method.

logger.logUnhandledErrors();

Logging Stack Trace

You can use the "logStackTrace" method to log the stack trace of an error.

try {
  // code that might potentially throw an error
} catch (error) {
  logger.logStackTrace(error);
}

Logging Nested Objects

To log nested objects, you can use the "logNestedObject" method. The depth of the object can also be configured using the optional "maxDepth" argument.

const myObject = {
  name: "John",
  age: 30,
  address: {
    street: "123 Main St",
    city: "New York",
  },
};

logger.logNestedObject(myObject, 2); // logs the myObject up to 2 levels deep

Logging with Context

You can use the "logWithContext" method to add context to your logs. The context is added as a property to the logged object.

logger.logWithContext("database", "info", "Connected to database");

Usage with NestJS 🐝

Create a Logger Provider

To use LogService in your NestJS application, you can create a logger provider that will create an instance of LogService and inject it into your services.

import { Provider } from "@nestjs/common";
import { LogService } from "logstash-winston-3";

export const LoggerProvider: Provider = {
  provide: "Logger",
  useFactory: () => {
    return LogService.getInstance({
      serviceName: "my-app",
      logstashHost: "localhost",
      logstashPort: 5000,
    });
  },
};

In this example, we are creating a provider named "Logger" that will create an instance of LogService using the parameters specified.

Inject the Logger

Now that we have created a logger provider, we can inject it into our services using the "@Inject()" decorator.

import { Injectable, Inject } from "@nestjs/common";

@Injectable()
export class MyService {
  constructor(@Inject("Logger") private readonly logger: LogService) {}

  async myMethod() {
    try {
      // some code that might throw an error
    } catch (error) {
      this.logger.error("An error occurred", { error });
      throw error;
    }
  }
}

In this example, we are injecting the "Logger" provider into our service and using it to log errors.

Use the Logger with Context

You can also use the logger with context to add additional information to your logs.

async myMethod() {
	this.logger.logWithContext('myMethod', 'info', 'Starting execution');
	try {
		// some code
		this.logger.logWithContext('myMethod', 'info', 'Execution successful');
	} catch (error) {
		this.logger.logWithContext('myMethod', 'error', 'An error occurred', { error });
		throw error;
	}
}

In this example, we are adding the name of the method ("myMethod") as the context for our logs. This makes it easier to trace which method generated the log message.

Keep the default winston logs in the console

If you want to keep the default winston logs in the console, you can use the following code:

import { Provider } from "@nestjs/common";
import { LogService } from "logstash-winston-3";

export const LoggerProvider: Provider = {
  provide: "Logger",
  useFactory: () => {
    return LogService.getInstance({
      serviceName: "my-app",
      logstashHost: "localhost",
      logstashPort: 5000,
      callback: (level: "error" | "warn" | "debug", message: string) => {
        logger[level](`${message}`);
      },
    });
  },
};

FAQ

  1. How can I configure LogService to send logs to Logstash?

    LogService can be configured to send logs to a Logstash server by specifying the Logstash host and port when creating an instance of LogService. You can use the getInstance method to create an instance of LogService with the following parameters:

    const logger = LogService.getInstance({
      serviceName: "my-app",
      logstashHost: "localhost",
      logstashPort: 5000,
    });

    In this example, "my-app" is the name of the service for which logs are being collected. You should replace "localhost" with the IP address or hostname of your Logstash server, and "5000" with the port on which Logstash is listening for logs.

  2. How can I add metadata to logs?

    You can add metadata to logs by passing a JSON object as the second argument to the appropriate logging method. For example:

    logger.info("Info", { metadataKey: "metadataValue" });

    In this example, we have added a key-value pair to the log's metadata as a JSON object.

  3. How can I customize the format of logs?

    LogService uses Winston for log management, so you can customize the format of logs using Winston's formatting options. You can use the following options:

    logger.setPrettyPrint(true); // For more readable formatting
    logger.setJsonStringify(true); // For serializing logs to JSON
  4. How can I configure the minimum log level?

    You can configure the minimum log level using LogService's setLevel method. The available log levels are "error", "warn", "info", and "debug".

    logger.setLevel("debug");

    In this example, we have configured the minimum log level to "debug".

  5. How can I use LogService with a framework other than NestJS?

    LogService can be used with other popular frameworks or libraries. You can create an instance of LogService with the appropriate parameters and use it to log events in your application.

  6. How can I use LogService with different log transport protocols?

    LogService can be used with different log transport protocols such as syslog or fluentd using the corresponding log transport libraries. The log transport libraries can be installed via npm and imported into your application.

  7. How can I troubleshoot common errors when using LogService?

    If you encounter errors when using LogService, you can check that the configuration parameters are correct and that the required libraries are installed. You can also check the server logs to detect errors and warnings that may be related to the use of LogService. If you are not sure of the cause of the error, you can consult the documentation or reach out to the LogService community for help.

Contributing

Contributions to LogService are always welcome! If you find a bug or want to suggest a new feature, please open an issue on the GitHub repository.

If you want to contribute code, please fork the repository and create a new branch for your feature or bug fix. Once you have made your changes, create a pull request and we will review your code.

Please make sure to follow our code of conduct and our contribution guidelines when contributing to LogService. We ask that you be respectful and professional in all interactions with other contributors and maintainers.

License 📜

LogService is distributed under the MIT license. See the LICENSE file for details.

Author 🙋‍♀️

This package was created by Cerfio. Please consider starring the project on Github if you find it helpful! ✨