• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript morgan.token函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中morgan.token函数的典型用法代码示例。如果您正苦于以下问题:TypeScript token函数的具体用法?TypeScript token怎么用?TypeScript token使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了token函数的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: setupLogging

/**
 * Set up the logging middleware provided by morgan
 *
 * @param logfile
 * @param app
 */
function setupLogging({ logfile }, app) {
  // Set up morgan for logging, with optional logging into a file
  let middleware;
  if (logfile) {
    // create a write stream (in append mode)
    const accessLogPath = path.resolve(logfile);
    const accessLogStream = fs.createWriteStream(accessLogPath, { flags: 'a' });
    console.log('Log location: ' + accessLogPath);
    // setup the logger
    middleware = morgan('combined', { stream: accessLogStream });
  } else {
    middleware = morgan('combined');
  }

  app.use(middleware);
  morgan.token('remote-user', function(req) { return req.isProxy ? 'proxy' : 'local_express'; });
}
开发者ID:BitGo,项目名称:BitGoJS,代码行数:23,代码来源:expressApp.ts


示例2: function

/**
 * Configure logger
 * @param  {string} logfile Path to logfile
 * @param  {object} config Configuration for transports
 * @return {winston.Logger}
 */
export default function(app: Application, options: ILoggingOptions) {
  const cwd = process.cwd();
  const logFile = path.resolve(cwd, `${options.dir}/${options.file}`);
  const addRequestId = require("express-request-id")({ setHeader: false });

  app.use(addRequestId);
  morgan.token("id", (req: IRequestWithId) => req.id.split("-")[0]);

  app.use(morgan("[:date[iso] #:id] Started :method :url for :remote-addr", {immediate: true}));

  app.use(morgan("[: date[iso] #: id] Completed : status : res[content - length] in : response - time ms"));

  // If logs directory does not exist, create one
  if (!fs.existsSync(path.resolve(cwd, options.dir))) {
    mkdirp.sync(path.resolve(cwd, options.dir));
  }

  // If log file does not exist, create one with empty content.
  if (!fs.existsSync(logFile)) {
    fs.writeFileSync(logFile, "");
  }

  const logger = winston.createLogger({
    exitOnError: false,
    format: winston.format.json(),
    level: "info",
    transports: [
      new winston.transports.File({
        filename: logFile,
        handleExceptions: true,
        level: "info",
        maxFiles: 5,
        maxsize: 5242880, // 5MB
      }),
      new winston.transports.Console({
        handleExceptions: true,
        level: "debug",
      }),
    ],

  });

  return logger;
}
开发者ID:charlesponti,项目名称:cthulhu,代码行数:50,代码来源:logger.ts


示例3: switch



morgan.token('colored-method',function(req,res){
  var method = req.method

  if(method){
    var color = 0
    switch( method.toLowerCase() ){
      case 'delete':
        color = 31 // red
        break;

      case 'options':
          color = 33 // yellow
          break;

      case 'post':
        color = 32 // green
        break;

      case 'pull':
        color = 36 // cyan
        break;
    }

    return '\x1b['+color+'m'+method+'\x1b[0m'
  }

  return method
})

