本文整理汇总了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'; });
}
示例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;
}
示例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){
示例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();
//.........这里部分代码省略.........
示例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 }));
}
}
示例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');
}