如何在btrace中将日志写入文件?

4

我有以下的btrace脚本。我想记录特定类中函数的进入和退出。

..
package com.sun.btrace.samples;

import com.sun.btrace.BTraceUtils;
import com.sun.btrace.Profiler;
import com.sun.btrace.annotations.*;
@BTrace class Profiling {
@Property
Profiler swingProfiler = BTraceUtils.Profiling.newProfiler();

@OnMethod(
    clazz="com.pkg.classname", 
    method="/.*/")
    void entry(@ProbeMethodName(fqn=true) String probeMethod) {
        BTraceUtils.print("Entry" );
        BTraceUtils.println(BTraceUtils.timestamp() );
        BTraceUtils.println(probeMethod);
    }

@OnMethod(
    clazz="com.pkg.classname", 
    location=@Location(value=Kind.RETURN)
    )
    void exit(@ProbeMethodName(fqn=true) String probeMethod, @Duration long duration) {
        BTraceUtils.print("Exit:" );
        BTraceUtils.println(BTraceUtils.timestamp() );
        BTraceUtils.println(probeMethod);
    }

}

这会在控制台上输出结果。我该怎样将结果写入文件呢?Btrace不允许创建新对象。
(显然的解决方法是重定向到文件。另一个选择是使用VisualVM btrace插件,然后输出将进入visualVM窗口。不确定它是否能够处理非常大的输出,比如500Mb左右。)
谢谢。
3个回答

5
你可以使用BTrace代理程序(http://kenai.com/projects/btrace/pages/UserGuide#btrace-agent)启动你的应用程序。然后,你可以向代理程序指定scriptOutputFile参数,并且所有调用println等函数生成的输出都将被写入到指定的文件中,而不是标准输出(stdout)。请注意保留HTML标记。

1
不,BTrace无法记录到文件中,因为它需要尽可能轻量化,以便跟踪结果不受其自身日志记录的影响。您将需要重定向到日志文件中。

-2
您可以像这样将控制台输出写入日志文件:
Process p = Runtime.getRuntime().exec("cmd /c " + command);
StringBuffer output = new StringBuffer("");
if (p != null) {
    BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String buf = "";
    try {
        int count = 0;
        while ((buf = is.readLine()) != null) {
            output.append(buf);
            output.append(System.getProperty("line.separator"));
            if(++count % flushLineNumber == 0){
                FileUtils.writeStringToFile(file, output.toString(), true);
                output.setLength(0);
            }
        }
        is.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

这个命令是brtrace......我已经在我的个人项目中有了这个功能。


这个答案相当简洁。请尽量具体说明如何解决问题。 - IInspectable
有人问如何将btrace日志输出重定向到文件中。通常,btrace日志会在命令行中打印出来。我帖子中的代码将btrace输出从命令行重定向到文件中。我的代码中的命令类似于“btrace -cp btrace/build [pid] TraceMethodArgsAndReturn.java”。 - vcycyv
1
仍然不清楚您发布的代码(它恰好是C#/仅限Windows,并且质量很差)如何实际用于解决最初问题。更重要的是,与仅将命令行输出重定向到文件(例如“btrace ... > btrace.log”)相比,有哪些优势? - IInspectable

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接