Skip to content

Commit

Permalink
feat: initial commit of open sourced code
Browse files Browse the repository at this point in the history
  • Loading branch information
sekhavati committed Jul 13, 2023
0 parents commit 5a67d87
Show file tree
Hide file tree
Showing 16 changed files with 19,525 additions and 0 deletions.
35 changes: 35 additions & 0 deletions .github/workflows/continuous-integration.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
name: Continuous Integration

on: pull_request

jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
matrix:
node: [ 16, 18 ]
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node }}
- run: npm version
- run: npm ci
- run: npm run build

unit-test:
needs: [build]
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
matrix:
node: [ 16, 18 ]
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node }}
- run: npm ci
- run: npm run lint
- run: npm run test
48 changes: 48 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
name: Publish Package

on:
push:
tags:
- 'v[0-9]+.[0-9]+.[0-9]+'

jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: "16"
- run: npm version
- run: npm ci
- run: npm run build

unit-test:
needs: [build]
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: "16"
- run: npm ci
- run: npm run lint
- run: npm run test

publish:
needs: [unit-test]
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: "16"
- run: npm ci
- run: npm run build
- run: npm config set //registry.npmjs.org/:_authToken ${NPM_TOKEN}
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- run: npm publish --access=public
17 changes: 17 additions & 0 deletions .github/workflows/version-changelog.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: Version & Changelog

on:
push:
branches:
- main

jobs:
version:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: google-github-actions/release-please-action@v3
with:
release-type: node
package-name: "logger-nodejs"
token: ${{ secrets.RELEASE_PLEASE_TOKEN }}
112 changes: 112 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Webstorm
.idea/

# MacOS
.DS_Store

build/
4 changes: 4 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx lint-staged
3 changes: 3 additions & 0 deletions .lintstagedrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"*.{js,ts,json,yml}": "npm run lint"
}
5 changes: 5 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"singleQuote": false,
"bracketSpacing": true,
"trailingComma": "es5"
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Cuckoo Internet

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
140 changes: 140 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
# logger-node

A simple and fast JSON logging library for Node.js services

## Usage

```javascript
import { Logger } from "@cuckoointernet/logger-node";

const logger = new Logger("my-package");
```

### Log simple messages at different levels

```javascript
logger.debug("Hello Cuckoo!");
logger.info("Hello Cuckoo!");
logger.warn("Hello Cuckoo!");
logger.error("Hello Cuckoo!");
logger.fatal("Hello Cuckoo!");
```

### Log additional data via the second argument

```javascript
// Data in object supplied is automatically merged into the log record
logger.info("Hello Cuckoo!", { colour: "yellow" });
```

#### Serialisers

Data provided to the second argument undergoes additional processing if they match certain keys. For instance, if you pass an object with an `error` key it will be run through a serialiser that is able to process stack information in a better way. The standard serialisers are:

| Field | Description |
| ------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `error` | Used for serialising JavaScript error objects, including traversing an error's cause chain for error objects with a `.cause()` |
| `err` | Same as `error` (deprecated) |
| `req` | Common fields from a node.js HTTP request object |
| `res` | Common fields from a node.js HTTP response object |

### Log JavaScript `Error` objects

```javascript
// Alternatively you can supply an instance of Error to log its exception details via the second argument
logger.warn("Sad Cuckoo...", new Error("Wings were clipped!"));

// To log an Error *and* other data at the same time, use the 'error' field name
logger.error("Sad Cuckoo...", {
error: new Error("Wings were clipped!"),
colour: "yellow",
});
```

### Return a JavaScript `Error` after logging

When logging at levels `error` and `fatal` you can return a JavaScript `Error` that has the same message as the log record and then `throw`:

```javascript
// The message of the error thrown will be "Mission failed"
throw logger.error("Mission failed").returnError();

// You can log additional data via the second argument as per usual
throw logger
.fatal("Mission failed", { reason: "Ran out of fuel..." })
.returnError();
```

### Child Loggers

A child logger can be created from an existing one to specialize a logger for a sub-component of your application, i.e. to create a new logger with additional bound fields that will be included in its log records.

```javascript
const parentLogger = new Logger("parent", "debug");

// The child logger inherits the same name and log level as the parent
const childLogger = parentLogger.createChildLogger({
subPackage: "child",
anotherChildField: "whatever-you-want",
});

// All log records will contain the two additional fields setup at initialisation, ie: subPackage & anotherChildField
childLogger.info("Hello from child");
```

## Log Levels

Setting a logger instance to a particular level results in only log records of that level and above being written. You can configure it via the options below:

1. If not specified the logger defaults to `info` level:

```javascript
const logger = new Logger("my-package");
```

2. Set via `logLevel` constructor parameter:

```javascript
const logger = new Logger("my-package", "debug");
```

3. Set via `LOG_LEVEL` environment variable:

```javascript
// process.env.LOG_LEVEL = "debug"
const logger = new Logger("my-package");
```

The available log levels and best practices guidance on when to use them are as follows:

- `fatal` (60): The service/app is going to stop or become unusable now
- `error` (50): Fatal for a particular request, but the service/app continues servicing other requests
- `warn` (40): A note on something that should probably be looked at
- `info` (30): Detail on regular operation
- `debug` (20): Anything else, i.e. too verbose to be included in "info" level

If you want to prevent the logger from printing any messages you can set the log level to `silent`. This is sometimes useful, for example when running tests to reduce noise in the terminal.

## Log Records

The structure of log records is outlined below:

```
{
// User supplied data
name: "my-package",
msg: "Hello Cuckoo!",
...any additional data supplied via second argument to logger methods (see examples above)
// Record metadata (added automatically)
logLevel: "info",
level: 30,
time: "2022-02-03T19:02:57.534Z",
hostname: "banana.local",
pid: 123,
// AWS metadata (added automatically if applicable)
@requestId: <id>
}
```

0 comments on commit 5a67d87

Please sign in to comment.