Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Integrating log4j and CFMX

An open source Java project gives developers new capabilities

Unless you've never developed a Web application, or for that matter, an application of any size, you've undoubtedly encountered a situation where the application wasn't doing what it was doing when you developed it ("It worked fine for me!") or when it was tested ("I swear we tested this!").

The application might be slow, it could be throwing a SQL error, or maybe a form submission is causing your application to throw an error. Usually it's an end user that reports this information to you and usually you'd like way more information than what you're getting over the phone, through e-mail, or through your help-desk system. To get more information, you may have at some point injected code into your production application that output data to the browser or wrote data to a text file. It might have been something as simple as using the <cfoutput> tag to show a SQL query, a <cfdump> to show a data structure, or maybe you looked at cfstat and perfmon. If you're using ColdFusion 5 or greater, you might have used the <cflog> tag to log data to a file.

All of these solutions, while simple, have their disadvantages. Injecting debugging code into a production application is error prone and may be impossible (sometimes developers aren't given access to the production application). If you wrote a custom tag or used the <cflog> tag, the debugging code is always on, which means that your log files could (and probably will) grow to be unmanageably large and probably unusable. (Technically it is possible to turn off the <cflog> tag by using security sandboxes in ColdFusion MX. To do this, browse to the "Sandbox Security" page in ColdFusion Administrator. Then you must create a security sandbox for the directory that you want to disable <cflog> for. Finally, edit the sandbox you created and disable the <cflog> tag by moving it from the left-hand select box to the right-hand select box. You must then restart ColdFusion MX for your change to take place.)

Wouldn't it be nice to be able to leave logging code in your application and then be able to change the granularity at runtime? If you agree, read on!

Log4j is an open source Java project that gives the developer the ability to control which log statements are output with arbitrary granularity. It is fully configurable at runtime using external configuration files and most important, it can be utilized within ColdFusion. In this article, I'll introduce you to the basics of log4j; show examples of how log4j can be used within ColdFusion; talk about some tips and tricks; and point you to further resources for developing applications with log4j.

This article is not intended to be an in-depth introduction to log4j. There are numerous tutorials available on the Web, some of which are highlighted at the end of this article.

Before getting started, you'll need to make sure that you have appropriately configured your system:

  • ColdFusion MX must be installed. You'll see that I'm using the ColdFusion MX Enterprise integrated Web server running on port 8300 throughout the examples. Note that while log4j can probably be utilized by versions of ColdFusion prior to MX, I will not be providing examples or configuration tips for those versions.
  • You'll need to confirm that the log4j JAR file exists in your ColdFusion installation. On most systems, log4j will exist in either {$jrun4_install} serverscfusioncfusion-earcfusion-warWEB-INFcfusionlib or {$cfusion_install}lib.
  • If you plan on developing a Java-based CFX tag to utilize log4j (from the research I've done), you'll need to use version 1.1.3 of log4j, which is not the latest version of log4j, but is the version included with ColdFusion MX. You'll find a link in the resources section of this article that points to the earlier versions of log4j, specifically version 1.1.3. For various reasons, you cannot use the latest versions of log4j and ColdFusion MX due to incompatibilities between version 1.1.3 and version 1.2.8 (the most recent version of log4j).
  • Finally, create a folder in /cfusionmx/wwwroot/ called "log4j", into which you'll put the source code for this article (code examples for this article appear at the end, and can be downloaded from www.sys-con.com/coldfusion/sourcec.cfm).
What Is log4j and Why Should You Use It?
As I mentioned briefly above, log4j is an open source Java project that gives the developer the ability to control which log statements are output with arbitrary granularity at runtime. Unpacked a little more, log4j enables you to inject logging code into your application during development, leave it there during production, and then configure the level of logging (i.e., only error messages but not warning messages), the section of your application you want logging from, and the endpoint you'd like the logging to reach, all using a simple properties file or an XML document.

You should use log4j for a couple of reasons. First, with the addition of ColdFusion components in ColdFusion MX (which include object-oriented concepts and structures), ColdFusion developers have the ability to create encapsulated classes that exist within packages. For instance, a company that sells hardware products might have a ColdFusion component named

com.mycompany.catalog.product.saw

How do you debug or track the logic that exists in the "saw" methods? You could use <cflog>, but then you'd either have a separate log file for each component (i.e.; <cflog file="saw" type="information" text="The saw has been instantiated.">) or you'd have one big log file with a lot of unrelated entries, and no way to turn on logging for just the saw component.

Second, <cflog>, <cfoutput>, or writing your own logging custom tag or component most likely assumes that the log messages should end up in a text file or be written to the browser as part of the returned HTML. log4j makes no such assumptions. Instead, you can configure log4j to output to the system log, to your own custom text file, to a database, to a message queue, to e-mail, or to the Windows Event log. In fact, you can configure log4j to output data to almost anything that receives data, because you can write your own "Appenders," which are the tools that receive your logging message and then hand it off to the appropriate recipient. Writing an appender is beyond the scope of this article, but there are numerous tutorials available on the Web (some of which are highlighted at the end of this document).

Finally, you should use log4j because it's extremely fast. log4j was designed from the ground up to be as fast as possible. It's highly unlikely that something you write during the last week of your development cycle will be as fast or as reliable as log4j.

Hopefully at this point your appetite has been whetted and you want to see how it works! Let's get to it!

Using log4j and ColdFusion MX
Integrating log4j into your application is relatively straightforward. First you use the CreateObject() function to get access to the log4j Category class:

categoryObject = CreateObject("java", "org.apache.log4j.Category");

The Category object, probably the most used class in the log4j package, defines a static method in Java (which means that you don't have an instance of the Category class before using it) called "getInstance()" and returns an instance of the Category class specific to the section of code you want to use logging in. When using log4j in Java, you'll almost always use the fully qualified name of the class as the argument to the "getInstance()" method like this:

categoryInstance = Category.getInstance("com.mycompany.MyClass");

However, because you're using log4j in ColdFusion MX, you'll probably want to either: a) standardize on a common naming system for your code (using names like "com.mycompany.database" or "com.mycompany.products"); or b) if you're using ColdFusion components use the GetMetaData() function to return the name of the component. For instance, given an instance of a ColdFusion component called "theInstance", you can retrieve the name like this:

componentName = GetMetaData(theInstance).name;

So back to log4j. You have a variable called "categoryObject" and you want to call the "getInstance()" method on that class to return an instance of the Category class (which will handle the actual logging), specific to the section of code you're using. You'll end up with something like this (if you're not logging inside the CFC):

logger = categoryObject.getInstance("com.mycompany.product");

or if you're using a ColdFusion component you might have something like this (if the logging is occurring inside the CFC):

logger = categoryObject.getInstance(getMetaData(this).name);

That was the hard part! The only thing left to do is log the message. The Category instance (called "logger" in the example above) has five ways of logging the message: fatal(), error(), warn(), info(), and debug(). Each of these methods is considered to be of a specific priority with fatal() being the highest priority, and debug() being the lowest priority. You use the one that makes the most sense for the section of code you're working on. For example, let's say you're working on a simple guest book form submission. After saving the information about the guest book submission to a database, you want to log that the submission was successful. This is purely informational and as such your code would look like this:

categoryObject = CreateObject("java", "org.apache.log4j.Category");
logger = categoryObject.getInstance("com.mycompany.guestbook");
logger.info("guest book submission saved successfully.");

To make it more interesting, let's say that you have a flaky database. Sometimes the database goes down, so you want to log any errors that happen as a result. You'd use the error() method instead:

<cftry>
<cfquery name="save" datasource="mydb">
INSERT INTO guestbook(name, email)
VALUES ('Aaron', 'myemail')
</cfquery>
<cfcatch>
<cfset categoryObject = CreateObject("java", "org.apache.log4j.Category")>
<cfset logger = categoryObject.getInstance("com.mycompany.guestbook")>
<cfset logger.error(cfcatch.message)>
</cfcatch>
</cftry>

If you've been following along with your favorite IDE, you're probably wondering where all this data is being sent. Right now everything you've done is being ignored because by default, log4j isn't going to log anything. You have to specify what categories of code you want logged, which priorities you want logged, and where you want that information logged to. So let's get to the configuration!

There are three ways to configure log4j. The first and easiest is by using the BasicConfigurator class. Just like the Category class, you must first use the ColdFusion CreateObject() function:

configurator = CreateObject("java", "org.apache.log4j.BasicConfigurator");

and then you call the "configure()" method:

configurator.configure();

The two lines of code above set up log4j to log all messages to the standard output stream, which in the case of ColdFusion MX is the log file named "cfusion-out.log", located in {cfusion}/logs/ or in {cfusion}/runtime/logs/. While simple, this isn't very helpful and could get to be harmful, so let's move to the second configuration option.

The PropertyConfigurator class gives you the ability to specify a text configuration file (technically a Java properties file). To configure log4j using the PropertyConfigurator class, you'll first use the CreateObject function to get access to the PropertyConfigurator class and then you'll call the "configure()" method on the class with the full path to the properties configuration file:

configurator = CreateObject("java", org.apache.log4j.PropertyConfigurator");
configurator.configure("c:mysiteconfig.properties");

Third and finally, you could use the DOMConfigurator, which is a class that allows you to provide an XML configuration file. The syntax is not much different than the PropertyConfigurator:

configurator = CreateObject("java", "org.apache.log4j.xml.DOMConfigurator");
configurator.configure("C:mysiteconfig.xml");

The configuration files are the magic in the process. The configuration files allow you to direct logging to different "Appenders"; things like the console, a text file, e-mail, a message queue, or the Windows Event Log. In short, specify the category you want to set up for logging by specifying the name of the category that you used in the code examples above:

<category name="com.mycompany.products">
<priority value="info"/>
<appender-ref ref="logfile"/>
</category>

and then specify the priority and which appender you'd like to use. In the example above, I've specified that I want to see messages with a priority of "info" or higher (which includes everything but "debug" messages) and that I want the messages to be sent to an appender called "logfile". Next you'd configure the appender, which in the above example is called "logfile":

<appender name="logfile" class="org.apache.log4j.FileAppender">
<param name="File" value="C:\mysite\logging.log" />
<param name="Append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%t %-5p %c{2} - %m%n"/>
</layout>
</appender>

Because the configuration files aren't really related to ColdFusion, I'll leave it up to you to read about the available patterns (ways of arranging the data in the log file) and appenders (methods of storing the data) in the log4j documentation (links available at the end of this article).

Tips and Tricks
log4j is a resource not unlike a database or an e-mail server. You don't want to use it unnecessarily because it can, and most likely will, slow down an application in production. As such, one of the first things you should do is to make sure your application performs adequately with logging turned off (i.e., in the configuration file, don't create a <category> element for any of your sections, this effectively turns logging off). Make sure to test your application before and after inserting log4j statements to ensure that log4j isn't slowing your application down too much.

Second, one of the most expensive operations when using log4j is the configuration operation. If possible, make sure to initialize log4j only once by using an init() method in a ColdFusion component or by using your own custom logic. For instance, you might write something like this in your Application.cfm:

<cfscript>
if (NOT IsDefined("application.init") {
configurator = CreateObject("java", "org.apache.log4j.xml.DOMConfigurator");
configurator.configure("c:mysiteconfig.xml");
application.init = true;

}
</cfscript>

The "configure()" method need only be called once because internally it modifies a static variable (a variable whose storage is allocated for the entire execution of a program), which means that log4j will remain configured as long as the ColdFusion server process is running. Note that this also means that the configuration you use applies to all the Web applications running in this instance (if you have multiple instances of ColdFusion MX then you don't have to worry about this).

Finally, the log4j team recognized that string concatenation can be an expensive operation in and of itself. As such, they included some utility methods in the Category class that let you first check to see if the logging method you want to use is even enabled. For example, the following block of code requires ColdFusion to first evaluate the "guest book was signed by " & #email#' string before sending data to the info() method.

categoryInstance = CreateObject("java", "org.apache.log4j.Category");
logger = categoryInstance.getInstance("com.foo");
logger.info("guest book was signed by " & #email#);

However, you can use the isInfoEnabled() method to verify that "info" messages should even be logged. Going back to the example above, it would actually be marginally faster to do this:

categoryInstance = CreateObject("java", "org.apache.log4j.Category");
logger = categoryInstance.getInstance("com.foo");
if (logger.isInfoEnabled()) {
logger.info("guest book was signed by " & #email#);
}

Likewise, you could also use the "isDebugEnabled()" method to verify that debug operations should be logged.

Further Resources
I've included two sample ColdFusion scripts at the end of this article, "log4j_sample_propertyconfig.cfm" and "log4j_sample_xmlconfig.cfm," (Listing 1 and Listing 2) as well as the corresponding configuration files for each ("sample_config.properties" and "sample_config.xml"; Listing 3 and Listing 4).

  • Third-Party Logging API: http://sys-con.com/story/passwordprompt?storyid=36144
  • log4j documentation: http://jakarta.apache.org/log4j/docs/index.html
  • log4j earlier releases: http://jakarta.apache.org/log4j/docs/earlier.html
  • log4j configuration: http://webforums.macromedia.com/coldfusion/ messageview.cfm?catid=273&threadid=726244
  • ColdFusion debugging: www.forta.com/blog/index.cfm?mode=e&entry=920
  • Harness the power of log4j with Jabber: www.106.ibm.com/developerworks/java/library/j-instlog/
  • log4j appenders: www.qos.ch/ac2001/F11-90.html
  • The complete log4j manual: www.qos.ch/shop/products/clm_t.jsp
  • More Stories By Aaron Johnson

    Aaron Johnson is a senior software engineer at Jive Software. He lives with his wonderful wife, young son and dog in a Portland, Oregon. You can find out more by reading his blog at http://cephas.net/blog/.

    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
    Mobile device usage has increased exponentially during the past several years, as consumers rely on handhelds for everything from news and weather to banking and purchases. What can we expect in the next few years? The way in which we interact with our devices will fundamentally change, as businesses leverage Artificial Intelligence. We already see this taking shape as businesses leverage AI for cost savings and customer responsiveness. This trend will continue, as AI is used for more sophistica...
    Real IoT production deployments running at scale are collecting sensor data from hundreds / thousands / millions of devices. The goal is to take business-critical actions on the real-time data and find insights from stored datasets. In his session at @ThingsExpo, John Walicki, Watson IoT Developer Advocate at IBM Cloud, will provide a fast-paced developer journey that follows the IoT sensor data from generation, to edge gateway, to edge analytics, to encryption, to the IBM Bluemix cloud, to Wa...
    What is the best strategy for selecting the right offshore company for your business? In his session at 21st Cloud Expo, Alan Winters, U.S. Head of Business Development at MobiDev, will discuss the things to look for - positive and negative - in evaluating your options. He will also discuss how to maximize productivity with your offshore developers. Before you start your search, clearly understand your business needs and how that impacts software choices.
    SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
    SYS-CON Events announced today that Fusic will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Fusic Co. provides mocks as virtual IoT devices. You can customize mocks, and get any amount of data at any time in your test. For more information, visit https://fusic.co.jp/english/.
    SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
    SYS-CON Events announced today that Enroute Lab will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enroute Lab is an industrial design, research and development company of unmanned robotic vehicle system. For more information, please visit http://elab.co.jp/.
    SYS-CON Events announced today that Mobile Create USA will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Mobile Create USA Inc. is an MVNO-based business model that uses portable communication devices and cellular-based infrastructure in the development, sales, operation and mobile communications systems incorporating GPS capabi...
    SYS-CON Events announced today that Keisoku Research Consultant Co. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Keisoku Research Consultant, Co. offers research and consulting in a wide range of civil engineering-related fields from information construction to preservation of cultural properties. For more information, vi...
    There is huge complexity in implementing a successful digital business that requires efficient on-premise and cloud back-end infrastructure, IT and Internet of Things (IoT) data, analytics, Machine Learning, Artificial Intelligence (AI) and Digital Applications. In the data center alone, there are physical and virtual infrastructures, multiple operating systems, multiple applications and new and emerging business and technological paradigms such as cloud computing and XaaS. And then there are pe...
    SYS-CON Events announced today that Interface Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Interface Corporation is a company developing, manufacturing and marketing high quality and wide variety of industrial computers and interface modules such as PCIs and PCI express. For more information, visit http://www.i...
    SYS-CON Events announced today that SIGMA Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. uLaser flow inspection device from the Japanese top share to Global Standard! Then, make the best use of data to flip to next page. For more information, visit http://www.sigma-k.co.jp/en/.
    SYS-CON Events announced today that B2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. B2Cloud specializes in IoT devices for preventive and predictive maintenance in any kind of equipment retrieving data like Energy consumption, working time, temperature, humidity, pressure, etc.
    Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
    While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 brings the mainstream adoption of containers for production workloads. In his session at 21st Cloud Expo, Ben McCormack, VP of Operations at Evernote, will discuss how data centers of the future will be managed, how th...
    SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp em...
    SYS-CON Events announced today that Nihon Micron will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nihon Micron Co., Ltd. strives for technological innovation to establish high-density, high-precision processing technology for providing printed circuit board and metal mount RFID tags used for communication devices. For more inf...
    SYS-CON Events announced today that Suzuki Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Suzuki Inc. is a semiconductor-related business, including sales of consuming parts, parts repair, and maintenance for semiconductor manufacturing machines, etc. It is also a health care business providing experimental research for...
    SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
    SYS-CON Events announced today that Daiya Industry will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Daiya Industry specializes in orthotic support systems and assistive devices with pneumatic artificial muscles in order to contribute to an extended healthy life expectancy. For more information, please visit https://www.daiyak...