How to use morgan - 10 common examples

To help you get started, we’ve selected a few morgan 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 marcells / node-build-monitor / app / app.js View on Github external
import express from 'express';
import http from 'http';
import path from 'path';
import socketio from 'socket.io';
import config from './config';
import favicon from 'serve-favicon';
import morgan from 'morgan';
import errorhandler from 'errorhandler';

let app = express();

app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon(path.join(__dirname, 'public/images/favicon.ico')));
app.use(morgan('combined'));
app.get('/', (req, res) => res.render('index', {
  title: 'Build Monitor'
}));
app.use(express.static(path.join(__dirname, 'public')));

if ('development' === app.get('env')) {
  app.use(errorhandler());
}

// run express
let server = http.createServer(app),
  io = socketio.listen(server);

server.listen(
  app.get('port'), () => console.log(`node-build-monitor is listening on port ${app.get('port')}`));
github freeCodeCamp / chapter / server / index.ts View on Github external
nextjs.nextApp.prepare().then(async () => {
  const port = process.env.PORT || 8000;

  const connection = await initDB;
  await connection.runMigrations();

  app.use(
    morgan(':method :url :status', {
      skip: (req: express.Request) => req.url.startsWith('/_next/'),
    }),
  );
  app.use(express.json());
  app.use(express.static('public'));

  app.use(apiV1);

  app.use(responseErrorHandler);

  app.get('*', (req, res) => {
    nextjs.handle(req, res);
  });

  app.listen(port, () => {
    console.log(`\n\nstarted on port ${port}\n\n`); // tslint:disable-line no-console
github IamMohaiminul / MERNjs / client / app.js View on Github external
import express from 'express';
import path from 'path';
import favicon from 'serve-favicon';
import logger from 'morgan';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// route handlers
app.get('*', function (req, res) {
  res.render('index', { title: 'MERN' });
});

export default app;
github revathskumar / react-server-render / src / app.js View on Github external
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';

import routes from './routes/index';
import users from './routes/users';

const app = express();

// view engine setup
app.set('views', path.join(__dirname, '..', 'views'));
app.set('view engine', 'pug');

app.locals.pretty = true;
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '..', 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers
github jhnns / spa-vs-universal / universal / server / index.js View on Github external
import config from "./config";
import api from "./api";
import { isDev } from "./env";

const app = express();
const pathToPublic = path.resolve(process.cwd(), "dist", "public");
const universalApp = require(path.resolve(process.cwd(), "dist", "app", "server")).default;
const expectedReferrers = ["http://" + config.hostname + ":" + config.port];

if (isDev) {
    expectedReferrers.push("http://" + config.hostname + ":" + config.devServerPort);
}

app.server = http.createServer(app);

app.use(morgan("dev"));
app.use(helmet());
// "same-origin" would be the best, but "origin-when-cross-origin" has the best cross-browser support
app.use(helmet.referrerPolicy({ policy: "origin-when-cross-origin" }));
app.use(
    bodyParser.json({
        limit: config.bodyLimit,
    })
);
app.use(
    bodyParser.urlencoded({
        limit: config.bodyLimit,
        extended: true,
    })
);
app.use(session(config.session));
api(app);
github GIScience / OSM-realtime-update / server / api.js View on Github external
accesslogger.setLevels(winston.config.syslog.levels);
    accesslogger.stream = {
        write: message => accesslogger.info("[API access]", message)
    };

    // set data directory for serving data
    api.dataDirectory = config.api.dataDirectory;

    // enable body parsing
    // parse application/x-www-form-urlencoded
    api.use(bodyParser.urlencoded({ extended: false }));
    // parse application/json
    api.use(bodyParser.json());

    // new token to log POST body
    morgan.token('body', function (req) {return "body: " + JSON.stringify(req.body);});
    api.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method ' +
        ':url :body HTTP/:http-version" :status :res[content-length] :response-time ms ' +
        '":referrer" ":user-agent" ', {stream: accesslogger.stream}));

    // configure listening port
    api.listen(config.api.port, function () {
        log.notice(`Real-time OSM API server running on port ${config.api.port}.`);
    });

    // initialise data storage
    api.db = new sequelize(config.api.database, null, null, {
        dialect: "sqlite",
        storage: config.api.database,
        logging: false,
        operatorsAliases: false
    });
github open-webrtc-toolkit / QoSTestFramework / mcu-bench_cpp / QOSserver / qosServer.js View on Github external
for (j = 1; j < array.length; j += 1) {
      if (array[j] === '') {
        val += '=';
      } else {
        val += array[j];
      }
    }

    params[array[0]] = val;

  }
  return params;
};

