# starling-logger

> Colorful logger for NodeJS apps

Latest version **3.0.0** (published 2022-06-07) · SEE LICENSE IN LICENSE license · 0 weekly downloads

## Install

```sh
npm install starling-logger
pnpm add starling-logger
yarn add starling-logger
bun add starling-logger
```

## Health

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

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 3.0.0 |
| Published | 2022-06-07 |
| First published | 2022-06-04 |
| Weekly downloads | 0 |
| License | SEE LICENSE IN LICENSE |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 2 |
| Unpacked size | 38.4 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Max-Starling |
| Maintainers | max_starling |
| Keywords | colorful, colors, logger, nodejs, starling, console, logs, request, response, custom, logging, prettify, output, warning, error, info, success |

## Links

- npm: https://www.npmjs.com/package/starling-logger
- Repository: https://github.com/Max-Starling/starling-logger
- Homepage: https://github.com/Max-Starling/starling-logger#readme
- Issues: https://github.com/Max-Starling/starling-logger/issues
- npm.io page: https://npm.io/package/starling-logger

## Dependencies (2)

- [chalk](https://npm.io/package/chalk.md) ^4.1.2
- [moment](https://npm.io/package/moment.md) ^2.29.3

## Alternatives

- [cli-color](https://npm.io/package/cli-color.md) — 3.4M weekly downloads
- [log](https://npm.io/package/log.md) — 1.3M weekly downloads
- [logstash-client](https://npm.io/package/logstash-client.md) — 4.5K weekly downloads
- [@nocobase/plugin-logger](https://npm.io/package/@nocobase/plugin-logger.md) — 2.0K weekly downloads
- [child-process-debug](https://npm.io/package/child-process-debug.md) — 695 weekly downloads

## Recent versions

- 3.0.0 (latest) — 2022-06-07
- 2.1.3 — 2022-06-05
- 2.1.2 — 2022-06-05
- 2.1.1 — 2022-06-05
- 2.1.0 — 2022-06-05
- 2.0.0 — 2022-06-04
- 1.0.0 — 2022-06-04

## README

# starling-logger
- [Description](#description)
  - [Log structure](#log-structure)
- [Installation](#installation)
- [Usage](#usage)
  - [Basic types](#basic-types)
  - [Custom type](#custom-type)
  - [HTTP request and response](#http-request-and-response)
  - ["Go to line" feature in VSCode](#go-to-line-feature-in-vscode)
  - [Return value](#return-value)
- [Config](#config)
  - [Date](#date)

## Description

`starling-logger` is a colorful logger written in TypeScript with minimal dependencies that supports
* different log types: 4 default types and custom types,
* beautiful display of objects, colors for all primitives 
* HTTP request & response logging support,
* determining the filename and the line on which logger method is called. 

### Log structure
By default logs have the following structure:
```js
DATE | SCENE | LOG_TYPE | ...MESSAGES
```
In more detail,
```js
MMM D, YYYY HH:mm:ss | file_name:line_of_code | LOG_TYPE | value1 value2 ... valueN
```
You can change the structure using [Config](#config).

## Installation
Install the latest version
```
> npm install starling-logger
```
Install the specific version `x.y.z`
```
> npm instsall starling-logger@x.y.z
```
[List of all versions can be found on NPM](https://www.npmjs.com/package/starling-logger)

## Usage
- [Basic types](#basic-types)
- [Custom type](#custom-type)
- [HTTP request and response](#http-request-and-response)
- ["Go to line" feature in VSCode](#go-to-line-feature-in-vscode)
- [Return value](#return-value)

### Basic types

The starling-logger has 5 basic log types and 4 methods for them:
* `LOG` (white) - `log(...messages: any[]): string`,
* `SUCCESS` (green) - `success(...messages: any[]): string`, 
* `INFO` (green) - `info(...messages: any[]): string`, 
* `WARNING` (yellow) - `warning(...messages: any[]): string`, 
* `ERROR` (red) - `error(...messages: any[]): string`.

You pass values of any type using commas - the method beautifully combines them in one message.

Example:
```ts
/* app.ts */
import Logger from 'starling-logger';

/* ... */

const logger = new Logger();

logger.log("beautiful object", {
  objectOfClass: new Date(),
  number: 100,
  string: "starling",
  null: null,
  boolean: true,
  arrayOfValues: [
    null,
    undefined,
    17,
    19.1,
    true,
    false,
    "first name",
    "last name"
  ]
});
logger.success("App is listening on port", 8080);
logger.info("Service is ready for usage");
logger.warning("You propably shouldn't use this method in development mode");
logger.error(new Error("Something went wrong"));
```
![Screenshot 2022-06-05 112401](https://user-images.githubusercontent.com/22237384/172041993-cad9c49a-cff3-4f6b-a3bc-e90184f5a49b.png)



### Custom type

You can use your custom log type using
```ts
logCustom({
  type: '<input your type name>',
  color: '<select color from available LOG_COLORS>',
}, ...messages: any[])
```

Example
```ts
/* app.ts */
import Logger, { LOG_COLORS } from "starling-logger";

const logger = new Logger();

logger.logCustom(
  { type: "CUSTOM", color: LOG_COLORS.blue },
  "my awesome customized log"
);

const logTest = (...messages) =>
  logger.logCustom({ type: "TEST", color: LOG_COLORS.magenta }, ...messages);
logTest("test of custom log type");
```

![image](https://user-images.githubusercontent.com/22237384/172044255-9198080c-55d5-4f89-84a0-0873396f7c8a.png)


### HTTP request and response

```ts
interface RequestData {
  method?: string;
  url?: string;
}

interface ResponseData {
  statusCode?: number;
  responseTime?: number;
}

interface ResponseError {
  message: string;
}
```
```ts
logRequest(req: RequestData)
logResponse(req: RequestData, res: ResponseData, err: ResponseError)
```
Example for Express app
```ts
/* app.ts */

/* before all other middlewares */
app.use((req, res, next) => {
  req.startedAt = process.hrtime();
  logger.logRequest(req);
  next();
});

/* ... */

/* after all middlewares */
const hrtimeToMs = hrtime => {
  const msFloat = hrtime[0] * 1000 + hrtime[1] / 1000000;
  return parseInt(`${msFloat}`, 10);
};

/* response success */
app.use((req, res, next) => {
  res.responseTime = hrtimeToMs(process.hrtime(req.startedAt));
  logger.logResponse(req, res);
  next();
});

/* response error */
app.use((err, req, res, next) => {
  res.responseTime = hrtimeToMs(process.hrtime(req.startedAt));
  logger.logResponse(req, res, err);
  next();
});
```

### "Go to line" feature in VSCode

This feature is supported by VSCode.

Since we have `file_name:line_of_code` in every log, you can click on it in the console and the search window fill be open with `file_name:line_of_code` filled.

![image](https://user-images.githubusercontent.com/22237384/172326865-a4f526a5-0e4a-46e4-8f95-5dddc8b67587.png)

Click on the correct file from the list and you will be taken to the line with which the logger method was called.

### Return value

Instead of returning nothing as `console.log` does, `starling-logger` returns log as `string`.
```ts
const logger = new Logger();
const successMessage = logger.success('Connected!');
console.log(successMessage);
```

So you can use it for testing, outputing somewhere else or futher formatting.

All logger methods are tested with unit tests via Jest due to `string` return values. 


## Config
You can change logger configuration via `loggerConfig` passing it to the constructor when creating the logger instance.
```ts
class Logger {
  constructor(loggerConfig: LoggerConfig) { /* ... */ }
}
const logger = new Logger({ /* ... */ });
```
```ts
interface LoggerConfig {
  showDate?: boolean;
  scene?: string | null;
  output?: any;
}
```
```ts
const DEFAULT_LOGGER_CONFIG = {
  showDate: true,
  scene: null,
  output: console.log,
}
```

### Date
`starling-logger` uses Moment to format dates. Current date format is `"MMM D, YYYY HH:mm:ss"`

You can hide date using `{ showDate: false }` option in logger config.
```ts
const logger = new Logger({ showDate: false });
```
Disabling date may be useful for production because date might be already shown in some remote console tools.

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