How to use the log4js.connectLogger function in log4js

To help you get started, we’ve selected a few log4js 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 log4js-node / log4js-node / examples / example-connect-logger.js View on Github external
// define logger
const logger = log4js.getLogger('log4jslog');

// set at which time msg is logged print like: only on error & above
// logger.setLevel('ERROR');

// express app
app.use(express.favicon(''));
// app.use(log4js.connectLogger(logger, { level: log4js.levels.INFO }));
// app.use(log4js.connectLogger(logger, { level: 'auto', format: ':method :url :status' }));

// ### AUTO LEVEL DETECTION
// http responses 3xx, level = WARN
// http responses 4xx & 5xx, level = ERROR
// else.level = INFO
app.use(log4js.connectLogger(logger, { level: 'auto' }));

// route
app.get('/', (req, res) => {
  res.send('hello world');
});

// start app
app.listen(5000);

console.log('server runing at localhost:5000');
console.log('Simulation of normal response: goto localhost:5000');
console.log('Simulation of error response: goto localhost:5000/xxx');
github litixsoft / baboon / lib / config / express.js View on Github external
// Disable caching of scripts for easier testing
        app.use(function noCache(req, res, next) {

            if (req.url.indexOf('/app/') === 0 || req.url.indexOf('/common/') === 0 ||
                req.url.indexOf('/api/') === 0 || req.url.indexOf('/assets/') === 0) {

                res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
                res.header('Pragma', 'no-cache');
                res.header('Expires', 0);
            }
            next();
        });

        // Logger in development mode
        app.use(log4js.connectLogger(loggers.express, {level: 'auto', format: ':status :method :url'}));

        // Static path for files and partial views
        app.use(express.static(path.join(rootPath, '.tmp')));
        app.use(express.static(path.join(rootPath, 'client')));

        // Path for application views
        app.set('views', rootPath + '/.tmp/views');
    }
    else if (app.get('env') === 'production') {

        // Enable compress
        app.use(compress());

        // Disable caching for rest api
        app.use(function noCache(req, res, next) {
github litixsoft / baboon / lib / config / express.js View on Github external
// Enable compress
        app.use(compress());

        // Disable caching for rest api
        app.use(function noCache(req, res, next) {

            if (req.url.indexOf('/api/') === 0) {
                res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
                res.header('Pragma', 'no-cache');
                res.header('Expires', 0);
            }
            next();
        });

        // Logger in production mode
        app.use(log4js.connectLogger(loggers.express, {level: 'auto'}));

        // Path for favicon with cache
        //app.use(express.favicon(path.join(rootPath, '.dist', 'public', 'favicon.ico'), {maxAge:oneMonth}));

        // Static path for files with cache
        app.use(express.static(path.join(rootPath, '.dist', 'public'), {maxAge: oneMonth}));

        // Static path for partial views without cache
        app.use(express.static(path.join(rootPath, '.dist', 'views', 'partials')));

        // Path for application views
        app.set('views', rootPath + '/.dist/views');
    }

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded());
github jay0815 / react_from_zero / server.js View on Github external
result: { type: 'dateFile', filename: 'logs/normal.log',layout: {type: 'basic'},'pattern':'.yyyy-MM-dd.log', alwaysIncludePattern:true},
        default: { type: 'dateFile', filename: 'logs/default.log', layout: {type: 'basic'},'pattern':'yyyy-MM-dd.log',alwaysIncludePattern:true},
    },
    categories: {
        default: {
            appenders: ['out', 'default'], level: 'info'
        },
        result: {
            appenders: ['result'], level: 'info'
        },
    }
});

const normalLog = log4js.getLogger('normal');

app.use(log4js.connectLogger(normalLog, {level: 'trace', format: ':method :url'}));

let env = process.env.NODE_ENV;

const isProduction = env === 'production';

const isDeveloping = !isProduction;

app.use(cookieParser());

//通过localhost可以访问项目文件夹下的所有文件,等于动态为每个静态文件创建了路由
app.use(express.static(path.join(__dirname, '/dist')));