morgan.token('errormsg', function getErrorMsg(req) {
  return req.errormsg
})

var logDirectory = path.join(__dirname, 'logs')
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)
var accessLogStream = fs.createWriteStream(path.join(logDirectory, 'error.log'), {
  flags: 'a'
})

// setup the logger
app.use(morgan('combined', {
  stream: accessLogStream,
  skip: function(req, res) {
    return res.statusCode < 400
  }
}))
github microsoft / opensource-portal / middleware / logger.ts View on Github external
//
// Copyright (c) Microsoft.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

'use strict';

const logger = require('morgan');

const encryptionMetadataKey = '_ClientEncryptionMetadata2';
const piiFormat = ':id :method :scrubbedUrl :status :response-time ms - :res[content-length] :encryptedSession :correlationId';
const format = ':method :scrubbedUrl :status :response-time ms - :res[content-length] :encryptedSession :correlationId';

logger.token('encryptedSession', function getUserId(req) {
  const config = req.app.settings.runtimeConfig;
  if (req.session && req.session.passport && req.session.passport.user) {
    const userType = config.authentication.scheme === 'aad' ? 'azure' : 'github';
    return req.session.passport.user[userType] && req.session.passport.user[userType][encryptionMetadataKey] !== undefined ? 'encrypted' : 'plain';
  }
});

logger.token('id', function getUserId(req) {
  const config = req.app.settings.runtimeConfig;
  if (config) {
    const userType = config.authentication.scheme === 'aad' ? 'azure' : 'github';
    return req.user && req.user[userType] && req.user[userType].username ? req.user[userType].username : undefined;
  }
});

logger.token('correlationId', function getCorrelationId(req) {
github bitpay / bitcore / packages / bitcore-wallet-service / src / lib / expressapp.ts View on Github external
this.app.use((req, res, next) => {
      if (config.maintenanceOpts.maintenanceMode === true) {
        // send a 503 error, with a message to the bitpay status page
        let errorCode = 503;
        let errorMessage = 'BWS down for maintenance';
        res.status(503).send({ code: errorCode, message: errorMessage });
      } else {
        next();
      }
    });

    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();
github micro-tools / log4bro / src / ExpressMiddlewares.js View on Github external
const optKeys = [];

        // Check for additional access logs
        if (customTokens && typeof customTokens === "object") {
            for (const key in customTokens) {
                try {
                    morgan.token(key, typeof customTokens[key] === "function" ? customTokens[key] : errorHandler);
                }
                catch(err) {
                    morgan.token(key, errorHandler);
                }
                optKeys.push(`\"${key}\": \":${key}\"`);
            }
        }

        morgan.token("host_name", function getHostName(request, response) {
            return hostName;
        });

        morgan.token("service_name", function getHostName(request, response) {
            return serviceName;
        });

        morgan.token("uri", function getUri(request, response) {
            try {
                return request._parsedUrl.pathname;
            } catch (e) {
                return "error";
            }
        });

        morgan.token("query_string", function getQueryString(request) {

morgan

HTTP request logger middleware for node.js

MIT
Latest version published 5 years ago

Package Health Score

81 / 100
Full package analysis