Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
addressed review comments
  • Loading branch information
Arpendu Kumar Garai authored and Arpendu Kumar Garai committed Aug 20, 2022
commit 20528a9139ad5260750e1a0e3ee26f54f159d15d
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const PORT = 5000;
const app = express();
const simpleLogger = new Logger('SimpleLogging');

const LD_SDK_KEY = 'sdk-d2432dc7-e56a-458b-9f93-0361af47d578';
const LD_SDK_KEY = 'sdk-********-****-****-****-************';
const LOG_LEVEL_FLAG_KEY = 'backend-log-level';
const client = LaunchDarkly.init(LD_SDK_KEY);
const asyncGetFlag = util.promisify(client.variation);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const CronJob = cron.CronJob;
const CronTime = cron.CronTime;

// Initiating LaunchDarkly Client
const LD_SDK_KEY = 'sdk-d2432dc7-e56a-458b-9f93-0361af47d578';
const LD_SDK_KEY = 'sdk-********-****-****-****-************';
const userName = 'admin';
const launchDarklyClient = LaunchDarkly.init( LD_SDK_KEY );

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { format } from 'date-fns';
import padEnd from 'lodash/padEnd.js';
import capitalize from 'lodash/capitalize.js';

const LEVELS = { debug: 10, log: 20, warn: 30, error: 40 };
let currentLogLevel = LEVELS['debug'];

class DynamicLogger {
constructor( module, ldClient, flagKey, user ) {
this.module = module ? module : '';

this.debug = this.debug.bind(this);
this.info = this.info.bind(this);
this.warn = this.warn.bind(this);
this.error = this.error.bind(this);
this.writeToConsole = this.writeToConsole.bind(this);
this.ldClient = ldClient;
this.flagKey = flagKey;
this.user = user;
this.previousLevel = null;
}

static setLogLevel(level) {
currentLogLevel = LEVELS[level];
}

static get(module) {
return new Logger(module);
}

writeToConsole(level, message) {
if (LEVELS[level] >= currentLogLevel) {
const dateTime = format(new Date(), 'MM-dd-yyyy HH:mm:ss:SSS');
const formattedLevel = padEnd(capitalize(level), 5);
const formattedMessage = `${dateTime} ${formattedLevel} [${
this.module
}] ${message}`;
console[level](formattedMessage, '');
}
}

async debug( message ) {
if ( await this._presentLog( 'debug' ) ) {
this.writeToConsole('debug', message);
}
}

async error( message ) {
if ( await this._presentLog( 'error' ) ) {
this.writeToConsole('error', message);
}
}

async info( message ) {
if ( await this._presentLog( 'info' ) ) {
this.writeToConsole('info', message);
}
}

async warn( message ) {
if ( await this._presentLog( 'warn' ) ) {
this.writeToConsole('warn', message);
}
}

async _presentLog( level ) {

const minLogLevel = await this.ldClient.variation(
this.flagKey,
{
key: this.user
},
'debug' // Default / fall-back value if LaunchDarkly unavailable.
);

if ( minLogLevel !== this.previousLevel ) {
console.log( `Switching to log-level: ${ minLogLevel }` );
}

switch ( this.previousLevel = minLogLevel ) {
case 'error':
return level === 'error';
case 'warn':
return level === 'error' || level === 'warn';
case 'info':
return level === 'error' || level === 'warn' || level === 'info';
default:
return true;
}
}
}

export default DynamicLogger;
Original file line number Diff line number Diff line change
@@ -1,41 +1,33 @@
import chalk from 'chalk';
import util from 'util';
import LaunchDarkly from 'launchdarkly-node-server-sdk';
import LdLogger from './ld_logger.js';
import DynamicLogger from './dynamic_logger.js';

const LD_SDK_KEY = 'sdk-d2432dc7-e56a-458b-9f93-0361af47d578';
const LD_SDK_KEY = 'sdk-********-****-****-****-************';
const flagKey = 'backend-log-level';
const userName = 'admin';
const launchDarklyClient = LaunchDarkly.init( LD_SDK_KEY );
const logger = new LdLogger( launchDarklyClient, flagKey, userName );
const asyncGetFlag = util.promisify(launchDarklyClient.variation);
const user = {
user: userName
};
let logger;
let loop = 0;

