# logging-chiper

> just a little module to log

Latest version **2.1.0** (published 2022-06-22) · ISC license · 0 weekly downloads

## Install

```sh
npm install logging-chiper
pnpm add logging-chiper
yarn add logging-chiper
bun add logging-chiper
```

## Health

**Score 20/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities.

Warnings: low downloads; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.1.0 |
| Published | 2022-06-22 |
| First published | 2022-03-02 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 3 |
| Unpacked size | 18.6 KB |
| Known vulnerabilities | 0 (+1 in 1 direct dependencies) |
| Install scripts | no |
| Author | chiper@cristiandi |
| Maintainers | cristiandi.chiper |

## Links

- npm: https://www.npmjs.com/package/logging-chiper
- npm.io page: https://npm.io/package/logging-chiper

## Dependencies (3)

- [uuid](https://npm.io/package/uuid.md) ^8.3.2
- [winston](https://npm.io/package/winston.md) 3.7.2
- [@google-cloud/logging-winston](https://npm.io/package/@google-cloud/logging-winston.md) 4.2.3

## Recent versions

- 2.1.0 (latest) — 2022-06-22
- 2.0.0 — 2022-05-10
- 1.4.2 — 2022-04-27
- 1.4.1 — 2022-03-03
- 1.4.0 — 2022-03-03
- 1.3.0 — 2022-03-03
- 1.2.0 — 2022-03-02
- 1.1.0 — 2022-03-02
- 1.0.0 — 2022-03-02

## README

# Logging Chiper

# Table of Contents

- [Logging Chiper](#logging-chiper)
- [Table of Contents](#table-of-contents)
- [Description](#description)
- [Motivation](#motivation)
- [Requirements](#requirements)
- [Usage](#usage)
  - [Install](#install)
  - [Initialization](#initialization)
  - [Parameters](#parameters)
  - [Example](#example)

# Description

This simple module offers a way to use some functionalities from the
[logging-chiper](https://github.com/chiper-inc/logging-chiperr).

# Motivation

As company we want to standardize the way we log our application, so that's we
wrote this module to make it easier to log our application.

# Requirements

1. Nodejs LTS.
2. **GOOGLE_APPLICATION_CREDENTIALS** defined with the file path as environment
   variable.

# Usage

## Install

`npm i logging-chiper -S -E`

OR

`yarn add logging-chiper -S -E`

## Initialization
To initialize the logger you need call the `init` function at start point of your application, using the following parameters:

```typescript
// import the class from the library
import { Logger } from 'logging-chiper';

Logger.init({
  projectId: 'your-project-id',
  service: 'your-service-name',
  version: '0.0.1',
});
```

## Parameters

As we want to standardize the way we log our application, so we defined a base
structure as input parameters to accomplish this:

```typescript
// Log method
Logger.getInstance().log({
  stt: 'my-stt', // name of the stt owner
  context: 'my-context', // name of the class or file (optional)
  functionName: 'my-function', // name of the function (optional)
  message: 'my-message', // message to log
  data: { // data to log (optional)
    storeId: '' + 123456,
    responseCode: '' + 200,
    testField: 'test',
    extraField: 'extra',
  },
});

// Warn method
Logger.getInstance().warn({
  stt: 'my-stt', // name of the stt owner
  context: 'my-context', // name of the class or file (optional)
  functionName: 'my-function', // name of the function (optional)
  message: 'my-message', // message to log
  data: { // data to log (optional)
    storeId: '' + 123456,
    responseCode: '' + 200,
    testField: 'test',
    extraField: 'extra',
  },
});

// Error method
Logger.getInstance().error({
  stt: 'my-stt', // name of the stt owner
  context: 'my-context', // name of the class or file (optional)
  functionName: 'my-function', // name of the function (optional)
  message: 'my-message', // message to log
  error, // the exception to log that just occurred
  data: { // data to log (optional)
    storeId: '' + 123456,
    responseCode: '' + 200,
    testField: 'test',
    extraField: 'extra',
  },
});
```

As you can see, all the methods follows almost the same structure, but when you
want to log an error, you need to pass the error as parameter.

## Examples

### Simple Log
```typescript
import { Logger } from 'logging-chiper';

const bootstrap = () => {
  Logger.init({
    projectId: 'your-project-id',
    service: 'your-service-name',
    version: '0.0.1',
  });

  Logger.getInstance().log({
    stt: 'solutions',
    context: 'main.ts',
    functionName: 'bootstrap',
    message: 'this is a log message...',
  });
};
}

bootstrap();
```

### Log Requests

#### With Express

```typescript
import { createMiddleware } from 'logging-chiper';
import express, { Request, Response } from 'express';
import { AddressInfo } from 'net';
import { LoggingWinston } from '@google-cloud/logging-winston';
import { transports } from 'winston';

const app = express();

createMiddleware([ // creates the middleware
  new transports.Console(), // logs to console
  new LoggingWinston({ // logs to gpc 
    projectId: "chiper-development",
    logName: "myapp"
  })
]).then((mw) => {

  app.use(mw); // setup middler into express

  app.get('/info', (req: Request, res: Response) => {
    (req as any).log.info("get Hello World!"); // Using log from request
    res.status(200).send('Hello World!');
  });

  const server = app.listen(3000, () => {
    const address = (server.address() as AddressInfo)
    mw.logger.info(`running at http://${address.address}:${address.port}`); // use the logger from mw.
  });

});

```

## With NestJS

- You need the create an interceptor for logging:

app.logmiddleware.ts
```typescript
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { createMiddleware } from 'logging-chiper';
import { LoggingWinston } from '@google-cloud/logging-winston';
import { transports } from 'winston';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  async use(req: Request, res: Response, next: NextFunction) {
    const mw = await createMiddleware([ // creates the middleware
        new transports.Console(), // logs to console
        new LoggingWinston({ // logs to gpc 
        projectId: "chiper-development",
        logName: "myapp"
        })
    ])
    mw(req, res, next);
  }
}

```
- And then configure in the module:

app.module.ts
```typescript
import { MiddlewareConsumer, Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { LoggerMiddleware } from "./app.loggermiddleware";

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware)
      .forRoutes('*');
  }
}
```

---
_Source: https://npm.io/package/logging-chiper · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
