• Stars
    star
    119
  • Rank 297,930 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 5 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A simple, practical and innovative Node.js log library that enables you to view logs in Chrome dev tools and browser Console.

ServerLog

中文文档

A simple, practical and innovative Node.js log library that enables you to view logs in Chrome dev tools and browser Console.

ServerLog contains the following features:

  • Friendly log output format;
  • Support info, warn, error 3 log levels, as simple as possible API design;
  • By registering Express middleware, can automatically attach the request URL to the end of the log;
  • The log generated by the same batch request generates a Request ID to facilitate the association and filtering of the logs;
  • The accompanying Chrome extension allows you to view request related logs in Chrome dev tools and browser Console.

Preview

  • Print in terminal:

image

  • Print in Chrome extension:

image

  • Print in browser Console:

image

Get started

Install

> npm i --save serverlog-node

Usage

const serverlog = require('serverlog-node');
const logger = serverlog.getLogger('home');

logger.info('Something to log...');

If you are using Express framework, you can get another functionality by registering middleware:

  • Automatically add request ID in the request log.
  • Automatically add the current URL in the request log.
  • Send the request log to the Chrome extension, and you can view the logs in the Chrome dev tools and browser Console panel.
const express = require('express');
const app = express();
const serverlog = require('serverlog-node');
const logger = serverlog.getLogger();

app.use(serverlog.middleware());

app.use((req, res) => {
    logger.info('Something to log within request...');
    res.send('Hello World!');
});

Chrome extension

It's easier to view logs using the accompanying Chrome extension.

https://github.com/eshengsky/ServerLog/tree/master/chrome-extension-server-log

Api

serverlog

config(Options)

Overwrite the default settings with the incoming Options.

Options: parameters object.

serverlog.config({
    console: {
        colors: true,
        depth: null,
        appendUrl: true,
        forceSingleLine: false
    },
    extension: {
        enable: true,
        key: 'yourownsecretkey'
    }
});

The full parameters supported are as follows:

Property name Description Type Default
console.colors Enable colors boolean true
console.depth The parsing depth of the object, see here util.inspect number null
console.appendUrl Automatically attach the current request URL to the end of the log boolean true
console.forceSingleLine Force each log to not wrap boolean false
extension.enable Enable Chrome extension functions boolean true
extension.key The key of the current service, see here Secret Key string yourownsecretkey
extension.maxLength Max length of logs, in kb units number 80

middleware()

Registers log middleware that supports frameworks that are compatible with Express middleware.

app.use(serverlog.middleware());

getLogger(categoryName)

Create and return a logger instance.

categoryName: String, log category name, default: normal.

logger

info(arg1, arg2, ...args)

Logs an info log that can be passed in to any type, any number of parameters.

logger.info('This is an info log.');

warn(arg1, arg2, ...args)

Logs an warning log that can be passed in to any type, any number of parameters.

let undef;
logger.warn('This is a warning log.', 'Take care, undef value is:', undef);

error(arg1, arg2, ...args)

Logs an error log that can be passed in to any type, any number of parameters.

try {
    foo.bar();
} catch (err) {
    logger.error('This is an error log. Error:', err);
}

infoC(arg1, arg2, ...args), warnC(arg1, arg2, ...args), errorC(arg1, arg2, ...args)

Output only the corresponding logs to the terminal.

infoE(arg1, arg2, ...args), warnE(arg1, arg2, ...args), errorE(arg1, arg2, ...args)

Output only the corresponding logs to the Chrome extension.

// Print the full file content in the Chrome extension
logger.infoE('read data from local file:', JSON.parse(data));

// Just print a little in console
logger.infoC('read data from local file, please view data in Chrome extension.');

Request ID

What is request ID

After registered middleware, all the logs associated with the request contain a request ID by default. In the same request, the request ID for all logs must be the same, and the request ID must be different in different requests.

For example, when user A accesses the index.html process ServerLog prints 10 logs, the request ID for the 10 logs are the same, and user B also accesses the page, resulting in 10 logs, which must also have the same request ID, but different from the request ID of User A.

