Click here to close now.

Welcome!

Java Authors: Elizabeth White, Carmen Gonzalez, Pat Romanski, Jason Bloomberg, Liz McMillan

Related Topics: Adobe Flex, Java

Adobe Flex: Article

Boost Productivity of Your Flex-Java Project with Log4Fx Component

It's hard to overestimate the importance of having good logging facility when you develop distributed applications

It’s hard to overestimate the importance of having a good logging facility when you develop distributed  applications. Did the client’s request reached the server-side component? What did the server send back?  Add to this the inability to use debuggers while processing GUI events like focus change, and you may   need to spend hours if not days trying to spot some sophisticated errors. That’s why a commercial-grade  logger is a must if you work with an application that is spread over the network and written in  different languages such as Adobe Flex and Java.

Log4Fx is an advanced, yet very simple to use, logger component for Adobe Flex applications that use Java application servers. You can set up the logging on the client or server sides, and you can redirect the output of the log messages to local log windows or make the log output easily available to the production support teams located remotely.  Think of a production situation when a particular client complains that the application runs slow. Log4Fx allows you to turn on the logging just for this client and you can do it remotely with Web-browser access to the log output.

Log4Fx comes with several convenient and easy-to-use display panels with log messages. This manual also covers techniques of logging mixed Flex/Java projects with or without Flex Builder.

USING LOG4FX
If you’ve been using other loggers like log4j, you’ll be pleasantly surprised at how Log4Fx automatically inserts required logging code in your existing Flex project. It comes down to memorizing a couple of keystroke combinations as explained below. But first, you need to install Log4Fx, and then add it to your Flex project. Just right-click on your Flex Project, select Log4Fx > Add Dependency Files from the popup menu.This action will add several new artifacts to your project:
  • A new Flex component Log4FxLoggingTarget.mxml, will be automatically added to your project directory
  • An extra tag <Log4FxLoggingTarget xmlns=”*”> will be added at the end of the source code of your default Flex application
  • A new application RemoteLogReceiver.mxml is added to the project to provide remote access to the log messages
  • The Log4Fx.swc is added to your project’s build path
  • A small file log4flex.jar is added to the your Java server’s lib folder
Now you can use the hot keys to add required log lines to your application code. You can see the list of available hot keys by pressing CTRL + R. 

For example, let’s say you are considering adding a line to the application called MyStockProtflio:

trace(“Entered  the method getPriceQuotes”);

Just press the cursor in the script section of your application and press Ctrl+R followed by M, which will insert the  following lines in your program:

  import mx.logging.Log;
  import mx.logging.ILogger;
  private var logger:ILogger = Log.getLogger("MyStockPortfolio");

Now place the cursor, say in the function getPriceQuotes(), and press Ctrl+R followed by D and the following line will be added at your cursor location:

if (Log.isDebug()) logger.debug("");

Enter the text between the double quotes, and if you’ll set the level of logging to Debug, this message will be sent to the specified destination selected with the Logging Manager as explained below.

If you need to write a log message that will deliver fatal errors, press Ctrl+R, F , and you’ll see a new line in your code:

if (Log.isFatal()) logger.fatal("");

Just enter appropriate error information inside the quotes, and Log4Fx will send the information of this error to the selected log target.  

Here’s the code for the HelloWorld application with highlighted inserts from Log4Fx:

<?xml version="1.0" encoding="UTF-8"?><mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Grid>
        <mx:GridRow>
            <mx:GridItem>
                <mx:LinkButton label="Hello world!"           
                           click="logger.warn('Warning');"/>
            </mx:GridItem>
        </mx:GridRow>
        <mx:GridRow>
            <mx:GridItem>
                <mx:LinkButton label="Hello world again!"
                             click="logger.info('Info');"/>
            </mx:GridItem>
        </mx:GridRow>
    </mx:Grid>
    <mx:Script>
        <![CDATA[
            import mx.logging.Log;
            import mx.logging.ILogger;
            private var logger:ILogger = Log.getLogger("com.farata.samples");
        ]]>
    </mx:Script>

