I’m having trouble getting my head around declaring functions dynamically. I tried to ask this question so it was more generic but I really don’t know what I’m doing in this case and kept coming back to my code.
I have a json object which contains log levels (as seen in code below) and for each log level I need to create a function so I can call, for example: log.info(‘my log message’);
The problem I’m experiencing is when I call log.info() I can’t figure out that ‘info’ was called for all I know log.error() could of been called because all these functions contain the same dynamic code and I don’t know a way to detect what function called this.
I hope that makes sense. I’m writing this for Node.js
so my code so far is below. I have a comment saying where my problem function is and where I want the log level to display.
exports.logger = function() { // Syslog severity levels var levels = { emerg: { "code": 0 }, alert: { "code": 1 }, crit: { "code": 2 }, error: { "code": 3 }, warning: { "code": 4 }, notice: { "code": 5 }, info: { "code": 6 }, debug: { "code": 7 } }; // Loop through each severity level for (var severity in levels) { // Ensure we're not iterating over a prototype if (levels.hasOwnProperty(severity)) { // Declare function this[severity] = function(message) { // Here's the problem: I have no idea what called this function. console.log('Log severity level here:', message); }; } } }
This is how I call it:
var logger = require('log.js'); var log = new (logger.logger)( // settings removed for example ); log.info('test');
Problem courtesy of: Sean Bannister