Python:如何在被调用的方法中获取调用者的方法名?
假设我有两种方法:
def method1(self):
...
a = A.method2()
def method2(self):
...
Run Code Online (Sandbox Code Playgroud)
如果我不想对method1进行任何更改,如何在method2中获取调用者的名称(在此示例中,名称为method1)?
我现在正在开发一个应用程序,并放置一个全局isDebug开关.我想换行console.log以方便使用.
//isDebug controls the entire site.
var isDebug = true;
//debug.js
function debug(msg, level){
var Global = this;
if(!(Global.isDebug && Global.console && Global.console.log)){
return;
}
level = level||'info';
Global.console.log(level + ': '+ msg);
}
//main.js
debug('Here is a msg.');
Run Code Online (Sandbox Code Playgroud)
然后我在Firefox控制台中得到了这个结果.
info: Here is a msg. debug.js (line 8)
Run Code Online (Sandbox Code Playgroud)
如果我想用debug()被调用的行号记录,info: Here is a msg. main.js (line 2)怎么办?
花在C之类的语言上的JavaScript开发人员经常会错过使用某些类型的内省的能力,比如记录行号,以及调用当前方法的方法.好吧,如果您使用的是V8(Chrome,Node.js),您可以使用以下内容.
是否可以获取每个日志输出的行号和文件?
例如:
var winston = require('winston');
winston.log('info', 'some message!'); // this is at line 4 of myfile.js
Run Code Online (Sandbox Code Playgroud)
应该在日志文件中指定'some message'来自myFile.js第4行.
简单的介绍:
我试图获取函数定义的行号,仅解析文档注释的公共内容.我已经到了可以找到函数名称的地步,如果我想要我可以执行该函数,但我似乎无法找出任何方法来提取行号信息.注意:这纯粹是出于文档目的,因此不需要跨浏览器.
我知道firebug(但不是firebug lite,所以我不知道这是多么可能)显示鼠标悬停时引用函数的行号和脚本位置.我查看了firebug源代码并发现它们调用了(domPanel.js:536),但似乎无法在源代码中找到这个"addMember"函数:
this.addMember(object, "userFunction", userFuncs, name, val, level, 0, context);
Run Code Online (Sandbox Code Playgroud)
可能这是不可能确定的.我的后备正在使用[userfunction].name,[userfunction].toSource()然后尝试匹配源到源.但是我想尽可能避免这些,因为名称可能是非唯一的,而toSource()给出了源后处理.也许有办法绑定firebug api?
最小解释代码:
[注意目标是获取此信息:window.MyWindowObject.PublicFunction: script.js line 3]
的script.js
(function () {
function referencedFunction() {
///<summary>Sample XML Doc Comment</summary>
alert('well hello there!');
}
var publicObject = window.MyWindowObject || {};
publicObject.PublicFunction = referencedFunction;
window.MyWindowObject = publicObject;
}());
Run Code Online (Sandbox Code Playgroud)
index.htm的
<!DOCTYPE html>
<html>
<script src="script.js"></script>
</html>
Run Code Online (Sandbox Code Playgroud)
编辑:对于在稍后搜索时发现此信息的任何人,我发现了一些其他有用的相关信息:
Stacktrace.js:https://github.com/eriwen/javascript-stacktrace - 非常接近但不完全是我想要的,因为它似乎没有获得最终功能的位置.他们网站上的例子不正确(虽然演示"看起来"像我想要的)
在chrome(和IE9)中:[userfunction].toString()保留注释(不在firefox中),这是我最终可能会使用的.我打算使用firefox的[userfunction].toSource(),但这看起来像浏览器操作的函数源.firefox的[userfunction].toString()似乎保留了代码,但删除了注释
我有一个nodejs项目,使用log4js来写日志。我想在开始新日期时创建新的文件日志。
示例:
daily.2017_07_31.log
daily.2017_08_01.log
daily.2017_08_02.log
daily.2017_08_03.log
在java中,我知道配置log4j,但在带有log4js的nodejs中我不知道。感谢大家的帮助:)
javascript ×3
node.js ×3
express ×1
firebug ×1
intellisense ×1
log4js-node ×1
logging ×1
npm ×1
python ×1
v8 ×1
winston ×1