<Log4FlexLoggingTarget xmlns="*"/>
</mx:Application>

You still need to take care of two more items:

1. Define the destination of log messages by specifying the logging target.
2. Using Logging Manager, define the properties for various logging categories, set the default logging level et al.

Using Logging Manager
The logging manager is a part of Log4Fx, and it allows you to change the logging settings on the fly while debugging the application is in progress. During the lifespan of the application, you may need to be able to redirect the log messages to a different target(s). This functionality is implemented in the Logging Manager, which is a UI component that supports interactive control levels, categories, and targets. This is what you can do with the Logging Manager on the client side:
  • Automatically discover and list logging categories, and allow changing of the logging level for each logical category or a package.
  • List registered targets/destinations, and set default logging level and other common parameters.
  • Store the logging settings on the client's computer.
To see this panel, start the application that uses Log4Fx and press CTRL+SHIFT+BACKSPACE  –  the  logging manager will pop up on top of your application window. The following screenshot shows the logging manager panel on top of the HelloWorld application after the user pressed CTRL+SHIFT+BACKSPACE.



You can change the logging level at any time while your application is running. This feature is crucial for mission-critical production applications, where you can’t ask the user to stop the application (i.e., financial trading systems), but need to obtain the logging information to help the customer on the live system.

Even if the user is not an IT professional, s/he can do this by following directions of the production support engineer.
You can also change the default log level by selecting the required log level from the dropdown box. The destination (target) of your log messages can be selected from another dropdown as described in the section Working with Log targets.

WORKING WITH LOG TARGETS
Trace

If you set the target Trace on the Logging Manager panel, all program messages will be output using the class from Flex framework called TraceTarget as if you've been using the function trace().

Socket
Setting the target to Socket will engage SocketTarget class for logging your program messages via HTTP connection.

 
If your Flex project was configured to work with the Java Servlet container, i.e., Apache Tomcat, adding Log4Fx dependency files creates a small file on the server side log4flex.jar, which contains two Java classes – FlexLoggerServlet and ServerFlexLogger.  The file web.xml will be automatically modified to add a section that maps the requests that contain the url-pattern “logging” to FlexLoggerServlet.

You can also use this reference implementation if you decide to customize the logger to utilize non-Java Web servers, i.e., PHP or .Net.

Server
This option can be used by applications that utilize Flex remoting via LiveCycle Data Services ES (LCDS), OpenAMF, or any other remoting transport. If you want to send the log output to the server, create a Java class that will support logging on the server side. Here's the sample version of a class that uses popular Log4J component:

package com.theriabook.logging;
import org.apache.log4j.Logger;
import org.apache.log4j.Level;

public class ServerFlexLogger {
    
    static public void log(String levelStr, String message)
    {
        logger.log(Level.toLevel(levelStr), message);
    }
    static Logger logger;  
    static
    {
          logger = Logger.getLogger("MyFlexLogger");
        logger.setLevel(Level.ALL);
    }
}

In Logging Manager, as soon as you select Server as a target, a text field will be shown where you need to enter the name of the server-side destination that is mapped to the class com.theriabook.logging.ServerFlexLogger.

Now the log messages from your Flex programs will be sent to the server destination ServerFlexLogger and logged there. The section 5.4 shows an example of how such communication could have been programmed manually, but Log4Fx spares you from this. Just configure the Flex remoting destination and enter its name in the Destination field as shown above.
 
Local Panel
Flex developers who spend most of the time “inside” the Eclipse IDE, send the log output to the local panel, which is nothing else but yet another Eclipse View.
 
Right-click on your Flex Project, select Log4Fx > Show Workbench Viewer from the popup menu. You'll see a new view panel in your Eclipse workbench:


 

Select Local Panel as a target, and now you can your log messages will be sent to a new Farata Logger View:

 
The push buttons on the toolbar allow you to turn on/off the output of debug, info, warning, fatal and error messages. You can also sort the messages by level, time, category, and message text.

XPanel
The XPanel target allows to trace Flex/Flash applications interactively in a separate window. It also gives you native platform features like the ability to save a log to a file, keep the log window always on top and redirect the output to platform-specific debugging API. XPanel runs on Windows 95/98/Me, NT/2000/XP/Vista.  To configure output to the external XPanel, just right-click on your Flex Project, and select Log4Fx > Show External Viewer from the popup menu. You’ll see an empty XPanel window will be displayed. Ensure that the target on the Logging Monitor is set to XPanel. Now your log messages will be streamed to an external XPanel window:


 
XPanel's toolbar provides quick access to Exit, Save Log, Start/Stop Logging, Clear Log, independent logging levels, Text/DataGrid Mode and “About” menu options.

Log4FlexLoggingTarget Explained
When you first added the Log4Fx dependency files, the file Log4FlexLoggingTarget.mxml was automatically added to your application project. It allows setting default targets for Log4Fx. In this section we'll discuss the code for the Log4FlexLoggingTarget.mxml:

<fx:LoggingTarget
xmlns:fx="http://www.faratasystems.com/2006/components"
xmlns:mx="http://www.adobe.com/2006/mxml"
defaultLoggerLevel="{LogEventLevel.INFO}">

<mx:Script>
    import mx.logging.LogEventLevel;
</mx:Script>

 <!-- Setting default output to XPanel -->
<fx:XPanelLogOutput
  fieldSeparator=" -> " />
     <!-- Setting special popup window for filtering -->
     <fx:adjustmentManager>
      <fx:LoggingAdjustmentManager
       keyCode="{Keyboard.BACKSPACE}"
       shiftKey="true"
       ctrlKey="true">
       <mx:Array>
        <!-- List of available outputs (with their own settings) -->
        <fx:XPanelOutputDescription />
        <fx:TraceOutputDescription
         fieldSeparator=" -> "
         includeCategory="true"
         includeDate="true"
         includeLevel="true"
         includeTime="true" />
        <fx:SocketOutputDescription />
        <fx:ServerOutputDescription/>
        <fx:LocalConnectionOutputDescription/>
        <fx:RemoteOutputDescription/>
       </mx:Array>
      </fx:LoggingAdjustmentManager>
     </fx:adjustmentManager>
</fx:LoggingTarget>

This code performs the following actions:
1. Set the default logger level. You can change it by modifying the value of the property defaultLoggerLevel, which has a default value of LogEventLevel.INFO, and we’ve included this code for illustration purposes.
2. Set the destination of the default output of the logger. By default, the log info goes to XPanel. You can change the default value either by assigning appropriate value to XPanelLogOutput, (for example, LocalConnectionOutput) or by using Logging Manager. You can also specify additional parameters for targets, for example, fieldSeparator, which denotes the field delimiter to be used in log files. All available parameters are listed in Eclipse Help (see, com.theriabook.util.XPanelTarget or other targets). The next section of this document describes how to set such parameters.
3. You can redefine the hot keys that bring up the Logging Settings panel by changing the values of the properties keyCode, shiftKey and/or ctrlKey. For example, if you use the combination keyCode=“{Keyboard.ESCAPE}”, ctrlKey="false" and shiftKey="true" in the code, pressing SHIFT + ESC will open the Logging Monitor window. If none of these properties are set, you can open the Logging Monitor by pressing F12.
4. In the code section “List of available outputs” you can change the list of available logging targets in the Logging Manager panel. By default, it shows XPanelOutput, TraceOutput, SocketOutput, ServerOutput, LocalConnectionOutput ? RemoteOutput, which were described above. If you do not need all targets, remove some of the available outputs from Log4FlexLoggingTarget.mxml.

You can set the default logging level is defined in the file Log4FlexLoggingTarget.mxml and in the Logging Manager panel. The latter has higher priority over the settings specified in Log4FlexLoggingTarget.mxml. For example, after adding Log4Fx to your project, you can specify LogEventLevel.WARN as the default logger level that will take effect on the application startup. But if you change this level to ERROR using the Logging Manager panel, it’ll remember the ERROR level till the next start of your application despite the fact that the file Log4FlexLoggingTarget.mxml still has the WARN level. To remove all logger settings made from the panel, press the button Clear Local Storage on the Logging Manager panel. After that, the settings from the file Log4FlexLoggingTarget.mxml will be in effect again.

Remote Logging
Adding dependency file described above created a new application in your project – RemoteLogReceiver.mxml, which can be used by a remote production support crew. Let’s say the user’s application is deployed at the following URL:
http://230.123.12.10:8080/myapplication.html. By pressing the CTRL-SHIFT-BACKSPACE, the user brings the Logging Manager and selects the target Remote Logging.


 
The destination RemoteLogging is selected automatically, and the user needs to input a password, which he will share with the production support engineer.

Since the RemoteLogReceiver.mxml is also an application that is sitting right next to your main application in Flex Builder’s project, it’ll also will get compiled into an SWF file, the html wrapper will be generated too, and it will be deployed in the Web server of your choice too. The end users will never use it, and they won’t even know that it exists. But production engineer can enter its URL in his browser when needed:

http://230.123.12.10:8080/RemoteLogReceiver.html

Think of an undercover informant who just lives in the neighborhood, but when engaged, it immediately starts sending the information out.

After entering the password provided by the user and pressing the button Connect, he’ll start receiving Log messages sent by the user’s application.
 


The pushbuttons on the toolbar allow selective output of log messages – it works the same way as with XPanel.

Summary
Given the huge productivity boost, the cost of $99 for Log4Fx component seems to be nominal. Even if you are not planning to purchase the logger, give it a try and download its manual at myflex.org, which also has good coverage of Adobe  Flex logging aspects.

More Stories By Flex News Desk

Flex News Desk provides the very latest news on the cross-platform Flex development framework for creating rich Internet applications, and on Adobe's AIR/Flex/Flash product combination.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
Advanced Persistent Threats (APTs) are increasing at an unprecedented rate. The threat landscape of today is drastically different than just a few years ago. Attacks are much more organized and sophisticated. They are harder to detect and even harder to anticipate. In the foreseeable future it's going to get a whole lot harder. Everything you know today will change. Keeping up with this changing landscape is already a daunting task. Your organization needs to use the latest tools, methods and expertise to guard against those threats. But will that be enough? In the foreseeable future attacks w...
Disruptive macro trends in technology are impacting and dramatically changing the "art of the possible" relative to supply chain management practices through the innovative use of IoT, cloud, machine learning and Big Data to enable connected ecosystems of engagement. Enterprise informatics can now move beyond point solutions that merely monitor the past and implement integrated enterprise fabrics that enable end-to-end supply chain visibility to improve customer service delivery and optimize supplier management. Learn about enterprise architecture strategies for designing connected systems tha...
Wearable devices have come of age. The primary applications of wearables so far have been "the Quantified Self" or the tracking of one's fitness and health status. We propose the evolution of wearables into social and emotional communication devices. Our BE(tm) sensor uses light to visualize the skin conductance response. Our sensors are very inexpensive and can be massively distributed to audiences or groups of any size, in order to gauge reactions to performances, video, or any kind of presentation. In her session at @ThingsExpo, Jocelyn Scheirer, CEO & Founder of Bionolux, will discuss ho...
Hadoop as a Service (as offered by handful of niche vendors now) is a cloud computing solution that makes medium and large-scale data processing accessible, easy, fast and inexpensive. In his session at Big Data Expo, Kumar Ramamurthy, Vice President and Chief Technologist, EIM & Big Data, at Virtusa, will discuss how this is achieved by eliminating the operational challenges of running Hadoop, so one can focus on business growth. The fragmented Hadoop distribution world and various PaaS solutions that provide a Hadoop flavor either make choices for customers very flexible in the name of opti...
Even as cloud and managed services grow increasingly central to business strategy and performance, challenges remain. The biggest sticking point for companies seeking to capitalize on the cloud is data security. Keeping data safe is an issue in any computing environment, and it has been a focus since the earliest days of the cloud revolution. Understandably so: a lot can go wrong when you allow valuable information to live outside the firewall. Recent revelations about government snooping, along with a steady stream of well-publicized data breaches, only add to the uncertainty
The Workspace-as-a-Service (WaaS) market will grow to $6.4B by 2018. In his session at 16th Cloud Expo, Seth Bostock, CEO of IndependenceIT, will begin by walking the audience through the evolution of Workspace as-a-Service, where it is now vs. where it going. To look beyond the desktop we must understand exactly what WaaS is, who the users are, and where it is going in the future. IT departments, ISVs and service providers must look to workflow and automation capabilities to adapt to growing demand and the rapidly changing workspace model.
SYS-CON Events announced today that Dyn, the worldwide leader in Internet Performance, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Dyn is a cloud-based Internet Performance company. Dyn helps companies monitor, control, and optimize online infrastructure for an exceptional end-user experience. Through a world-class network and unrivaled, objective intelligence into Internet conditions, Dyn ensures traffic gets delivered faster, safer, and more reliably than ever.
As organizations shift toward IT-as-a-service models, the need for managing and protecting data residing across physical, virtual, and now cloud environments grows with it. CommVault can ensure protection &E-Discovery of your data – whether in a private cloud, a Service Provider delivered public cloud, or a hybrid cloud environment – across the heterogeneous enterprise. In his session at 16th Cloud Expo, Randy De Meno, Chief Technologist - Windows Products and Microsoft Partnerships, will discuss how to cut costs, scale easily, and unleash insight with CommVault Simpana software, the only si...
Cloud data governance was previously an avoided function when cloud deployments were relatively small. With the rapid adoption in public cloud – both rogue and sanctioned, it’s not uncommon to find regulated data dumped into public cloud and unprotected. This is why enterprises and cloud providers alike need to embrace a cloud data governance function and map policies, processes and technology controls accordingly. In her session at 15th Cloud Expo, Evelyn de Souza, Data Privacy and Compliance Strategy Leader at Cisco Systems, will focus on how to set up a cloud data governance program and s...
Roberto Medrano, Executive Vice President at SOA Software, had reached 30,000 page views on his home page - http://RobertoMedrano.SYS-CON.com/ - on the SYS-CON family of online magazines, which includes Cloud Computing Journal, Internet of Things Journal, Big Data Journal, and SOA World Magazine. He is a recognized executive in the information technology fields of SOA, internet security, governance, and compliance. He has extensive experience with both start-ups and large companies, having been involved at the beginning of four IT industries: EDA, Open Systems, Computer Security and now SOA.
The industrial software market has treated data with the mentality of “collect everything now, worry about how to use it later.” We now find ourselves buried in data, with the pervasive connectivity of the (Industrial) Internet of Things only piling on more numbers. There’s too much data and not enough information. In his session at @ThingsExpo, Bob Gates, Global Marketing Director, GE’s Intelligent Platforms business, to discuss how realizing the power of IoT, software developers are now focused on understanding how industrial data can create intelligence for industrial operations. Imagine ...
Operational Hadoop and the Lambda Architecture for Streaming Data Apache Hadoop is emerging as a distributed platform for handling large and fast incoming streams of data. Predictive maintenance, supply chain optimization, and Internet-of-Things analysis are examples where Hadoop provides the scalable storage, processing, and analytics platform to gain meaningful insights from granular data that is typically only valuable from a large-scale, aggregate view. One architecture useful for capturing and analyzing streaming data is the Lambda Architecture, representing a model of how to analyze rea...
SYS-CON Events announced today that Vitria Technology, Inc. will exhibit at SYS-CON’s @ThingsExpo, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Vitria will showcase the company’s new IoT Analytics Platform through live demonstrations at booth #330. Vitria’s IoT Analytics Platform, fully integrated and powered by an operational intelligence engine, enables customers to rapidly build and operationalize advanced analytics to deliver timely business outcomes for use cases across the industrial, enterprise, and consumer segments.
The Internet of Things (IoT) promises to evolve the way the world does business; however, understanding how to apply it to your company can be a mystery. Most people struggle with understanding the potential business uses or tend to get caught up in the technology, resulting in solutions that fail to meet even minimum business goals. In his session at @ThingsExpo, Jesse Shiah, CEO / President / Co-Founder of AgilePoint Inc., showed what is needed to leverage the IoT to transform your business. He discussed opportunities and challenges ahead for the IoT from a market and technical point of vie...
HP and Aruba Networks on Monday announced a definitive agreement for HP to acquire Aruba, a provider of next-generation network access solutions for the mobile enterprise, for $24.67 per share in cash. The equity value of the transaction is approximately $3.0 billion, and net of cash and debt approximately $2.7 billion. Both companies' boards of directors have approved the deal. "Enterprises are facing a mobile-first world and are looking for solutions that help them transition legacy investments to the new style of IT," said Meg Whitman, Chairman, President and Chief Executive Officer of HP...
Containers and microservices have become topics of intense interest throughout the cloud developer and enterprise IT communities. Accordingly, attendees at the upcoming 16th Cloud Expo at the Javits Center in New York June 9-11 will find fresh new content in a new track called PaaS | Containers & Microservices Containers are not being considered for the first time by the cloud community, but a current era of re-consideration has pushed them to the top of the cloud agenda. With the launch of Docker's initial release in March of 2013, interest was revved up several notches. Then late last...
The explosion of connected devices / sensors is creating an ever-expanding set of new and valuable data. In parallel the emerging capability of Big Data technologies to store, access, analyze, and react to this data is producing changes in business models under the umbrella of the Internet of Things (IoT). In particular within the Insurance industry, IoT appears positioned to enable deep changes by altering relationships between insurers, distributors, and the insured. In his session at @ThingsExpo, Michael Sick, a Senior Manager and Big Data Architect within Ernst and Young's Financial Servi...
The explosion of connected devices / sensors is creating an ever-expanding set of new and valuable data. In parallel the emerging capability of Big Data technologies to store, access, analyze, and react to this data is producing changes in business models under the umbrella of the Internet of Things (IoT). In particular within the Insurance industry, IoT appears positioned to enable deep changes by altering relationships between insurers, distributors, and the insured. In his session at @ThingsExpo, Michael Sick, a Senior Manager and Big Data Architect within Ernst and Young's Financial Servi...
PubNub on Monday has announced that it is partnering with IBM to bring its sophisticated real-time data streaming and messaging capabilities to Bluemix, IBM’s cloud development platform. “Today’s app and connected devices require an always-on connection, but building a secure, scalable solution from the ground up is time consuming, resource intensive, and error-prone,” said Todd Greene, CEO of PubNub. “PubNub enables web, mobile and IoT developers building apps on IBM Bluemix to quickly add scalable realtime functionality with minimal effort and cost.”
Sensor-enabled things are becoming more commonplace, precursors to a larger and more complex framework that most consider the ultimate promise of the IoT: things connecting, interacting, sharing, storing, and over time perhaps learning and predicting based on habits, behaviors, location, preferences, purchases and more. In his session at @ThingsExpo, Tom Wesselman, Director of Communications Ecosystem Architecture at Plantronics, will examine the still nascent IoT as it is coalescing, including what it is today, what it might ultimately be, the role of wearable tech, and technology gaps stil...