# log middleware

# Install and use

The log middleware is an independent middleware and needs to be installed and used separately

npm i sener-log
import { Log } from 'sener-log';
new Log();

# Basic usage

The log middleware is used for server-side log printing, saving the file as a .log file.

The following is the basic usage of reporting a log

import { Sener, Router } from 'sener';
import { Log } from 'sener-log';

const router = new Router({
     '/demo': ({ logger }) => {
         logger.log('test log', {age: 18}, 'info');
         return { data: {success: true} };
     },
});

new Sener({
   middlewares: [router, new Log()],
});

In addition to using logger context, you can also use middleware to call logger

const log = new Log();

log.logger.log('test log', {age: 18}, 'info');
// log.logger is equivalent to SenerContext.logger;

The following is a basic log content

[2023-03-07 01:46:09:313] type=log; msg=$$$message; payload={}; traceid=f8f9fa20-d192-405a-818e-0fc3653be13d; logid=93955e89-9e7d-40bb- b853-f653b2b892c3; duration=3; ua=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36; host=localhost:3001; timestamp=1678 124769313;

Features:

  1. Support reporting of public information and reporting of information on a custom basis
  2. Support configuration save directory
  3. Support the configuration of the maximum number of records in a single file, if the maximum number of records is exceeded, a new log file will be saved
  4. Support configuration log level, print logs on demand
  5. Support to correlate all server-side internal requests accessed during a client request through traceid.
  6. Write log files in batches to save performance overhead to the greatest extent. Active logging is also supported.
  7. Support recording the time consumption of each log from the start of the request

# Construction parameters

The log middleware has the following construction parameters

interface ILoggerOptions {
     dir?: string; // The storage directory of the log file is 'log' by default, which is {Sener.Dir}/log
     useConsole?: boolean; // Whether to write logs is to use console.log to print logs, the default is false, generally used for dev
     maxRecords?: number; // The maximum number of logs for a single file, the default value is 10000
     level?: (()=>number)|number; // Configure the log level. You can use a constant or configure a function to get it dynamically. The default value is -1, that is, all logs will be written to the file. After configuring the constant, it can also be dynamically modified through the API.
     interval?: number; // Set the cycle time for checking and saving logs, the unit is ms, the default is 5000
}
  1. About level: each log has a level, the default value is 5, when the log level value is greater than or equal to the configured level, the log will be written into the log file
  2. About the log storage mechanism: logger will check the log queue regularly, interval is to set this regular check period, if there are logs that need to be saved, they will be written in batches at one time, which has achieved performance savings. You can also actively force the save through the save method.

# Full log information

A complete log basic information is as follows:

interface ILogDBData {
   traceid: string; // The id corresponding to a request on the server side
   host: string; // client host
   url: string; // client url
   ua: string; // client ua

   msg: string; // log message
   payload: any; // data
   type: TLogType; // log type
   level: number; // log level

   duration: number; // The time from the start of the request when printing, in ms
   time: string; // formatted time when printing formatted to ms
   timestamp: number; // Timestamp when printing
   logid: string; // unique representation of a single log
}

# API

# log

The api for writing logs is declared as follows

type TLogType = 'error' | 'log' | 'warn' | 'info';

interface IMessageData {
     msg?: string; //
     payload?: any;
     type?: TLogType;
     level?: number;
}
function log(msg: string | IMessageData, payload?: any, type?: TLogType): void;

use string

logger. log('xxx');
logger.log('xxx', {age: 18}, 'error');

use object

logger. log({
     msg: 'xxx',
     payload: {age: 18},
     level: 5, // level default value is 5
});

###setLogLevel

Dynamically set the log level

logger.setLogLevel(10);

###save

The save method is used to actively force the log to be saved

logger. save();

# traceid

The traceid will be obtained or generated when the request reaches the server, and then written to baseInfo. When headers['x-trace-id'] is not empty, a traceid will be generated.

The logs generated by all subsequent internal requests in the server will have the same traceid. When the response is sent to the client, the traceid will be sent to the client as headers['x-trace-id'], which can be passed to the client The obtained header traceid queries all server logs generated by a request

An example of getting traceid is as follows

logger. traceid();

# setBaseInfo

The setBaseInfo method is used to set the public basic information of the log, which is declared as follows

interface IBaseInfo {
     traceid?: string; // request traceid
     host?: string; // client host
     url?: string; // client access url
     ua?: string; // client ua
}
function setBaseInfo (data: Partial<IBaseInfo> & IJson): void;

Use as follows:

logger.setBaseInfo({appName: 'xxx'});

###newLogFile

newLogFile is used to actively generate a new log file to write the log

logger. newLogFile();

###count

The count method is used to get how many logs are currently in the log file in use

const n = logger. count();

# refreshDurationStart

refreshDurationStart is used to refresh the start time of log calculation time consumption.

logger. refreshDurationStart();

# refreshTraceId

refreshTraceId is used to regenerate traceid

logger. refreshTraceId();
Document update time: 5/26/2023, 8:01:12 AM