Milos Zikic - Personal site, sharing thoughts about startups, products and engineering

Logging in Flex

Server side developers have been used to use some Log4Something to provide application logging.

Flex provides similar pattern to this but working a lot lately with various Flex developers they are not aware of it. All of them use trace() since it helps during debugging time but power of logging in production is avoided.

If You have installed a debug version of Flash player (affects also Air running in ADL) you can configure logging by creating mm.cfg file in your %homepath% (on windows) or $home (on Linux).

Sample mm.cfg file is:

ErrorReportingEnable=1
TraceOutputFileEnable=1


This will enable logging and will put the log stuff in %homepath%\Application Data\Macromedia\Flash Player\Logs\flashlog.txt.
If You want to change the file to which Flex does the logging just add the TraceOutputFileName property to the mm.cfg which will point to the file on the file system. More configuration options are available on livedocs.

However there is a more convenient way to achieve this and a better pattern as well. This is to use the same pattern already present in all other logging frameworks.

First step is to initialize logging on application startup:
// Create a target.
var logTarget:TraceTarget = new TraceTarget();

// Log only messages for the classes in the mx.rpc.* and
// mx.messaging packages.
logTarget.filters=["mx.rpc.*","mx.messaging.*"];

// Log all log levels.
logTarget.level = LogEventLevel.ALL;

// Add date, time, category, and log level to the output.
logTarget.includeDate = true;
logTarget.includeTime = true;
logTarget.includeCategory = true;
logTarget.includeLevel = true;

// Begin logging.
Log.addTarget(logTarget);


This will create a default TraceTarget implementation which will in debug mode log to flashlog.txt if you have mm.cfg configured.

And then in order to log:

private static var logger:ILogger = Log.getLogger("com.test.logger.LogerSample");


And then somewhere in the code just log in known way: logger.debug(), logger.info() etc.
TraceTarget is not that useful for us but we can easily implement our own Targets and provide advanced loging features. AS3CoreLib has FileTarget implemented which provides logging to file. It is easy to implement for instance WebServiceTarget, SocketTarget or similar.

And one more thing for the ones used to pass the class instead of typing the string to Log.getLogger() You can implement a LogUtil class which will have a method like this:


public static function getLogName (object:Object) : String {
if (object is Class) {
return getQualifiedClassName(object);
} else {
return object.toString();
}
}


Now You can use a syntax like this to get logger:
private static var logger:ILogger = Log.getLogger(LogerSample);

More on this topic can be read on logging livedocs.

Share this post