First version
[src/app-framework-demo.git] / afm-client / app / etc / _Trace.js
1 /* 
2  * Copyright 2014 Fulup Ar Foll
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 var util       = require("util");
18 var path       = require("path");
19 var config= require('./_Config');
20
21 function TracePoint () {
22         var saved = Error.prepareStackTrace;                           // save default prepareStack function
23         Error.prepareStackTrace = function(_, stack){ return stack; }; // overload err stack handling
24         Error.captureStackTrace(this, arguments.callee);               // request a stack
25         this.trace = this.stack;                                       // effectively build trace
26         Error.prepareStackTrace = saved;                               // restore original nodejs function  
27 }
28
29 // ------- Public Methods --------------
30 var dbgLevel = function(target, level, format) {  //+ arguments
31     // try to get debugLevel from calling object or global config
32     if (target && target.dbgLevel)  dbgLevel = target.dbgLevel;
33     else dbgLevel = config.DBG_LVL || 1;
34     
35     if (dbgLevel >= level ) {
36
37         var args = [].slice.call(arguments, 2); // copy argument in a real array leaving out level
38         var message = util.format.apply(null, args);
39         
40         var trace = new TracePoint().trace;
41         var info = {
42             fullpath : trace[1].getFileName(),
43             linenum  : trace[1].getLineNumber(),
44             basename : path.basename (trace[1].getFileName())
45         };
46         
47         if (dbgLevel >= 5) {
48             console.log("%s:%d", info.fullpath, info.linenum);
49             console.log("\t[%d] %j", dbgLevel, message);
50         }
51         else console.log("--%d-- [%s:%d] -- %j", dbgLevel, info.basename, info.linenum, message);
52     }
53 };
54
55 module.exports = dbgLevel;