// const publicPath = path.join(__dirname + '/dist');
// 加入gzip解析 .gz后缀文件
// if ( isProduction ) {
//   const expressStaticGzip = require('express-static-gzip')
github eclipse / orion.client / modules / orionode / server.js View on Github external
// create web server
	var app = express();
	if (configParams.get("orion.https.key") && configParams.get("orion.https.cert")) {
		server = https.createServer({
			secureOptions: constants.SSL_OP_NO_TLSv1,
			key: fs.readFileSync(configParams.get("orion.https.key")),
			cert: fs.readFileSync(configParams.get("orion.https.cert"))
		}, app);
	} else {
		server = http.createServer(app);
	}

	// Configure middleware
	if (log) {
		var requestLogger = log4js.getLogger('request');
		app.use(log4js.connectLogger(requestLogger, {
			format: ':method :url :status - :response-time ms'
		}));
	}
	if (password || configParams.get("pwd")) {
		app.use(listenContextPath ? contextPath : "/", auth(password || configParams.get("pwd")));
	}
	app.use(compression());
	var orion = require('./index.js')({
		workspaceDir: workspaceDir,
		configParams: configParams,
		maxAge: dev ? 0 : undefined,
		server: server
	});
	app.use(listenContextPath ? contextPath : "/", /* @callback */ function(req, res, next){
		req.contextPath = contextPath;
		next();
github DesignOpen / board / src / server.js View on Github external
}
));

var app = express();

// Set view engine to ejs
app.engine('html', require('ejs').renderFile);
// Find all node-side views inside frontend folder
app.set('views', config.serveDir);

if (process.env.NODE_ENV !== 'production') {
    // Pretty print JSON responses in development
    app.set('json spaces', 2);

    // Add request logging
    app.use(log4js.connectLogger(logger));

    // Disable caching for easier testing
    app.use(function noCache(req, res, next) {
        res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
        res.header('Pragma', 'no-cache');
        res.header('Expires', 0);
        next();
    });

    // Emulate latency in local development
    if (config.apiLatency !== null) {
        app.use(function(req, res, next) {
            if (req.path.indexOf('/api') !== -1) {
                setTimeout(next, config.apiLatency);
            } else {
                next();
github IBM / mern-app / server / server.js View on Github external
const appName = require('./../package').name;
const http = require('http');
const express = require('express');
const log4js = require('log4js');
const localConfig = require('./config/local.json');
const path = require('path');

const logger = log4js.getLogger(appName);
logger.level = process.env.LOG_LEVEL || 'info'
const app = express();
const server = http.createServer(app);

app.use(log4js.connectLogger(logger, { level: logger.level }));
const serviceManager = require('./services/service-manager');
require('./services/index')(app);
require('./routers/index')(app, server);

// Add your code here

const port = process.env.PORT || localConfig.port;
server.listen(port, function(){
  logger.info(`mernexample listening on http://localhost:${port}`);
});

app.use(function (req, res, next) {
  res.sendFile(path.join(__dirname, '../public', '404.html'));
});

app.use(function (err, req, res, next) {
github bs32g1038 / node-blog / server / main.ts View on Github external
export async function bootstrap() {
    const app = await NestFactory.create(AppModule, { logger: false });
    app.use(helmet());
    app.use(json({ limit: '20mb' }));
    app.useStaticAssets(staticAssetsPath, { prefix: '/static/' });
    app.use(log4js.connectLogger(requestInfoLogger, { level: 'info' }));
    app.useGlobalFilters(new AllExceptionsFilter());
    return await app.listen(APP_SERVER.port);
}
github shadowsocks / shadowsocks-manager / server / app.js View on Github external
mongoose.Promise = require('q').Promise;
var mongoAuth = {};
if(config.db.user) {mongoAuth.user = config.db.user;}
if(config.db.pass) {mongoAuth.pass = config.db.pass;}
mongoose.connect('mongodb://' + config.db.host + ':' + config.db.port + '/' + config.db.name, mongoAuth);
var moment = require('moment-timezone');
moment().tz('Asia/Shanghai').format();

var fs = require('fs');
var http = require('http');
var https = require('https');

var log4js = require('log4js');
var logger = log4js.getLogger('server');
var loggerExpress = log4js.getLogger('express');
app.use(log4js.connectLogger(loggerExpress, 
    '[:remote-addr][:method][:url][:status][:response-time ms]'
));

logger.info('当前程序版本:' + version);

var log4js = exports.log4js = function(cb) {
    var log4js = require('log4js');
    log4js.configure({
        appenders: [{
            type: 'console',
            category: 'server'
        }, {
            type: 'dateFile',
            filename: 'logs/server.log',
            pattern: '-yyyy-MM-dd',
            alwaysIncludePattern: true,