Logging with pino & TypeScript [JavaScript/Express.js]


pino is a fast logger (Benchmarks).

This articles shows how to use pino with TypeScript and Express.js.

😸 Installation

yarn add pino # npm install --save pino
yarn add --dev @types/pino

🐡 Configuration

Add ./src/utils/Logger.ts, like this:

import * as pino from "pino";
import { APP_ID, LOG_LEVEL } from "./Config";

export const logger = pino({
name: 'app-name',
level: 'debug'
});

After then, you can use the logger.

🗻 With Express.js

If you want to use pino with Express.js, please add

yarn add express-pino-logger

After then, you can use pino with Express:

import * as express from "express";
import * as expressPinoLogger from "express-pino-logger";
import { logger } from './utils/Logger';

const app = express();
app.use(expressPinoLogger({ logger: logger }));

app.get("/", function(req, res) {
res.send("hello world");
});

app.listen(3000);

🚌 Appendix

Support logs into multiple files

Installation

npm i pino-tee -g

How to use

const pino = require('pino');
const childProcess = require('child_process');
const stream = require('stream');

// Environment variables
const cwd = process.cwd();
const {env} = process;
const logPath = `${cwd}/log`;

// Create a stream where the logs will be written
const logThrough = new stream.PassThrough();
const log = pino({name: 'project'}, logThrough);

// Log to multiple files using a separate process
const child = childProcess.spawn(process.execPath, [
require.resolve('pino-tee'),
'warn', `${logPath}/warn.log`,
'error', `${logPath}/error.log`,
'fatal', `${logPath}/fatal.log`
], {cwd, env});

logThrough.pipe(child.stdin);

// Log pretty messages to console (optional, for development purposes only)
const pretty = pino.pretty();
pretty.pipe(process.stdout);
logThrough.pipe(pretty);

🗽 References

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!