首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >快速日志记录颜色格式

快速日志记录颜色格式
EN

Stack Overflow用户
提问于 2016-03-19 06:13:03
回答 1查看 898关注 0票数 1

新手来了。

在express 3.2.6中,我注意到当您将日志设置为app.use(express.logger('dev'))时,stdout中的日志格式是灰色的,看起来很方便(暗模式?),如下所示:

但是,当使用EXPRESS4.0并使用摩根进行日志记录时,在app.js中使用以下内容

代码语言:javascript
复制
var morgan = require('morgan');
app.use(morgan('dev'));

登录终端如下所示

无论如何,使用express 4.0和morgan来获取日志的“暗模式”主题?或者这只在express 3.0中可用?

看起来可以对其进行修改以实现此目的?https://github.com/expressjs/morgan/blob/master/index.js#L183

EN

回答 1

Stack Overflow用户

发布于 2016-03-19 08:06:00

你可以通过创建一个自定义的记录器来定制记录器的颜色

代码语言:javascript
复制
//logger.js
require('colors');
var _ = require('lodash');
var config = require('../config/config');

// create a noop (no operation) function for when loggin is disabled
var noop = function () {
};
// check if loggin is enabled in the config
// if it is, then use console.log
// if not then noop
var consoleLog = config.logging ? console.log.bind(console) : noop;

var logger = {
  log: function () {
    var tag = '[ ✨ LOG ✨ ]'.green;
    // arguments is an array like object with all the passed
    // in arguments to this function
    var args = _.toArray(arguments)
        .map(function (arg) {
          if (typeof arg === 'object') {
            // turn the object to a string so we
            // can log all the properties and color it
            var string = JSON.stringify(arg, null, 2);
            return tag + '  ' + string.cyan;
          } else {
            return tag + '  ' + arg.cyan;
          }
        });

    // call either console.log or noop here
    // with the console object as the context
    // and the new colored args :)
    consoleLog.apply(console, args);
  },

  error: function () {
    var args = _.toArray(arguments)
        .map(function (arg) {
          arg = arg.stack || arg;
          var name = arg.name || '[ ❌ ERROR ❌ ]';
          var log = name.yellow + '  ' + arg.red;
          return log;
        });

    consoleLog.apply(console, args);
  }
};

module.exports = logger;

用法

代码语言:javascript
复制
//controller
var logger = require('./relative/path/to/logger');
logger.log('some thing');
logger.error('some thing');
// you may use custom colors and create custom functions like warning() etc

希望它能有所帮助;)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36095090

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档