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

@innova2/winston-mongodb

v1.0.2

Published

A TypeScript MongoDB transport for winston.

Downloads

5

Readme

Winston MongoDB transport

A easy to use Winston 3.x transport for MongoDB.

:hammer_and_wrench: Installation

To import the library you just need to run this command :

npm install @innova2/winston-mongodb

Make sure you have Winston, otherwise run this command :

npm install winston

:memo: Usage

Configuration

Instantiate the MongoTransport and pass options:

const mongoTransport = new MongoTransport({
    connectionString: 'your mongo connection string',
    dbName: 'your database name',
    collectionName: 'your collection name',
    isCollectionCapped: true,
    cappedSize: 100000000, // 100 Mo
    clientOptions: {
        maxPoolSize: 10,
    },
});

The collection will be automatically created if it does not exist.

Look at the available options:

export interface MongoTransportOptions extends TransportStreamOptions {
    /**
     * Connection URI.
     */
    connectionString: string;

    /**
     * Optional. Options on creation of Mongo connection.
     */
    clientOptions?: MongoClientOptions;

    /**
     * Name of the database.
     */
    dbName: string;

    /**
     * Name of the collection.
     * The collection is auto-generated if it does not exist.
     */
    collectionName: string;

    /**
     * Is collection capped (size limitation).
     */
    isCollectionCapped: boolean;

    /**
     * Optional. Size limit in bytes of the capped collection.
     */
    cappedSize?: number;

    /**
     * Optional. Flat map meta properties (spread out at the root of the Mongo document).
     */
    metaDataToFlatten?: string[];
}

Specific document structure

You can override the type corresponding to the document structure by passing the type to generic of constructor.

Look at the base log interface:

export interface BaseLogDocument extends OptionalId<Document> {
    level: string;
    message: string;
    meta?: object;
    timestamp: string;
}

For example, you want to add 'context' and 'module' fields. Just create a custom log interface by extending BaseLogDocument like:

export interface CustomLog extends BaseLogDocument {
    context: string;
    module: string;
}

And configure your instance like:

const mongoTransport = new MongoTransport<CustomLog>({
    connectionString: 'your mongo connection string',
    dbName: 'your database name',
    collectionName: 'your collection name',
    isCollectionCapped: true,
    cappedSize: 100000000, // 100 Mo
    clientOptions: {
        maxPoolSize: 10,
    },
    // don't forget the metaDataToFlatten, so that
    // this metadata is at the top level of the document
    metaDataToFlatten: ['module', 'context'],
});

Please note that changing the type it has no impact on database structure. It's only useful when retrieving logs or directly the collection (MongoTransport#getCollection). The document structure in the database depending on winston logs structure.

Example of logging with Nest:

// Logging interceptor
this.logger.log(
    {
        message: 'HTTP call',
        // Metadata (meta object in DB)
        method: req.method,
        path: req.url,
        statusCode: res.statusCode,
        responseTimeInMs: endDate - startDate
    },
    [ctrlName, methodName].join(LOG_CTX_SEPARATOR), // Context (flattened by 'metaDataToFlatten' option)
);

// Simple formatting logs
const formattingLog = winston.format(entry => ({
    ...entry,
    module: 'API', // Flattened by 'metaDataToFlatten' option
}));

export default async (mongoTransport: MongoTransport): Promise<WinstonModuleOptions> => ({
    format: winston.format.combine(formattingLog(), winston.format.json()),
    transports: [mongoTransport],
});

Retrieve logs

You can use the query() method like:

transport.query({
    timestamp: {
        $gte: new Date(...),
        $lte: new Date(...),
    }
});

The result type is: Promise<T[]>. T is BaseLogDocument or your custom type.

If you want paginated date, just push 'limit' option:

transport.query({
    timestamp: {
        $gte: new Date(...),
        $lte: new Date(...),
    }
}, { limit: 20 }); // First page

The result type is: Promise<PaginatedDataDto<T>>. T is BaseLogDocument or your custom type.

To reach another page:

transport.query({
    timestamp: {
        $gte: new Date(...),
        $lte: new Date(...),
    }
}, { limit: 20, skip: 20 }); // Second page

You can also directly use the collection Mongo object by calling transport.getCollection().

:balance_scale: Licence

MIT

:busts_in_silhouette: Authors

:handshake: Contributors

Do not hesitate to participate in the project! Contributors list will be displayed below.