免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 843 | 回复: 0
打印 上一主题 下一主题

Log信息获取调用类和调用方法名的实现原理 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-01-22 18:27 |只看该作者 |倒序浏览
Sun JDK 源代码下载 http://wwws.sun.com/software/communitysource/
  先注册并登录到“Sun Community Source Licensing”,然后下载J2SE(几十兆)或者J2EE(几百兆)。
  
  Log能够把代码运行时间,类名,方法名,还有信息,全部都打印出来。
  一个直观的例子,每次启动Tomcat(缺省配置)的时候。一般可以看到
  Jul 9, 2004 11:22:29 AM org.apache.struts.util.PropertyMessageResources
  INFO: Initializing, config='org.apache.webapp.admin.ApplicationResources', returnNull=true
  Jul 9, 2004 11:22:41 AM org.apache.coyote.http11.Http11Protocol start
  INFO: Starting Coyote HTTP/1.1 on port 8080
  
  时间,类名,方法名,信息都打印了出来。
  那么,log是如何获取调用自身的这个类和这个方法名的呢?
  
  后面给出的代码是JDK1.4的源代码,和Log4J的源代码。说明其实现原理。
  获得调用类,和方法名,就是需要获得当前运行栈的结构。
  new Throwable().getStackTrace() 会返回当前运行栈的结构层次。
  利用这种原理,可以获得整个运行栈的调用关系。
  
  JDK1.4的Java.util.logging包, 通过Throwable.getStackTrace()方法实现的。
  // Get the stack trace.
  StackTraceElement stack[] = (new Throwable()).getStackTrace();
  
  完整的代码在JDK1.4的源代码里面,java.util.logging.LogRecord类的inferCaller方法。
  
  java代码:
  2 // Private method to infer the caller's class and method names
  3 private void inferCaller() {
  ...}
  4 needToInferCaller = false;
  5 // Get the stack trace.
  6 StackTraceElement stack[] = (new Throwable()).getStackTrace();
  7 // First, search back to a method in the Logger class.
  8 int ix = 0;
  9 while (ix t, to be in the format
  5
  6 
  7 java.lang.Throwable
  8 ...
  9 at org.apache.log4j.PatternLayout.format(PatternLayout.java:413)
  10 at org.apache.log4j.FileAppender.doAppend(FileAppender.java:183)
  11 at org.apache.log4j.Category.callAppenders(Category.java:131)
  12 at org.apache.log4j.Category.log(Category.java:512)
  13 at callers.fully.qualified.className.methodName(FileName.java:74)
  14 ...

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/58547/showart_469516.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP