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
    "We've been engaging with a lot of customers including Panasonic, we've been involved with Cisco and now we're working with the U.S. government - the Department of Homeland Security," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
    "We provide IoT solutions. We provide the most compatible solutions for many applications. Our solutions are industry agnostic and also protocol agnostic," explained Richard Han, Head of Sales and Marketing and Engineering at Systena America, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
    SYS-CON Events announced today that Calligo, an innovative cloud service provider offering mid-sized companies the highest levels of data privacy and security, 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. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalised support service from its globally located cloud plat...
    Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
    "The Striim platform is a full end-to-end streaming integration and analytics platform that is middleware that covers a lot of different use cases," explained Steve Wilkes, Founder and CTO at Striim, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
    SYS-CON Events announced today that DXWorldExpo has been named “Global 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. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
    SYS-CON Events announced today that Datera, that offers a radically new data management architecture, 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. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
    "We are focused on SAP running in the clouds, to make this super easy because we believe in the tremendous value of those powerful worlds - SAP and the cloud," explained Frank Stienhans, CTO of Ocean9, Inc., in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
    DX World EXPO, LLC., a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
    "MobiDev is a Ukraine-based software development company. We do mobile development, and we're specialists in that. But we do full stack software development for entrepreneurs, for emerging companies, and for enterprise ventures," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
    While the focus and objectives of IoT initiatives are many and diverse, they all share a few common attributes, and one of those is the network. Commonly, that network includes the Internet, over which there isn't any real control for performance and availability. Or is there? The current state of the art for Big Data analytics, as applied to network telemetry, offers new opportunities for improving and assuring operational integrity. In his session at @ThingsExpo, Jim Frey, Vice President of S...
    SYS-CON Events announced today that DXWorldExpo has been named “Global 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. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
    In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
    SYS-CON Events announced today that EnterpriseTech has been named “Media 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. EnterpriseTech is a professional resource for news and intelligence covering the migration of high-end technologies into the enterprise and business-IT industry, with a special focus on high-tech solutions in new product development, workload management, increased effic...
    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 Cloud Academy named "Bronze Sponsor" of 21st International Cloud Expo which will take place October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara, CA. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud com...
    SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, 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. Cloudistics delivers a complete public cloud experience with composable on-premises infrastructures to medium and large enterprises. Its software-defined technology natively converges network, storage, compute, virtualization, and ...
    SYS-CON Events announced today that CHEETAH Training & Innovation 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. CHEETAH Training & Innovation is a cloud consulting and IT training firm specializing in improving clients cloud strategies and infrastructures for medium to large companies.
    SYS-CON Events announced today that Datanami has been named “Media 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. Datanami is a communication channel dedicated to providing insight, analysis and up-to-the-minute information about emerging trends and solutions in Big Data. The publication sheds light on all cutting-edge technologies including networking, storage and applications, and thei...
    The current age of digital transformation means that IT organizations must adapt their toolset to cover all digital experiences, beyond just the end users’. Today’s businesses can no longer focus solely on the digital interactions they manage with employees or customers; they must now contend with non-traditional factors. Whether it's the power of brand to make or break a company, the need to monitor across all locations 24/7, or the ability to proactively resolve issues, companies must adapt to...