Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const colorize = process.env.NODE_ENV !== 'production';
// Logger to capture all requests and output them to the console.
const requestLogger = expressWinston.logger({
transports: [
new winston.transports.Console({
json: false,
colorize: colorize,
}),
],
expressFormat: true,
meta: true,
});
// Logger to capture any top-level errors and output json diagnostic info.
const errorLogger = expressWinston.errorLogger({
transports: [
new winston.transports.Console({
json: true,
colorize: colorize,
}),
],
});
export default {
requestLogger,
errorLogger,
error: winston.error,
warn: winston.warn,
info: winston.info,
log: winston.log,
verbose: winston.verbose,
});
// 开发环境中发送错误堆栈到前端并打印到控制台
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err,
});
console.error(err);
});
}
// 生产环境中保留错误日志
app.use(expressWinston.errorLogger({
transports: [
new winston.transports.Console({
json: true,
colorize: true,
}),
new winston.transports.File({
filename: 'logs/error.log',
}),
],
}));
// 错误时发送邮件提醒
app.use(function(err, req, res, next) {
sendErrMailFn(err);
next(err);
});
app.use(cookieParser());
app.use(compress());
app.use(methodOverride());
app.use(passport.initialize());
app.use(passport.session());
// disable 'X-Powered-By' header in response
app.disable('x-powered-by');
// enable CORS - Cross Origin Resource Sharing
app.use(cors());
// enable detailed API logging in dev env
if (config.env === 'development') {
expressWinston.requestWhitelist.push('body');
expressWinston.responseWhitelist.push('body');
app.use(expressWinston.logger({
winstonInstance,
meta: true, // optional: log meta data about request (defaults to true)
msg: 'HTTP {{req.method}} {{req.url}} {{res.statusCode}} {{res.responseTime}}ms',
colorStatus: true // Color the status code (default green, 3XX cyan, 4XX yellow, 5XX red).
}));
}
if (config.staticPath) {
/* eslint-disable no-console */
console.log('Serve static files from: \x1b[36m' + config.staticPath + '\x1b[0m');
/* eslint-enable no-console */
app.use(express.static(config.staticPath));
}
app.use(compress());
app.use(methodOverride());
app.use(passport.initialize());
app.use(passport.session());
// disable 'X-Powered-By' header in response
app.disable('x-powered-by');
// enable CORS - Cross Origin Resource Sharing
app.use(cors());
// enable detailed API logging in dev env
if (config.env === 'development') {
expressWinston.requestWhitelist.push('body');
expressWinston.responseWhitelist.push('body');
app.use(expressWinston.logger({
winstonInstance,
meta: true, // optional: log meta data about request (defaults to true)
msg: 'HTTP {{req.method}} {{req.url}} {{res.statusCode}} {{res.responseTime}}ms',
colorStatus: true // Color the status code (default green, 3XX cyan, 4XX yellow, 5XX red).
}));
}
if (config.staticPath) {
/* eslint-disable no-console */
console.log('Serve static files from: \x1b[36m' + config.staticPath + '\x1b[0m');
/* eslint-enable no-console */
app.use(express.static(config.staticPath));
}
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(compress());
app.use(methodOverride());
// secure apps by setting various HTTP headers
app.use(helmet());
// enable CORS - Cross Origin Resource Sharing
app.use(cors());
// enable detailed API logging in dev env
if (config.env === 'development') {
expressWinston.requestWhitelist.push('body');
expressWinston.responseWhitelist.push('body');
// app.use(expressWinston.logger({
// winstonInstance,
// meta: true, // optional: log meta data about request (defaults to true)
// msg: 'HTTP {{req.method}} {{req.url}} {{res.statusCode}} {{res.responseTime}}ms',
// colorStatus: true // Color the status code (default green, 3XX cyan, 4XX yellow, 5XX red).
// }));
}
app.use(express.static(path.join(appRoot.path, 'dist')));
app.use('/api', routes);
innograph.init('/api/graphql', app, {post: postCtrl});
app.get('*', (req, res) => {
res.sendFile(path.join(appRoot.path, 'dist/index.html'));
});
import expressWintston from 'express-winston';
//import Routes from './routes/index';
const app = express();
// Allow CORS
// https://www.npmjs.com/package/cors
app.use(cors()); // simple allow all config
app.options('*', cors()); // enables pre-flight requests e.g. DELETE, PATCH
app.use(bodyParser.urlencoded({extended: false})); // pull information from html in POST
app.use(bodyParser.json()); // support Json parsing
//app.use(passport.initialize()); // enable passport authentication
// Setup Winston http request logging
app.use(expressWintston.logger({winstonInstance: winston}));
/**
* OAuth2 Authorization
*
* - /login -> uses LDAP auth call to MacVad
*/
//app.use(['/oauth/token', '/oauth/login'], OAuth2.Token);
//app.use('/oauth/refresh', OAuth2.Refresh);
/**
* Route API v1
*/
// Routes
/*app.use([`${Config.get('API.URL_PREFIX')}/continents`],
}
next()
})
app.use(clsify(session))
app.use(function (req, res, next) {
session.set('context', {req: req, res: res})
next()
})
if (config.secret) {
app.use(requestId({secret: config.secret, namespace: config.serverName}))
}
// Adds optional express logging to winston logger
expressWinston.requestWhitelist = _.concat(expressWinston.requestWhitelist, ['body', 'log_ip', 'log_url'])
app.use(expressWinston.logger({
winstonInstance: logger({logentries_api_key: process.env.LETOKEN}),
meta: true,
colorStatus: true
}))
app.use(function (req, res, next) {
var ip = req.headers['x-forwarded-for'] || (req.connection && req.connection.remoteAddress)
ip = ip || (req.socket && req.socket.remoteAddress) || (req.connection && req.connection.socket && req.connection.socket.remoteAddress)
var parsed_url = url.parse(req.url) || {}
var log_url = (parsed_url.pathname && parsed_url.pathname.toLowerCase()) || ''
log_url = log_url.substring(0, getNthOccurrenceIndex(log_url, '/', 3))
// for log-entries to parse Key-Value-Pairs ("/" in value is causing problems)
req.log_ip = "'" + ip + "'"
req.log_url = "'" + log_url + "'"
next()
})
// },
// store: new MongoStore({ // 将 session 存储到 mongodb
// url: config.mongodb // mongodb 地址
// })
// }));
// // 处理表单及文件上传的中间件
// app.use(require('express-formidable')({
// uploadDir: path.join(__dirname, 'public/img'),// 上传文件目录
// keepExtensions: true// 保留后缀
// }));
// 正常请求的日志
app.use(expressWinston.logger({
transports: [
new winston.transports.Console({
json: true,
colorize: true
}),
new winston.transports.DailyRotateFile({
dirname:__dirname + '/server/logs/',
filename: 'success.%DATE%.log',
datePattern: 'YYYY-MM-DD-HH'
})
]
}));
// 错误请求的日志
app.use(expressWinston.errorLogger({
transports: [
new winston.transports.Console({
.catch(() => {}),
1000
)
// Register the required commands on the queue's Redis client
const scriptedClient = await defineRedisCommands(queue.client)
const app = express()
app.use(cors())
if (tracer !== undefined) {
app.use(tracingMiddleware({ tracer }))
}
app.use(
loggingMiddleware({
winstonInstance: logger,
level: 'debug',
ignoredRoutes: ['/ping', '/healthz', '/metrics'],
requestWhitelist: ['method', 'url', 'query'],
msg: 'request',
})
)
app.use(metricsMiddleware)
// Register endpoints
app.use(metaEndpoints())
app.use(lsifEndpoints(backend, queue, logger, tracer))
app.use(dumpEndpoints(backend, logger, tracer))
app.use(jobEndpoints(queue, scriptedClient, logger, tracer))
// Error handler must be registered last
);
// If we are in web debug mode, push the Logging to the console
if (app.Config.bot.webDebug === true) {
transports.push(new (winston.transports.Console)({
name: 'express-console',
timestamp: true,
colorize: true,
prettyPrint: true,
depth: 4,
level: app.Config.bot.webDebugLevel || 'info',
}));
}
// Attach the Logger to the express Instance
webServer.use(expressWinston.logger({
exitOnError: false,
transports,
meta: true, // optional: control whether you want to log the meta data about the request (default to true)
msg: app.Config.express.forwarded ? 'HTTP {{req.method}} {{req.url}} {{req.headers[\'x-forwarded-for\'] || req.connection.remoteAddress}}' : 'HTTP {{req.method}} {{req.url}} {{req.connection.remoteAddress}}',
expressFormat: false, // Use the default Express/morgan request formatting. Enabling this will override any msg if true. Will only output colors with colorize set to true
colorize: true, // Color the text and status code, using the Express/morgan color palette (text: gray, status: default green, 3XX cyan, 4XX yellow, 5XX red).
// optional: allows to skip some log messages based on request and/or response
ignoreRoute(req, res) {
return false;
},
}));
// Prevent the web server from being indexed by spiders
if (app.Config.express.noFollow) {
webServer.use((req, res, next) => {
res.header('X-Robots-Tag', 'noindex, nofollow');