launchDarklyClient.once('ready', async () => {
launchDarklyClient.once('ready', async () => {
setTimeout( executeLoop, 1000 );
}
);

//Fake node status reader randomized to throw errors.
function readNodeStatus() {
const nodeStatus = ( Math.random() * 100 ).toFixed( 1 );
if ( nodeStatus <= 30 ) {
throw new Error( 'IOError' );
}
return nodeStatus;
}

function executeLoop () {
console.log( chalk.dim.italic( `Loop ${ ++loop }` ) );
logger.debug( 'Executing loop.' );
try {
logger.debug( 'Checking number of nodes that are busy.' );
const nodeCount = readNodeStatus();
logger.info( `Number of Nodes that are busy: ${ nodeCount }%` );
if ( nodeCount >= 50 ) {
logger.warn( 'More than half of the nodes are busy. We should'
+ ' think of adding more nodes to the cluster.' );
}
} catch ( error ) {
logger.error( `Node count could not be read: ${ error.message }` );
}
setTimeout( executeLoop, 1000 );
async function executeLoop () {
const initialLogLevel = await asyncGetFlag(flagKey, user, 'debug');
logger = new DynamicLogger( 'DynamicLogging', launchDarklyClient, flagKey, userName );
DynamicLogger.setLogLevel(initialLogLevel);
console.log( chalk.dim.italic( `Loop ${ ++loop }` ) );
logger.debug( 'Executing loop.' );
logger.debug('This is a debug log.');
logger.info('This is an info log.');
logger.warn('This is a warn log.');
logger.error('This is a error log.');
setTimeout( executeLoop, 1000 );
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ app.get("/", async (req, res) => {
});
app.listen(8080);

const sdkKey = 'sdk-d2432dc7-e56a-458b-9f93-0361af47d578';
const LD_SDK_KEY = 'sdk-********-****-****-****-************';
const userName = 'admin';
let client;

async function init() {
if (!client) {
client = LaunchDarkly.init(sdkKey);
client = LaunchDarkly.init(LD_SDK_KEY);
await client.waitForInitialization();
}

Expand Down
63 changes: 0 additions & 63 deletions nodejs/nodejs-backend-admin-feature-flag-launchdarkly/ld_logger.js

This file was deleted.

18 changes: 9 additions & 9 deletions nodejs/nodejs-backend-admin-feature-flag-launchdarkly/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import padEnd from 'lodash/padEnd.js';
import capitalize from 'lodash/capitalize.js';

const LEVELS = { debug: 10, log: 20, warn: 30, error: 40 };
let LD_LOG_LEVEL = LEVELS['debug'];
let currentLogLevel = LEVELS['debug'];

class Logger {
constructor(module) {
Expand All @@ -13,19 +13,19 @@ class Logger {
this.log = this.log.bind(this);
this.warn = this.warn.bind(this);
this.error = this.error.bind(this);
this.consoleWriter = this.consoleWriter.bind(this);
this.writeToConsole = this.writeToConsole.bind(this);
}

static setLogLevel(level) {
LD_LOG_LEVEL = LEVELS[level];
currentLogLevel = LEVELS[level];
}

static get(module) {
return new Logger(module);
}

consoleWriter(level, message, context = '') {
if (LEVELS[level] >= LD_LOG_LEVEL) {
writeToConsole(level, message, context = '') {
if (LEVELS[level] >= currentLogLevel) {
const dateTime = format(new Date(), 'MM-dd-yyyy HH:mm:ss:SSS');
const formattedLevel = padEnd(capitalize(level), 5);
const formattedMessage = `${dateTime} ${formattedLevel} [${
Expand All @@ -36,19 +36,19 @@ class Logger {
}

debug(message, context) {
this.consoleWriter('debug', message, context);
this.writeToConsole('debug', message, context);
}

log(message, context) {
this.consoleWriter('log', message, context);
this.writeToConsole('log', message, context);
}

warn(message, context) {
this.consoleWriter('warn', message, context);
this.writeToConsole('warn', message, context);
}

error(message, context) {
this.consoleWriter('error', message, context);
this.writeToConsole('error', message, context);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
"main": "index.js",
"type": "module",
"scripts": {
"start": "nodemon index.js",
"bootstrap": "nodemon bootstrap.js",
"dynamic": "nodemon dynamic_logging.js",
"rateLimiter": "nodemon rate_limiter.js",
"cron": "nodemon cron_job.js"
"start": "node index.js",
"bootstrap": "node bootstrap.js",
"dynamic": "node dynamic_logging.js",
"rateLimiter": "node rate_limiter.js",
"cron": "node cron_job.js"
},
"author": "Arpendu Kumar Garai",
"license": "ISC",
Expand All @@ -21,7 +21,6 @@
"express": "^4.18.1",
"express-rate-limit": "^6.5.1",
"launchdarkly-node-server-sdk": "^6.4.2",
"lodash": "^4.17.21",
"nodemon": "^2.0.19"
"lodash": "^4.17.21"
}
}