• Blogs (9)
    • 📱 236 - 992 - 3846

      📧 jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • Dynamically assign Node.js log path

    Blogs20172017-03-16


    Dynamically assign Node.js log path

    In Node.js server-side, is there a simple way to dynamic assign log-path without such as Morgan etc? Here is my solution, with `pretty` npm etc, the log can be more powerful.

    The demo file is in ~/React/test/test-path.js, run `node test-path.js` to validate:

    (function() {
        var level = 4;
        var fp = __filename.split('/').slice(level).join('::').replace(/\.js$/, '::');
        //var fp = require('path').resolve(__dirname).substr(1).replace(/\//g, '::');
    
        function ClassFunc(age, name) {
            this.logPath = fp + this.constructor.name + '::';
            this.age = age;
            this.name = name;
            this.getName = function() {
                var fname = arguments[arguments.length-1] || 'N/A';
                console.log(this.logPath + fname + '-> ' + this.name);
            },
            this.getAge = function() {
                var fname = arguments[arguments.length-1] || 'N/A';
                console.log(this.logPath + fname + '-> ' + this.age);
            }
        }
        function func() {
            var logPath = fp + arguments.callee.name;
            console.log(logPath, '- logs...');
        }
    
        var instance = new ClassFunc(18, 'Golden Age');
        instance.getName('getName');
        instance.getAge('getAge');
    
        func();
    
     //will output:
     // React::test::test-path::ClassFunc::getName-> Golden Age
     // React::test::test-path::ClassFunc::getAge-> 18
     // React::test::test-path::func - logs...
    }());