How to use the express-winston.logger function in express-winston

To help you get started, we’ve selected a few express-winston examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github gmcdowell / bookshelf-demo / src / server.js View on Github external
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`],
github Colored-Coins / coloredcoinsd / server.js View on Github external
}
    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()
  })
github yunlzhang / lcddjmwebsite / index.js View on Github external
// 	},
// 	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({
github sourcegraph / sourcegraph / lsif / src / server.ts View on Github external
.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
github funsocietyirc / MrNodeBot / web / server.js View on Github external
);

    // 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');
github bertofer / MeanCourse / Examples / example_22_front_and_back / server.js View on Github external
var http = require('http');
var config = require('./config');
var express_jwt = require('express-jwt');
var cors = require('cors');

var app = express();
//mongoose
require('./models/index').initialize();
var mongoose = require('mongoose');
mongoose.connect(config.db_path);
//This middleware allow us to treat the body of the request as a json object.
app.use(bodyParser.json());
app.use(cors());

//Middleware for log every request to the system.
app.use(expressWinston.logger(config.winston_options));

var userRouter = require('./routes/user');

app.use('/user' ,userRouter);

var authenticationRouter = require('./routes/authentication');
app.use('/authentication', authenticationRouter);

http.createServer(app).listen(8081, function(){
  console.log('Listening on port 8080');
});
github argoproj / argo-ui / src / api / app.ts View on Github external
uiBaseHref: string,
        inCluster: boolean,
        namespace: string,
        forceNamespaceIsolation: boolean,
        instanceId: string,
        version,
        group = 'argoproj.io') {
    const config = Object.assign(
        {}, inCluster ? Api.config.getInCluster() : Api.config.fromKubeconfig(), {namespace, promises: true });
    const core = new Api.Core(config);
    const crd = new Api.CustomResourceDefinitions(Object.assign(config, {version, group}));
    crd.addResource('workflows');
    const app = express();
    app.use(bodyParser.json({type: () => true}));

    app.use(expressWinston.logger({
        transports: [winstonTransport],
        meta: false,
        msg: '{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}',
    }));

    function getWorkflowLabelSelector(req) {
        const labelSelector: string[] = [];
        if (instanceId) {
            labelSelector.push(`workflows.argoproj.io/controller-instanceid = ${instanceId}`);
        }
        if (req.query.phase) {
            const phases = req.query.phase instanceof Array ? req.query.phase : [req.query.phase];
            if (phases.length > 0) {
                labelSelector.push(`workflows.argoproj.io/phase in (${phases.join(',')})`);
            }
        }
github DataDog / trace-examples / javascript / node / microservices / api-gateway / src / app.js View on Github external
'use strict'

const axios = require('axios')
const cors = require('cors')
const express = require('express')
const expressWinston = require('express-winston')
const logger = require('./logger')

const app = express()

app.use(cors())
app.use(expressWinston.logger({
  winstonInstance: logger
}))

app.get('/users', (req, res) => {
  axios.get('http://auth:8080/.well-known/jwks.json')
    .then(() => {
      return axios.post('http://user:8080/graphql', {
        query: `{ users { name age } }`
      }, {
        headers: { 'Content-Type': 'application/json' }
      })
    })
    .then(response => {
      res.status(200).send(response.data.data)
    })
    .catch(() => {
github pixeloven / pixeloven / apps / examples / react-ssr-example / src / server / server.ts View on Github external
async function server(app: Application, config: Config) {
    /**
     * Setup express logger
     */
    app.use(
        expressWinston.logger({
            transports: [new winston.transports.Console()],
        }),
    );

    /**
     * Define render middleware
     * @todo Apply only for Production
     */
    if (config.environment.node === "production") {
        app.use(
            assetPath(
                config.publicPath,
                path.resolve(__dirname, "public/asset-manifest.json"),
            ),
        );
    }

express-winston

express.js middleware for winstonjs/winston

MIT
Latest version published 3 years ago

Package Health Score

59 / 100
Full package analysis