How to use winstonLogger method in mountebank

Best JavaScript code snippet using mountebank

index.js

Source:index.js Github

copy

Full Screen

1/*=============================================2= Dependencies =3=============================================*/4const winston = require('winston');5require('winston-daily-rotate-file');6const bodyParser = require('body-parser');7const stringify = require('json-stringify-safe');8const express = require('express')9const app = express();10const fs = require('fs');11const serveIndex = require('serve-index');12// SplunkLogger13const SplunkLogger = require("./splunklogger");14const utils = require("./utils");15const basicAuth = require('express-basic-auth')16/*=============================================17= Environment Variable Configuration =18=============================================*/19const SERVICE_IP = process.env.SERVICE_IP || 'localhost';20const SERVICE_PORT = process.env.SERVICE_PORT || 8080;21const FILE_LOG_LEVEL = process.env.FILE_LOG_LEVEL || 'info';22const SPLUNK_URL = process.env.SPLUNK_URL || null;23const RETRY_COUNT = parseInt(process.env.RETRY_COUNT, 10) || 0;24const HOST_NAME = process.env.HOSTNAME || '?'25const SERVICE_AUTH_TOKEN = process.env.SERVICE_AUTH_TOKEN || 'NO_TOKEN';26const SPLUNK_AUTH_TOKEN = process.env.SPLUNK_AUTH_TOKEN || null;27const USE_SPLUNK = checkEnvBoolean(process.env.USE_SPLUNK);28const USE_AUTH = checkEnvBoolean(process.env.SERVICE_USE_AUTH);29const ONLY_LOG_WHEN_SPLUNK_FAILS = checkEnvBoolean(process.env.ONLY_LOG_WHEN_SPLUNK_FAILS);30const MONITOR_USERNAME = process.env.MONITOR_USERNAME || '';31const MONITOR_PASSWORD = process.env.MONITOR_PASSWORD || '';32//TODO: Verify empty string doesn't break requests. Value for Splunklogger has to be string, not null.33const CA_CERT = process.env.CA_CERT || '';34//Defaults to use 750mb total storage.35const MAX_FILES = parseInt(process.env.MAX_FILES, 10) || 10;36const MAX_BYTE_SIZE_PER_FILE = parseInt(process.env.MAX_BYTE_SIZE_PER_FILE, 10) || (1024 * 1024 * 75)37//Should not end with a /, "/var/logs" or "logs" is good.38const LOG_DIR_NAME = process.env.LOG_DIR_NAME || null;39const APPEND_POD_NAME_TO_FILE = (process.env.APPEND_POD_NAME_TO_FILE == 'true');40const FILE_LOG_NAME = LOG_DIR_NAME ?41 LOG_DIR_NAME + '/sf' + (APPEND_POD_NAME_TO_FILE ? '-' + HOST_NAME : '') + '.log'42 : './logs/sf' + (APPEND_POD_NAME_TO_FILE ? '-' + HOST_NAME : '') + '.log';43/*=============================================44= APPLICATION CONFIGURATION =45=============================================*/46// turn off self-cert check47process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";48// Daily rotate file transport for logs49var transport = new winston.transports.DailyRotateFile({50 filename: FILE_LOG_NAME,51 datePattern: 'yyyy-MM-dd-',52 prepend: true,53 level: FILE_LOG_LEVEL,54 timestamp: true,55 maxsize: MAX_BYTE_SIZE_PER_FILE,56 maxFiles: MAX_FILES,57});58// Winston Logger init59var winstonLogger = new winston.Logger({60 level: FILE_LOG_LEVEL,61 transports: [62 new winston.transports.Console({ timestamp: true }),63 transport64 ]65});66winstonLogger.error = function (err, context) {67 winstonLogger.error(`SplunkLogger error:` + err + ` context:` + context);68};69// remove console if not in debug mode70if (FILE_LOG_LEVEL != 'debug') {71 winston.remove(winston.transports.Console);72}73var splunkLogger = new SplunkLogger({74 token: SPLUNK_AUTH_TOKEN,75 cacert: CA_CERT,76 level: 'info',77 url: SPLUNK_URL,78 maxRetries: RETRY_COUNT,79});80splunkLogger.requestOptions.strictSSL = false;81/*=============================================82= Main Application =83=============================================*/84// Init app85if (process.env.NODE_ENV != 'production' ||86 process.env.CORS_ALLOW_ALL == 'true') {87 app.use(function (req, res, next) {88 res.header("Access-Control-Allow-Origin", "*");89 res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");90 next();91 });92}93app.use(bodyParser.json());94app.use(bodyParser.urlencoded({ extended: true }));95var args = process.argv;96if (args.length == 3 && args[2] == 'server') {97 var server = app.listen(SERVICE_PORT, SERVICE_IP, function() {98 var host = server.address().address;99 var port = server.address().port;100 winstonLogger.info(`START log server (${HOST_NAME})- loglevel(${FILE_LOG_LEVEL}) fileLocation(${FILE_LOG_NAME})`)101 });102}103// handle posts to /log endpoint104app.post('/log', function (req, res) {105 getLog(req).then(function (mess) {106 res.status(200);107 return res.send(mess);108 }).catch(function(mess) {109 res.status(200);110 winstonLogger.error(mess);111 return res.send('An error has occured');112 });113});114//Setup the password protected /monitor115winstonLogger.debug('Serving index files from ' + LOG_DIR_NAME);116const users = {};117users[MONITOR_USERNAME] = MONITOR_PASSWORD;118app.get('/monitor', basicAuth({119 users,120 challenge: true, //Show popup box asking for credentials121}));122app.use('/monitor', serveIndex(LOG_DIR_NAME));123app.use('/monitor', express.static(LOG_DIR_NAME, {124 //Get browser to display instead of download weird filenames, *.log.1125 setHeaders: (res, path, stat) => {126 winstonLogger.debug('Getting monitored files for ' + LOG_DIR_NAME);127 res.set('content-type', 'text/plain; charset=UTF-8')128 }129}));130app.use(function (err, req, res, next) {131 winstonLogger.info(err, req);132 res.status(200).send('An error has occured.');133});134winstonLogger.info('Splunk Forwarder started on host: ' + SERVICE_IP + ' port: ' + SERVICE_PORT);135// get a log136var getLog = function (req) {137 return new Promise(function (resolve, reject) {138 var authorized = false;139 if (USE_AUTH && req.get('Authorization') === `Splunk ${SERVICE_AUTH_TOKEN}`) {140 authorized = true;141 };142 if (authorized || !USE_AUTH) {143 // extract stuff144 const mess = stringify(req.body);145 const host = req.get('host') || '?'146 const logsource = req.get('logsource') || '?'147 const fhost = req.get('http_x_forwarded_host') || '?'148 const refNo = req.get('referenceNumber') || '?'149 const applicationId = req.get('applicationId') || '?'150 const name = req.get('name') || '?'151 const tags = req.get('tags') || '?'152 const program = req.get('program') || '?'153 const times = req.get('timestamp') || '?'154 const http_host = req.get('http_host') || '?';155 const method = req.get('request_method') || '?';156 const forwarded = req.get('http_x_forwarded_for') || '?';157 const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || '?'158 const browser = req.headers['user-agent'];159 //todo: Verify! Screenshots showed severity_label.160 const severity = req.get('severity') || '?' //orig161 const severityLabel = req.get('severity_label') || '?' //from screenshot162 const logString = `applicationId(${applicationId}) program(${program}) mess(${mess}) host(${host}) logsource(${logsource}) fhost(${fhost}) refNo(${refNo}) name(${name}) severity(${severity}) tags(${tags}) method(${method}) times(${times}) browser(${browser}) sourceIP(${ip}), http_host(${http_host}) http_x_forwarded_for(${forwarded}) pod(${HOST_NAME})`;163 // write to local filesystem164 if (!ONLY_LOG_WHEN_SPLUNK_FAILS && USE_SPLUNK){165 winstonLogger.info(logString);166 }167 if (!USE_SPLUNK){168 winstonLogger.info(logString);169 return resolve('success');170 }171 else { // forward to splunk172 var payload = {173 message: {174 applicationId:applicationId,175 program: program,176 log: mess,177 times: times,178 refNo: refNo,179 name: name,180 severity: severity,181 tags: tags,182 http_host: http_host,183 method: method,184 host: host,185 pod: HOST_NAME,186 forwardedHost: fhost,187 forwarded: forwarded,188 browserType: browser,189 sourceIP: ip,190 logsource: logsource191 },192 // metadata: {193 // sourceIP: "TBD",194 // browserType: "TBD",195 // etc: "TBD"196 //},197 severity: "info"198 };199 winstonLogger.debug('sending payload');200 splunkLogger.send(payload, function (err, resp, body) {201 //TODO: Once sending to Splunk is setup, double check if err202 //is falsy on success or if we have to modify the check203 if (ONLY_LOG_WHEN_SPLUNK_FAILS && resp && resp.statusCode != 200){204 winstonLogger.info(logString);205 }206 winstonLogger.debug('ONLY_LOG_WHEN_SPLUNK_FAILS=' + ONLY_LOG_WHEN_SPLUNK_FAILS + ' resp=' + JSON.stringify(resp) + ' body=' + JSON.stringify(body) + ' Response from Splunk Server' + body);207 });208 winstonLogger.debug('sent payload');209 resolve('success');210 }211 }212 else {213 winstonLogger.info('unauthorized');214 winstonLogger.debug('received with headers: ', req.headers);215 reject('unauthorized');216 }217 }, function(err) {218 winstonLogger.info('error: ' + err);219 // reject('unauthorized');220 reject('something went wrong');221 });222};223exports.getLog = getLog;224function checkEnvBoolean(env){225 return env && env.toLowerCase() === 'true';...

