Log and Trace Features

Haxe provides developers with a powerful trace system. You can simply call trace everywhere within your own functions:

trace("Hello world !");

By default, in Flash the trace will display on the SWF screen in a scrolling TextField. In Neko it will be printed to stdout, and in JavaScript it will display in a DIV with the ID haxe:trace. Each trace is displayed with Filename and Line number informations where the trace occured :

Test.hx:11: Hello world !

In Flash, you can clear the trace by calling Log.clear().

Your custom trace

You can redirect the trace output by changing the Log.trace method where all trace calls are redirected. For example :

class MyTrace {

    public static function setRedirection() {
        haxe.Log.trace = myTrace;
    }

    private static function myTrace( v : Dynamic, ?inf : haxe.PosInfos ) {
        // .....
    }

}

The v argument is the first parameter of the trace call. It can be a String (like "Hello World" in our previous sample) or any other value. The inf argument contains all debug informations needed in order to display the error :

package haxe;

typedef PosInfos = {
    var fileName : String;
    var lineNumber : Int;
    var className : String;
    var methodName : String;
    var customParams : Array<Dynamic>;
}

The customParams array contains all extra arguments that were given to the original trace. Note that if no extra params were passed, then it is "null" instead of "[]" (is this intended in the API?).

For example :

class Test {
    function foo() {
        trace("hello","warning",123);
    }
}

Will be compiled as if it was calling :

    haxe.Log.trace(
        "hello",
        { 
            className : "Test",
            methodName : "foo",
            fileName : "Test.hx",
            lineNumber : 3,
            customParams : ["warning",123]
        }
    );

Removing the traces

You can simply remove all trace informations by compiling your project with --no-traces argument. This will remove all trace calls as if they were not present in the program.

Extra Position Parameter

It is sometimes useful to define a custom method that does some traces in some case. Let's take for example the following class :

class Test {
 
    static function assert( cond : Bool, ?pos : haxe.PosInfos ) {
      if( !cond )
          haxe.Log.trace("Assert in "+pos.className+"::"+pos.methodName,pos);
    }

    static function main() {
        assert( 1 == 1 ); // nothing
        assert( 0 == 3 ); // trace "Assert in Test::main"
    }

}

The following usage is possible since in Haxe when the haxe.PosInfos optional parameter is not set, its default value will always be replaced by the compiler.

version #13762, modified 2012-04-15 08:49:07 by elyon