morgan.token('browser-name',function(req,res){
开发者ID:AckerApple,项目名称:ack-node,代码行数:30,代码来源:router.ts


示例4: start

  /**
   * start
   *
   * @param opts.WalletService options for WalletService class
   * @param opts.basePath
   * @param opts.disableLogs
   * @param opts.doNotCheckV8
   * @param {Callback} cb
   */
  start(opts, cb) {
    opts = opts || {};

    this.app.use(compression());

    this.app.use((req, res, next) => {
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.setHeader(
        'Access-Control-Allow-Methods',
        'GET, POST, OPTIONS, PUT, DELETE'
      );
      res.setHeader(
        'Access-Control-Allow-Headers',
        'x-signature,x-identity,x-session,x-client-version,x-wallet-id,X-Requested-With,Content-Type,Authorization'
      );
      res.setHeader('x-service-version', WalletService.getServiceVersion());
      next();
    });
    const allowCORS = (req, res, next) => {
      if ('OPTIONS' == req.method) {
        res.sendStatus(200);
        res.end();
        return;
      }
      next();
    };
    this.app.use(allowCORS);
    this.app.enable('trust proxy');

    // handle `abort` https://nodejs.org/api/http.html#http_event_abort
    this.app.use((req, res, next) => {
      req.on('abort', () => {
        log.warn('Request aborted by the client');
      });
      next();
    });

    const POST_LIMIT = 1024 * 100 /* Max POST 100 kb */;

    this.app.use(
      bodyParser.json({
        limit: POST_LIMIT
      })
    );

    if (opts.disableLogs) {
      log.level = 'silent';
    } else {
      const morgan = require('morgan');
      morgan.token('walletId', function getId(req) {
        return req.walletId ? '<' + req.walletId + '>' : '<>';
      });

      const logFormat =
        ':walletId :remote-addr :date[iso] ":method :url" :status :res[content-length] :response-time ":user-agent"  ';
      const logOpts = {
        skip(req, res) {
          if (res.statusCode != 200) return false;
          return req.path.indexOf('/notifications/') >= 0;
        }
      };
      this.app.use(morgan(logFormat, logOpts));
    }

    const router = express.Router();

    const returnError = (err, res, req) => {
      if (err instanceof ClientError) {
        const status = err.code == 'NOT_AUTHORIZED' ? 401 : 400;
        if (!opts.disableLogs)
          log.info(
            'Client Err: ' + status + ' ' + req.url + ' ' + JSON.stringify(err)
          );

        res
          .status(status)
          .json({
            code: err.code,
            message: err.message
          })
          .end();
      } else {
        let code = 500,
          message;
        if (err && ((err.code && _.isNumber(err.code)) || (err.statusCode && _.isNumber(err.statusCode)))) {
          code = err.code || err.statusCode;
          message = err.message || err.body;
        }

        const m = message || err.toString();

//.........这里部分代码省略.........
开发者ID:matiu,项目名称:bitcore,代码行数:101,代码来源:expressapp.ts


示例5: baseMiddleware

/**
 * Denali ships with several base middleware included, each of which can be enabled/disabled
 * individually through config options.
 */
export default function baseMiddleware(router: Router, application: Application): void {

  let config = application.config;

  /**
   * Returns true if the given property either does not exist on the config object, or it does exist
   * and it's `enabled` property is not `false`. All the middleware here are opt out, so to disable
   * you must define set that middleware's root config property to `{ enabled: false }`
   */
  function isEnabled(prop: string): boolean {
    return !config[prop] || (config[prop] && config[prop].enabled !== false);
  }

  if (isEnabled('timing')) {
    router.use(timing());
  }

  if (isEnabled('logging')) {
    let defaultLoggingFormat = application.environment === 'production' ? 'combined' : 'dev';
    let defaultLoggingOptions = {
      // tslint:disable-next-line:completed-docs
      skip(): boolean {
        return application.environment === 'test';
      }
    };
    let format = (config.logging && config.logging.format) || defaultLoggingFormat;
    let options = defaults(config.logging || {}, defaultLoggingOptions);
    router.use(morgan(format, options));

    // Patch morgan to read from our non-express response
    morgan.token('res', (req: IncomingMessage, res: ServerResponse, field: string) => {
      let header = res.getHeader(field);
      return Array.isArray(header) ? header.join(', ') : header;
    });
  }

  if (isEnabled('compression')) {
    router.use(compression());
  }

  if (isEnabled('cookies')) {
    router.use(cookies(config.cookies));
  }

  if (isEnabled('cors')) {
    router.use(cors(config.cors));
  }

  if (isEnabled('xssFilter')) {
    router.use(helmet.xssFilter());
  }

  if (isEnabled('frameguard')) {
    router.use(helmet.frameguard());
  }

  if (isEnabled('hidePoweredBy')) {
    router.use(helmet.hidePoweredBy());
  }

  if (isEnabled('ieNoOpen')) {
    router.use(helmet.ieNoOpen());
  }

  if (isEnabled('noSniff')) {
    router.use(helmet.noSniff());
  }

  if (isEnabled('bodyParser')) {
    router.use(json({ type: config.bodyParser && config.bodyParser.type }));
  }

}
开发者ID:acburdine,项目名称:denali,代码行数:77,代码来源:middleware.ts


示例6: express

import { WickedError } from 'wicked-sdk';

import { kongMain } from './kong/main';
import * as utils from  './kong/utils';

const app = express();
app.initialized = false;
app.kongAvailable = false;
app.apiAvailable = false;

// Correlation ID
app.use(correlationIdHandler);

logger.token('correlation-id', function (req, res) {
    return req.correlationId;
});
app.use(logger('{"date":":date[iso]","method":":method","url":":url","remote-addr":":remote-addr","version":":http-version","status":":status","content-length":":res[content-length]","referrer":":referrer","response-time":":response-time","correlation-id":":correlation-id"}'));
// Make sure we get the body directly as JSON. Thanks.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/', function (req, res, next) {
    debug('/ (main processing loop)');
    if (!app.initialized)
        return res.status(503).json({ message: 'Not yet initialized.' });
    if (req.app.processingWebhooks) {
        error('Still processing last webhook load.');
        return res.send('OK');
    }
开发者ID:Haufe-Lexware,项目名称:wicked.portal-kong-adapter,代码行数:29,代码来源:app.ts



注:本文中的morgan.token函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript most.from函数代码示例发布时间:2022-05-25
下一篇:
TypeScript morgan.default函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap