node.js+express实现日志功能

一.插件相关内容

node.js中实现日志用到的插件log4.js

  • 安装插件
 //save是为了把它记录在package.json中
  npm install log4js --save  

有关log4js及level的等级 详细内容

//等级依次提升
* 设置level :info  那么 trance和debug日志信息不能写入日志文件,只能写入info及之后等级的日志信息
const logger = log4js.getLogger("cheese");
logger.trace("Entering cheese testing");
logger.debug("Got cheese.");
logger.info("Cheese is Comté.");
logger.warn("Cheese is quite smelly.");
logger.error("Cheese is too ripe!");
logger.fatal("Cheese was breeding ground for listeria.");

二.相关代码

1. 在express项目目录下创建一个logs的文件夹

  • 在文件下创建文件log.js (配置相关信息)
  • 并创建一个存放日志的文件夹log然后创建一个存放日志的文件,这我用的error.log

相关的配置内容

//引入插件log4js  
var log4js =require('log4js')
 //输出json格式的内容
log4js.addLayout('json',function(config){
    return function(logEvent){
        return JSON.stringify(logEvent)+config.separator
    }
});
log4js.configure({
    appenders:{
        out :{
            type:'file',
            filename: "logs/log/error.log",
            layout:{type:'json',separator:','}
        }
    },
    categories:{
        default:{appenders:['out'],level:'info'}
    }
})
var logger=log4js.getLogger('json-test')
exports.logger=logger;
exports.use = function (app) {
        app.use(log4js.connectLogger(logger, { level: 'info', format: ':method:url' }))
  }

2.##在app.js中引入log

app引入.png

3.在error.log文件中的内容

{"startTime":"2020-07-09T02:32:46.392Z","categoryName":"json-test","data":["POST/api/getAll"],"level":{"level":20000,"levelStr":"INFO","colour":"green"},"context":{},"pid":1612},
{"startTime":"2020-07-09T02:32:46.394Z","categoryName":"json-test","data":["POST/api/getAll"],"level":{"level":20000,"levelStr":"INFO","colour":"green"},"context":{},"pid":1612},
{"startTime":"2020-07-09T02:41:35.015Z","categoryName":"json-test","data":["OPTIONS/login"],"level":{"level":20000,"levelStr":"INFO","colour":"green"},"context":{},"pid":10988},
{"startTime":"2020-07-09T02:41:35.036Z","categoryName":"json-test","data":["POST/login"],"level":{"level":20000,"levelStr":"INFO","colour":"green"},"context":{},"pid":10988},

完整代码
Github

你可能感兴趣的:(node.js+express实现日志功能)