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


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:

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

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:


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");

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");

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"/>

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"/>

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:

if (NOT IsDefined("application.init") {
configurator = CreateObject("java", "org.apache.log4j.xml.DOMConfigurator");
application.init = true;


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
    In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
    Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
    DXWorldEXPO LLC announced today that ICC-USA, a computer systems integrator and server manufacturing company focused on developing products and product appliances, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City. ICC is a computer systems integrator and server manufacturing company focused on developing products and product appliances to meet a wide range of ...
    Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
    Michael Maximilien, better known as max or Dr. Max, is a computer scientist with IBM. At IBM Research Triangle Park, he was a principal engineer for the worldwide industry point-of-sale standard: JavaPOS. At IBM Research, some highlights include pioneering research on semantic Web services, mashups, and cloud computing, and platform-as-a-service. He joined the IBM Cloud Labs in 2014 and works closely with Pivotal Inc., to help make the Cloud Found the best PaaS.
    In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
    DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
    We are seeing a major migration of enterprises applications to the cloud. As cloud and business use of real time applications accelerate, legacy networks are no longer able to architecturally support cloud adoption and deliver the performance and security required by highly distributed enterprises. These outdated solutions have become more costly and complicated to implement, install, manage, and maintain.SD-WAN offers unlimited capabilities for accessing the benefits of the cloud and Internet. ...
    Headquartered in Plainsboro, NJ, Synametrics Technologies has provided IT professionals and computer systems developers since 1997. Based on the success of their initial product offerings (WinSQL and DeltaCopy), the company continues to create and hone innovative products that help its customers get more from their computer applications, databases and infrastructure. To date, over one million users around the world have chosen Synametrics solutions to help power their accelerated business or per...
    Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
    Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT staff augmentation services for software technology providers. By providing clients with unparalleled niche technology expertise and industry experience, Chetu has become the premiere long-term, back-end software development partner for start-ups, SMBs, and Fortune 500 companies. Chetu is headquartered in Plantation, Florida, with thirteen offices throughout the U.S. and abroad.
    Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
    I think DevOps is now a rambunctious teenager - it's starting to get a mind of its own, wanting to get its own things but it still needs some adult supervision," explained Thomas Hooker, VP of marketing at CollabNet, in this SYS-CON.tv interview at DevOps Summit at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
    "MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
    Major trends and emerging technologies – from virtual reality and IoT, to Big Data and algorithms – are helping organizations innovate in the digital era. However, to create real business value, IT must think beyond the ‘what’ of digital transformation to the ‘how’ to harness emerging trends, innovation and disruption. Architecture is the key that underpins and ties all these efforts together. In the digital age, it’s important to invest in architecture, extend the enterprise footprint to the cl...
    Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, discussed the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
    Two weeks ago (November 3-5), I attended the Cloud Expo Silicon Valley as a speaker, where I presented on the security and privacy due diligence requirements for cloud solutions. Cloud security is a topical issue for every CIO, CISO, and technology buyer. Decision-makers are always looking for insights on how to mitigate the security risks of implementing and using cloud solutions. Based on the presentation topics covered at the conference, as well as the general discussions heard between sessio...
    IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
    No hype cycles or predictions of zillions of things here. IoT is big. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, Associate Partner at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He discussed the evaluation of communication standards and IoT messaging protocols, data analytics considerations, edge-to-cloud tec...
    DXWorldEXPO LLC announced today that the upcoming DXWorldEXPO | CloudEXPO New York event will feature 10 companies from Poland to participate at the "Poland Digital Transformation Pavilion" on November 12-13, 2018.