Main role

Lets you be able to correlate all the logs you need in a large number of logs, as long as you know the request ID of one log.

How to find request ID

When you can navigate to a log related to a request, between the category name of log and the contents of the log, is the request ID. For example, the following Ra8dx5lAL:

[2019-05-08 15:23:06.911] [INFO] home - {Ra8dx5lAL} This is an info log. (URL: http://localhost:3000/)

If you can listen to a network request for a page, the response header x-request-id is the request ID:

x-request-id: Ra8dx5lAL

Persistence

ServerLog only output to stdout and stderr, does not provide the ability to log persistence, but you can do so in other ways:

  • Use PM2

If you deploy your project with PM2, logs will automatically save to the disk file. You can use PM2's own log management function to achieve log viewing, rotate, and so on.

By default, log file saved into $HOME/.pm2/logs directory.

  • Common

In a Linux environment, it is easy to redirect the output to a file with very simple commands, such as:

node server.js > logfile.txt

Specific can be referred here.

Example

https://github.com/eshengsky/ServerLog/tree/master/example

License

MIT License

Copyright (c) 2019 Sky.Sun

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.

More Repositories

1

iBlog

基于 Node.js 的开源个人博客系统,采用 Nuxt + Vue + TypeScript 技术栈。
Vue
1,336
star
2

node-bff

基于 Node.js 的可视化 BFF 解决方案。
Vue
215
star
3

lajax

🚀 lajax - 前端日志解决方案。
JavaScript
200
star
4

jQuery-emoji

😄 Let textarea or editable div has ability to insert emoji. 让文本框或div具备插入表情功能。
HTML
131
star
5

HostsDock

🎉 Store, manage and switch your hosts quickly.
JavaScript
99
star
6

Mocker

💎 HTTP/HTTPS mock tool, based on proxy server.
HTML
77
star
7

node-proxy

High performance HTTP and reverse proxy server based on Node.js. 基于 Node.js 的高性能 HTTP 及反向代理服务器,类似nginx。
JavaScript
75
star
8

saker

The template engine for Node.js and browsers.
JavaScript
46
star
9

chrome-extension-mocker

The most convenient tool to mock requests for axios, with built-in Chrome extension support.
Vue
42
star
10

pm2-server-monitor

The monitor for pm2 node.js servers, with nice web UI.
CSS
37
star
11

iBlog.Net

美观大方、功能全面的个人博客系统。
JavaScript
33
star
12

vue-card-swipe

A touch slider for vue.js, support sliding in any direction to switch cards, compatible with PC and mobile.
Vue
31
star
13

lajax4wx

前端日志解决方案 for微信小程序
JavaScript
28
star
14

filter-bar

适用于移动端列表页面的筛选条插件。
JavaScript
14
star
15

chrome-extension-server-log

在 Chrome F12 中查看服务器端的日志。
JavaScript
11
star
16

node-api

Node.js 中文 API 文档。
4
star
17

jQuery-cycleText

Cycle display text.循环交替显示文本。
HTML
4
star
18

node-static-server

基于Node.js的静态资源服务器,支持浏览器缓存,支持多文件合并请求。
JavaScript
3
star
19

jQuery-inputTip

Add tips in input text. 在input文本框中加入提示文字。
JavaScript
2
star
20

pwa-demo

pwa在线示例,请使用安卓手机最新版Chrome浏览器查看。
HTML
2
star
21

fine.js

A fine, tiny and practical JavaScript utility library. 一个精致、小巧、实用的javascript工具库。
JavaScript
2
star
22

iBlog2Nuxt

临时仓库,iBlog2重构版,基于Nuxt.js,重构完成后将合并至iBlog2仓库。
Vue
2
star
23

jQuery-inputClear

Add clear button into input text.在input文本框中加入清除按钮。
HTML
2
star
24

return-action

Let web page supports return action like native app.
HTML
1
star