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.

    IoT & Smart Cities Stories
    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 ...
    SYS-CON Events announced today that DatacenterDynamics has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY. DatacenterDynamics is a brand of DCD Group, a global B2B media and publishing company that develops products to help senior professionals in the world's most ICT dependent organizations make risk-based infrastructure and capacity decisions.
    René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
    Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
    @DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time t...
    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...
    DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
    When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
    Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
    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...