Full Screen

Full Screen

logger.js

Source:logger.js Github

copy

Full Screen

1const winston = require('winston');2const { format } = winston;3const stackReg = /at\s+()(.*):(.*):(\d*):(\d*)/gi;4const stackRegWithMap = /at\s+(.*)\s+\((.*):(.*):(\d*):(\d*)\)/gi;5const uppercase = format(data => {6 data.level = data.level.toUpperCase();7 return data;8});9const formatErrorInfo = (message, ...meta) => {10 const stackList = new Error().stack;11 if (stackList) {12 const stack = stackList.split('\n').slice(3);13 const match = stackRegWithMap.exec(stack[0]) || stackReg.exec(stack[0]);14 if (match) {15 const errorInfo = `[N:${match[1]}] [F:${match[3]}] [L:${match[4]} | P:${16 match[5]17 }] ${message}`;18 return [errorInfo].concat(meta);19 }20 }21 return [message].concat(meta);22};23const env = process.env.NODE_ENV || 'development';24const defaultOptions = {25 level: env === 'development' ? 'debug' : 'info',26 format: format.combine(27 uppercase(),28 format.colorize(),29 format.timestamp({30 format: 'YYYY-MM-DD HH:mm:ss'31 }),32 format.splat(),33 format.printf(data => {34 let defaultPrint = `[${data.timestamp}] [${data.level}] ${data.message}`;35 return defaultPrint;36 })37 ),38 transports: [39 new winston.transports.Console(),40 new winston.transports.File({ filename: './log/application/info.log' })41 ]42};43const winstonLogger = winston.createLogger(defaultOptions);44function debug(message, ...meta) {45 winstonLogger.debug.apply(winstonLogger, formatErrorInfo(message, meta));46}47function info(message, ...meta) {48 winstonLogger.info.apply(winstonLogger, [message].concat(meta));49}50function warn(message, ...meta) {51 winstonLogger.warn.apply(winstonLogger, formatErrorInfo(message, meta));52}53function error(message, ...meta) {54 winstonLogger.error.apply(winstonLogger, formatErrorInfo(message, meta));55}56module.exports.logger = {57 debug: debug,58 info: info,59 warn: warn,60 error: error...

Full Screen

Full Screen

WinstonLoggerBrowser.js

Source:WinstonLoggerBrowser.js Github

copy

Full Screen

1'use strict'2var winstonLogger = {};3winstonLogger.error = function(msgStr, msgObj) {4 console.log({'error': {5 'msg': msgStr,6 'obj': msgObj7 }});8}9winstonLogger.warn = function(msgStr, msgObj) {10 console.log({'warning': {11 'msg': msgStr,12 'obj': msgObj13 }});14}15winstonLogger.info = function(msgStr, msgObj) {16 console.log({'info': {17 'msg': msgStr,18 'obj': msgObj19 }});20}21winstonLogger.log = function(level, msg) {22 console.log({'log': {23 'level': level,24 'msg': msg25 }});26}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const winstonLogger = require('mountebank').winstonLogger;2const winston = require('winston');3const logger = winston.createLogger({4 format: winston.format.json(),5 defaultMeta: { service: 'mb' },6 new winston.transports.File({ filename: 'error.log', level: 'error' }),7 new winston.transports.File({ filename: 'combined.log' })8});9winstonLogger(logger);10const mb = require('mountebank');11const imposters = mb.create({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log' });12imposters.start()13 .then(() => {14 console.log('Imposter started');15 })16 .catch((error) => {17 console.error(error);18 });19const mb = require('mountebank');20const imposters = mb.create({ port: 2525, pidfile: 'mb.pid', logfile: 'C:\\Users\\username\\mb.log' });21imposters.start()22 .then(() => {23 console.log('Imposter started');24 })25 .catch((error) => {26 console.error(error);27 });28const winstonLogger = require('mountebank').winstonLogger;29const winston = require('winston');30const logger = winston.createLogger({31 format: winston.format.json(),32 defaultMeta: { service: 'mb' },33 new winston.transports.File({ filename: 'error.log', level: 'error' }),34 new winston.transports.File({ filename: 'combined.log' })35});36winstonLogger(logger);

Full Screen

Using AI Code Generation

copy

Full Screen

1var winston = require('winston');2var winstonLogger = require('winston').winstonLogger;3var logger = new (winston.Logger)({4 new (winston.transports.Console)(),5 new (winston.transports.File)({ filename: 'somefile.log' })6});7logger.log('info', 'Hello distributed log files!');8logger.info('Hello again distributed logs');9logger.add(winston.transports.File, { filename: 'somefile.log' });10logger.remove(winston.transports.Console);11winstonLogger.info('Hello again distributed logs');12var winston = require('winston');13var winstonLogger = require('winston').winstonLogger;14var logger = new (winston.Logger)({15 new (winston.transports.Console)(),16 new (winston.transports.File)({ filename: 'somefile.log' })17});18logger.log('info', 'Hello distributed log files!');19logger.info('Hello again distributed logs');20logger.add(winston.transports.File, { filename: 'somefile.log' });21logger.remove(winston.transports.Console);22winstonLogger.info('Hello again distributed logs');23var winston = require('winston');24var winstonLogger = require('winston').winstonLogger;25var logger = new (winston.Logger)({26 new (winston.transports.Console)(),27 new (winston.transports.File)({ filename: 'somefile.log' })28});29logger.log('info', 'Hello distributed log files!');30logger.info('Hello again distributed logs');31logger.add(winston.transports.File, { filename: 'somefile.log' });32logger.remove(winston.transports.Console);33winstonLogger.info('Hello again distributed logs');

Full Screen

Using AI Code Generation

copy

Full Screen

1var winston = require('winston');2var winstonLogger = require('winston-mock-logger');3var logger = winstonLogger.createLogger({4 new winston.transports.Console({5 })6});7logger.info('Hello world');8var winston = require('winston');9var winstonLogger = require('winston-mock-logger');10var logger = winstonLogger.createLogger({11 new winston.transports.Console({12 })13});14logger.info('Hello world');15var winston = require('winston');16var winstonLogger = require('winston-mock-logger');17var logger = winstonLogger.createLogger({18 new winston.transports.Console({19 })20});21logger.info('Hello world');22var winston = require('winston');23var winstonLogger = require('winston-mock-logger');24var logger = winstonLogger.createLogger({25 new winston.transports.Console({26 })27});28logger.info('Hello world');29var winston = require('winston');30var winstonLogger = require('winston-mock-logger');31var logger = winstonLogger.createLogger({32 new winston.transports.Console({33 })34});35logger.info('Hello world');36var winston = require('winston');37var winstonLogger = require('winston-mock-logger');38var logger = winstonLogger.createLogger({39 new winston.transports.Console({40 })41});42logger.info('Hello world');43var winston = require('winston');

Full Screen

Using AI Code Generation

copy

Full Screen

1var winston = require('winston');2var winstonLogger = require('winston').winstonLogger;3var logger = new (winston.Logger)({4 new (winston.transports.Console)()5});6winstonLogger(logger);7var mb = require('mountebank');8mb.create({9}).then(function (server) {10 server.post('/test', function (request, response) {11 response.send(200, { hello: 'world' });12 });13});14var client = require('http').createClient(2525);15var request = client.request('POST', '/test', { 'Content-Length': 0 });16request.end();17info: [mb:2525] [POST] /test (200)18info: [mb:2525] [POST] /test (200)19var winston = require('winston');20var winstonLogger = require('winston').winstonLogger;21var logger = new (winston.Logger)({22 new (winston.transports.File)({ filename: 'mb.log' })23});24winstonLogger(logger);25var winston = require('winston');26var winstonLogger = require('winston').winstonLogger;27var logger = new (winston.Logger

Full Screen

Using AI Code Generation

copy

Full Screen

1const winston = require('winston');2const winstonLogger = require('mountebank/src/util/winstonLogger');3winstonLogger(winston);4const winston = require('winston');5const winstonLogger = require('mountebank/src/util/winstonLogger');6winstonLogger(winston);7const winston = require('winston');8const winstonLogger = require('mountebank/src/util/winstonLogger');9winstonLogger(winston);10const winston = require('winston');11const winstonLogger = require('mountebank/src/util/winstonLogger');12winstonLogger(winston);13const winston = require('winston');14const winstonLogger = require('mountebank/src/util/winstonLogger');15winstonLogger(winston);16const winston = require('winston');17const winstonLogger = require('mountebank/src/util/winstonLogger');18winstonLogger(winston);19const winston = require('winston');20const winstonLogger = require('mountebank/src/util/winstonLogger');21winstonLogger(winston);22const winston = require('winston');23const winstonLogger = require('mountebank/src/util/winstonLogger');24winstonLogger(winston);25const winston = require('winston');26const winstonLogger = require('mountebank/src/util/winstonLogger');27winstonLogger(winston);28const winston = require('winston');29const winstonLogger = require('mountebank/src/util/winstonLogger');30winstonLogger(winston);31const winston = require('winston');32const winstonLogger = require('mountebank/src/util/winstonLogger');

Full Screen

Using AI Code Generation

copy

Full Screen

1var winston = require('winston');2var winstonLogger = require('winston').loggers.get('mb');3var winstonLogger = require('winston').loggers.get('mb');4winstonLogger.info('test log from winston');5winstonLogger.warn('test log from winston');6winstonLogger.error('test log from winston');7var winston = require('winston');8var winstonLogger = require('winston').loggers.get('mb');9winstonLogger.info('test log from winston');10winstonLogger.warn('test log from winston');11winstonLogger.error('test log from winston');12var winston = require('winston');13var winstonLogger = require('winston').loggers.get('mb');14winstonLogger.info('test log from winston');15winstonLogger.warn('test log from winston');16winstonLogger.error('test log from winston');17var winston = require('winston');18var winstonLogger = require('winston').loggers.get('mb');19winstonLogger.info('test log from winston');20winstonLogger.warn('test log from winston');21winstonLogger.error('test log from winston');22var winston = require('winston');23var winstonLogger = require('winston').loggers.get('mb');24winstonLogger.info('test log from winston');25winstonLogger.warn('test log from winston');26winstonLogger.error('test log from winston');27var winston = require('winston');28var winstonLogger = require('winston').loggers.get('mb');29winstonLogger.info('test log from winston');30winstonLogger.warn('test log from winston');31winstonLogger.error('test log from winston');32var winston = require('winston');33var winstonLogger = require('winston').log

Full Screen

Using AI Code Generation

copy

Full Screen

1const winston = require('winston');2const winstonLogger = require('mountebank/src/logger/winstonLogger');3const logger = winstonLogger.create({winston: winston});4const mb = require('mountebank');5mb.create({6});7mb.post('/imposters', {8 {9 {10 is: {11 }12 }13 }14});

Full Screen

Using AI Code Generation

copy

Full Screen

1var winston = require('winston');2var winstonLogger = require('mountebank/src/util/winstonLogger').create('mb');3winstonLogger.info('testing log');4winston.info('testing log');5var winston = require('winston');6var winstonLogger = require('mountebank/src/util/winstonLogger').create('mb');7winstonLogger.info('testing log');8winston.info('testing log');9var winston = require('winston');10var winstonLogger = require('mountebank/src/util/winstonLogger').create('mb');11winstonLogger.info('testing log');12winston.info('testing log');13var winston = require('winston');14var winstonLogger = require('mountebank/src/util/winstonLogger').create('mb');15winstonLogger.info('testing log');16winston.info('testing log');17var winston = require('winston');18var winstonLogger = require('mountebank/src/util/winstonLogger').create('mb');19winstonLogger.info('testing log');20winston.info('testing log');21var winston = require('winston');22var winstonLogger = require('mountebank/src/util/winstonLogger').create('mb');23winstonLogger.info('testing log');24winston.info('testing log');25var winston = require('winston');26var winstonLogger = require('mountebank/src/util/winstonLogger').create('mb');27winstonLogger.info('testing log');28winston.info('testing log');29var winston = require('winston');30var winstonLogger = require('mountebank/src/util/winstonLogger').create('mb');31winstonLogger.info('testing log');32winston.info('testing log');

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run mountebank automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful