Click here to close now.




















Welcome!

Java IoT Authors: Liz McMillan, Pat Romanski, VictorOps Blog, Cloud Best Practices Network, Elizabeth White

Related Topics: Adobe Flex, Java IoT

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
Too often with compelling new technologies market participants become overly enamored with that attractiveness of the technology and neglect underlying business drivers. This tendency, what some call the “newest shiny object syndrome,” is understandable given that virtually all of us are heavily engaged in technology. But it is also mistaken. Without concrete business cases driving its deployment, IoT, like many other technologies before it, will fade into obscurity.
The Internet of Things is in the early stages of mainstream deployment but it promises to unlock value and rapidly transform how organizations manage, operationalize, and monetize their assets. IoT is a complex structure of hardware, sensors, applications, analytics and devices that need to be able to communicate geographically and across all functions. Once the data is collected from numerous endpoints, the challenge then becomes converting it into actionable insight.
Consumer IoT applications provide data about the user that just doesn’t exist in traditional PC or mobile web applications. This rich data, or “context,” enables the highly personalized consumer experiences that characterize many consumer IoT apps. This same data is also providing brands with unprecedented insight into how their connected products are being used, while, at the same time, powering highly targeted engagement and marketing opportunities. In his session at @ThingsExpo, Nathan Treloar, President and COO of Bebaio, will explore examples of brands transforming their businesses by t...
With the Apple Watch making its way onto wrists all over the world, it’s only a matter of time before it becomes a staple in the workplace. In fact, Forrester reported that 68 percent of technology and business decision-makers characterize wearables as a top priority for 2015. Recognizing their business value early on, FinancialForce.com was the first to bring ERP to wearables, helping streamline communication across front and back office functions. In his session at @ThingsExpo, Kevin Roberts, GM of Platform at FinancialForce.com, will discuss the value of business applications on wearable ...
The Internet of Things (IoT) is about the digitization of physical assets including sensors, devices, machines, gateways, and the network. It creates possibilities for significant value creation and new revenue generating business models via data democratization and ubiquitous analytics across IoT networks. The explosion of data in all forms in IoT requires a more robust and broader lens in order to enable smarter timely actions and better outcomes. Business operations become the key driver of IoT applications and projects. Business operations, IT, and data scientists need advanced analytics t...
While many app developers are comfortable building apps for the smartphone, there is a whole new world out there. In his session at @ThingsExpo, Narayan Sainaney, Co-founder and CTO of Mojio, will discuss how the business case for connected car apps is growing and, with open platform companies having already done the heavy lifting, there really is no barrier to entry.
With the proliferation of connected devices underpinning new Internet of Things systems, Brandon Schulz, Director of Luxoft IoT – Retail, will be looking at the transformation of the retail customer experience in brick and mortar stores in his session at @ThingsExpo. Questions he will address include: Will beacons drop to the wayside like QR codes, or be a proximity-based profit driver? How will the customer experience change in stores of all types when everything can be instrumented and analyzed? As an area of investment, how might a retail company move towards an innovation methodolo...
Contrary to mainstream media attention, the multiple possibilities of how consumer IoT will transform our everyday lives aren’t the only angle of this headline-gaining trend. There’s a huge opportunity for “industrial IoT” and “Smart Cities” to impact the world in the same capacity – especially during critical situations. For example, a community water dam that needs to release water can leverage embedded critical communications logic to alert the appropriate individuals, on the right device, as soon as they are needed to take action.
SYS-CON Events announced today that HPM Networks will exhibit at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. For 20 years, HPM Networks has been integrating technology solutions that solve complex business challenges. HPM Networks has designed solutions for both SMB and enterprise customers throughout the San Francisco Bay Area.
SYS-CON Events announced today that Micron Technology, Inc., a global leader in advanced semiconductor systems, will exhibit at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Micron’s broad portfolio of high-performance memory technologies – including DRAM, NAND and NOR Flash – is the basis for solid state drives, modules, multichip packages and other system solutions. Backed by more than 35 years of technology leadership, Micron's memory solutions enable the world's most innovative computing, consumer,...
As more intelligent IoT applications shift into gear, they’re merging into the ever-increasing traffic flow of the Internet. It won’t be long before we experience bottlenecks, as IoT traffic peaks during rush hours. Organizations that are unprepared will find themselves by the side of the road unable to cross back into the fast lane. As billions of new devices begin to communicate and exchange data – will your infrastructure be scalable enough to handle this new interconnected world?
Through WebRTC, audio and video communications are being embedded more easily than ever into applications, helping carriers, enterprises and independent software vendors deliver greater functionality to their end users. With today’s business world increasingly focused on outcomes, users’ growing calls for ease of use, and businesses craving smarter, tighter integration, what’s the next step in delivering a richer, more immersive experience? That richer, more fully integrated experience comes about through a Communications Platform as a Service which allows for messaging, screen sharing, video...
SYS-CON Events announced today that Pythian, a global IT services company specializing in helping companies leverage disruptive technologies to optimize revenue-generating systems, has been named “Bronze Sponsor” of SYS-CON's 17th Cloud Expo, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Founded in 1997, Pythian is a global IT services company that helps companies compete by adopting disruptive technologies such as cloud, Big Data, advanced analytics, and DevOps to advance innovation and increase agility. Specializing in designing, imple...
In his session at @ThingsExpo, Lee Williams, a producer of the first smartphones and tablets, will talk about how he is now applying his experience in mobile technology to the design and development of the next generation of Environmental and Sustainability Services at ETwater. He will explain how M2M controllers work through wirelessly connected remote controls; and specifically delve into a retrofit option that reverse-engineers control codes of existing conventional controller systems so they don't have to be replaced and are instantly converted to become smart, connected devices.
SYS-CON Events announced today that IceWarp will exhibit at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. IceWarp, the leader of cloud and on-premise messaging, delivers secured email, chat, documents, conferencing and collaboration to today's mobile workforce, all in one unified interface
WebRTC has had a real tough three or four years, and so have those working with it. Only a few short years ago, the development world were excited about WebRTC and proclaiming how awesome it was. You might have played with the technology a couple of years ago, only to find the extra infrastructure requirements were painful to implement and poorly documented. This probably left a bitter taste in your mouth, especially when things went wrong.
As more and more data is generated from a variety of connected devices, the need to get insights from this data and predict future behavior and trends is increasingly essential for businesses. Real-time stream processing is needed in a variety of different industries such as Manufacturing, Oil and Gas, Automobile, Finance, Online Retail, Smart Grids, and Healthcare. Azure Stream Analytics is a fully managed distributed stream computation service that provides low latency, scalable processing of streaming data in the cloud with an enterprise grade SLA. It features built-in integration with Azur...
Akana has announced the availability of the new Akana Healthcare Solution. The API-driven solution helps healthcare organizations accelerate their transition to being secure, digitally interoperable businesses. It leverages the Health Level Seven International Fast Healthcare Interoperability Resources (HL7 FHIR) standard to enable broader business use of medical data. Akana developed the Healthcare Solution in response to healthcare businesses that want to increase electronic, multi-device access to health records while reducing operating costs and complying with government regulations.
For IoT to grow as quickly as analyst firms’ project, a lot is going to fall on developers to quickly bring applications to market. But the lack of a standard development platform threatens to slow growth and make application development more time consuming and costly, much like we’ve seen in the mobile space. In his session at @ThingsExpo, Mike Weiner, Product Manager of the Omega DevCloud with KORE Telematics Inc., discussed the evolving requirements for developers as IoT matures and conducted a live demonstration of how quickly application development can happen when the need to comply wit...
The Internet of Everything (IoE) brings together people, process, data and things to make networked connections more relevant and valuable than ever before – transforming information into knowledge and knowledge into wisdom. IoE creates new capabilities, richer experiences, and unprecedented opportunities to improve business and government operations, decision making and mission support capabilities.