TweetFollow Us on Twitter

Oct 01 Adv WebObjects

Volume Number: 17 (2001)
Issue Number: 10
Column Tag: Advanced WebObjects 5

Part 2 - Using the Log

by Emmanuel Proulx

WebObject's powerful logging API

Why Logging?

Sometimes you can't use a debugger. For example, when an obscure problem happens only on the server, and that machine doesn't have the development environment installed. In that case, you want to use logging.Ê

You don't have to be desperately seeking a bug to use logging; you could just need to keep a trace of the events of the application, for bookkeeper purposes. Or you might want to log a function that is behaving properly, just in case it has a change of heart. Whatever the reason, it is important to know how it is done.

Before we start, you might want to go back and add toString() functions to all your custom classes, so you will be able to print them out to the log.

Sending Values to the Log

The logging system in WebObjects is very powerful and comprehensive. All the message logging is done through the class NSLog. This class lets you log events two ways:

  • Sending values to the output, error or debug logging objects. This uses the same mechanism as System.out and System.err.
  • Sending output to a custom logger.

A third way of using NSLog is to enable logging on subsystems of WebObjects, as covered in a subsequent section.

The easiest way to use logging is simply to call these methods from anywhere in the code:

Function: NSLog.out.appendln(v)
  • Parameters: 1: The value to send to the output stream. If it is not a String already, this function will transform the value into a String.
    This function sends a value of any type (Object or base type) to the stdout output stream.
  • Function: NSLog.err.appendln(v) or NSLog.debug.appendln(v)
  • Parameters: 1: The value to send to the output stream. If it is not a String already, this function will transform the value into a String.
    This function sends value of any type (Object or base type) to the stderr error stream.

As a general rule, always write descriptive, helpful string containing the object and method that wrote the message, some debugging information, and if there was an exception thrown, the stack trace. To help you to extract the stack trace from an exception, simply call the following (very helpful) function:

Function: NSLog.throwableAsString(e)
Returns: String, the stack trace extracted from the exception.
Parameters: Throwable e: The exception containing the stack trace to extract.
This function extracts the stack trace from any kind of exception and returns it as a String.   

As an example, the following piece of code catches an exception, writes out useful information and the stack trace to the error log:

Listing 1. stackTraceExample()

This code sample is an example of using NSLog to send an error message to the log. It also shows how to 
print the stack trace to a String.

    public String stackTraceExample() {
        String result = "Welcome to this experiment... ";
        try  {
            result += "Doing something that may " + 
                "throw an exception. ";
            // ...
            throw new Exception("An error has occurred.");
        } catch (Exception e) {
            result += " An exception has occurred! ";
            NSLog.err.appendln("Class Main method " +
                "stackTraceExample() has thrown: " +
                e.toString() + ". STACK TRACE: " +
                NSLog.throwableAsString(e) ); 
            result += " Error logged and stack printed.";

        }
        return result;
    }

Verbose Mode

By default, NSLog sends messages to the log without any details about the context in which the message was send. But sometimes it doesn't give enough information to be able to track problems properly. This is why I recommend turning on the verbose mode. It is off by default. When it is on, the verbose mode prints more information before writing out the log message:

  • the time at which the message was sent to the log
  • the name of the current thread

To turn on the verbose mode globally in an application, simply call this method from the Application.main():

Function: NSLog.out.setIsVerbose(b) or 
NSLog.debug.setIsVerbose (b) or
NSLog.debug.setIsVerbose (b)

Parameters: boolean b: if true, then verbose mode is turned on. If false, it is turned off (the default).
This function lets you turn on and off the verbose mode for (respectively) the output log, 
the error log and the debug log.   

An example of this will be shown momentarily.

The log file will then be more crowded, but you never know when this extra information may be of assistance.

Redirecting the Logs to Files

Sending out anything to the stderr or stdout may be pretty much useless unless there is a way to capture all that information and see it later. By default, the log messages are not sent anywhere except to the console.

This piece of code shows how to redirect each logging object to a file.

Listing 1. logToAFileExample()

This code sample is an example of using NSLog to send an error message to a file.

    public String logToAFileExample() 
        throws FileNotFoundException {
        String result = "Another experiment... ";

        result += "Setting up the file. ";
        PrintStream ps = new PrintStream(
            new FileOutputStream("/tmp/a2log.txt",true)); 
        NSLog.PrintStreamLogger logFile = 
            new NSLog.PrintStreamLogger(ps); 
        NSLog.setOut(logFile); 

        result += "Writing a message. ";
        NSLog.out.appendln("Logging this message! " +
            new java.util.Date() );
        result += "Look at the file /tmp/a2log.txt. ";
        return result;
    }

Note that the file here is appended to, not overwritten. This means the log files can fill up the hard drive at one point. It is good practice to use different log files (e.g. one per day) and to have a procedure to archive log files and free up hard disk space regularly.

Another good practice is not to hardcode the folder names, but rather to get this as a property. This is also more portable, as you'd configure it differently for each platform, and even for each computer on which the application is deployed.

The example shown at the end of this section sets the three logs in the same file, under the folder specified as the system property "logfolder". I suggest you set this to the folder /var/log on the Mac OS X. Make sure that the user has write access to that folder. On other platforms, you may set this to an appropriate folder.

Turning Logging On and Off

Logging is on by default, but you may turn it off by calling this function:

Function: NSLog.out.setIsEnabled(b) or NSLog.debug.setIsEnabled (b) or NSLog.debug.setIsEnabled (b)
Parameters: boolean b: if true (the default), then the logging is on. If false, it is turned off.

This function lets you turn on and off the logging for (respectively) the output log, the error log and the debug log.   

I do not see why you would do something such as this, but hey, it's available.

WebObjects Subsystems Logging

Also, NSLog lets you control the type of information you wish to see from existing subsystems of WebObjects. You have the ability to decide which groups of related events will go to the log. You also have the ability to get only those events that are of a certain level of importance.

Group selection

A group is a category of messages. Each group corresponds to one subsystem within WebObjects. There are 25 different default groups. NSLog lets you decide which groups should log events, and which should be ignored. Manipulating groups is done with these methods:

Function: NSLog. setAllowedDebugGroups(g)
Parameters: long g: The bit mask that represents the groups that should log events.
This function replaces the bit mask for selecting the groups that should log events. Each bit is a 
different group. The accepted groups are listed below. The previous groups will be discarded.   

Function: NSLog. allowDebugLoggingForGroups(g)
Parameters: long g: The bit mask that represents the new groups that should log events.
This function adds the specified bits to the bit mask for selecting the groups that should log 
events. Each bit is a different group. The accepted groups are listed below. The previous groups will 
be preserved.   

Function: NSLog. refuseDebugLoggingForGroups(g)
Parameters: long g: The bit mask that represents the groups that should not log events.
This function removes the specified bits from the bit mask for selecting the groups that should log 
events. Each bit is a different group. The accepted groups are listed below. The bits that are not set 
will be preserved. To turn off all groups, simply call 

NSLog.refuseDebugLoggingForGroups(~0).   

Because of space restrictions, we won't show a complete list of the default groups. But one is available here:

http://developer.apple.com/techpubs/webobjects/FoundationRef/Java/Classes/NSLog.html#CAJEHBJJ

The most obvious example of a category of events is the SQL and database access. You often want to see the generated SQL statements and know when and why the database is being accessed. To turn on the database-related groups, simply call these:

NSLog.allowDebugLoggingForGroups
                                       (NSLog.DebugGroupSQLGeneration);
NSLog.allowDebugLoggingForGroups
                                    (NSLog.DebugGroupDatabaseAccess);

You may even create your own group simply by declaring a constant and assigning it existing groups. Combine the groups with the bitwise OR operator:

public final long DATABASEGROUP = NSLog.DebugGroupSQLGeneration | NSLog.DebugGroupDatabaseAccess;

Then use your new group the same way you use the NSLog groups:

NSLog.allowDebugLoggingForGroups(AClass.DATABASEGROUP);

Level selection

Throughout all WebObjects subsystems, you can filter out messages based on their level of importance. Some messages are more important (error messages) and some are less (informational messages). The method that sets the level is NSLog.setAllowedDebugLevel(int), which takes one of these 4 levels as a parameter:

  • NSLog.DebugLevelOff (0): This basically disables all messages.
  • NSLog.DebugLevelCritical (1): This displays only the error messages.
  • NSLog.DebugLevelInformational (2): This displays error messages, and some relevant messages.
  • NSLog.DebugLevelDetailed (3): This displays all messages, including many irrelevant ones.

    WARNING: Using NSLog.DebugLevelDetailed will greatly slow down the execution of your application. Avoid using it.


    Source Code Management

    What is SCM?

    Source Code Management (SCM) software help multiple developers that work on the same application, by taking care of concurrency and tracking file version history. The Project Builder has integrated support for one SCM product called CVS (Concurrent Version System). This product is popular on Unix platforms, and is installed with Mac OS X.

    Setting Up SCM

    Before starting to use SCM, you must set up a CVS repository (and usually also a server). Once those are set up, the next step is to create a blank folder that will serve as the root of all your projects (in this book, the root folder is ~/projects). Assume the CVSROOT environment variable is already set.

    • If the project you are working on is not yet in the repository, you must first put it there. This can be achieved by entering this command in a Terminal window (suppose you are working on vendor 1.0, release 1.0 of your application):
    cd ~projects
    cvs import Find-A-Luv V1_0 R1_0
    

    If you're going work with an existing project, you must first obtain it from the repository. You have to do that using the shell. Open a Terminal window and enter these commands:

    cd ~
    cvs co projects/Find-A-Luv
    

    Once either of these steps is executed, CVS is set up properly to work with WebObjects. Look in your project's folder and you will see some folders named "CVS".

    WARNING: Don't erase any CVS folders! If you do, then CVS will cease to work. If this happens to you, back up any modified code (without the CVS folders), then do a checkout (cvs co ...). Copy the backed up code on top of the old one you just got.

    You may now open your project with the Project Builder. Look at the menu SCM; all of its items are now available. The Project Builder has become aware of the CVS folders and can make use of the repository.

    Status of Files

    When SCM is enabled, you can see the status of the files in your project by looking in the file browser tab. A new column has appeared, displaying the state of all files. In this example, a little "M" means the file has been modified:

    You may synchronize the status column with the current status of the repository by selecting menu SCM | Refresh Status. If someone has modified a file, or if there's a conflict, you will see right away.

    Getting the Latest Version

    Suppose someone else has modified a file and you still have the older version. You must get the latest version. To do that, simply go to menu SCM | Update to Latest Revision. The Project Builder will transfer the file and display it instead of the old one.

    Committing Changes

    When you change a file, you must commit it before others can see your modifications. To do this, open menu SCM | Commit Changes. A dialog will pop up. Enter the description of the changes you applied. Click Commit.

    Adding Files

    After adding any files (using menu File | New File for example) don't forget to add the files in the repository. You may do so simply by following these steps:

    • Select the new file, folder or group
    • Go to menu SCM | Add to Repository.
    • The files are marked as being new, but are not added yet. To add, select the file, folder or group again and go to menu SCM | Commit Changes. You will be asked to enter a description.
    • The project itself is modified when you add files. Select the project in the file browser (first item) and go to menu SCM | Commit Changes.

    NOTE: Once the changes to the project are committed, there is no way to know if a file was added to the repository already or not. Don't forget to add new files to the repository. If you do, all other developers will get compilation errors because the files are missing on their computers.

    Comparing and Merging

    In the situation where a file is marked as being modified, you may want to see what was modified before committing it. In order to do that, you need some way to see the difference between your version of the file and the one in the repository. The menu SCM | Compare with Base does exactly that. It brings up a utility called FileMerge, which shows you the repository version on the left side, and the latest version on the right side. This is quite handy.

    Another situation may arise, in which the version in the repository is newer than the one you modified. Meaning someone modified and committed the file at the same time you were modifying your version of the file. The two versions need to be consolidated. FileMerge can help in this task, by showing you both versions of the file, and letting you merge the two versions into a newer, better third version. To do just that, you have to open menu SCM | Compare/Merge with Latest Revision.

    The FileMerge utility is out of the scope of this book, but you may learn all about it by checking out its online help.

    Version History

    You can see the list of versions of a file by clicking on it (or on the project) in the file browser, and pressing (-I (Inspector). Then click on the tab marked "SCM".

    From this same window, you can select multiple versions and view their differences, by clicking on the Compare button.

    PREFERENCES: SCM can be turned off and configured by going to menu Project Builder | Preferences, under the CVS Access category.


    I recommend using NSLog.DebugLevelDetailed only .in a production environment, and NSLog.DebugLevelInformational in a development environment.

    Setting Logging From the Command-Line

    Having the logging settings hardcoded in the source code may not be ideal. If you want to change the settings, you have to rebuild the application. The logging level and groups can also be set from a parameter of WebObjects applications. The logging level can be set using the parameter "DNSDebugLevel", and the logging groups using "DNSDebugGroups". The value of these parameters is the same as the value of the NSLog constants:

    Logging level: 0 (disables), 1, 2, 3 (all messages),
    Logging groups: an integer value obtained by adding the values of the wanted groups. For example, if 
    you want to use NSLog.DebugGroupSQLGeneration (bit number 17) and NSLog.DebugGroupDatabaseAccess (bit 
    number 16), you will specify 216 + 217 = 196608.
    

    But where do you specify this? You have two choices: in the Project Builder (when running interactively), and in your own script (when running in the background).

    In the Project Builder, simply go to the main target's settings, under the category Executable and then Arguments. Add these two arguments:

    DNSDebugLeve=2
    NDSDebugGroups=196608
    

    If you're using a shell script, then you must add these two arguments in it. Say your application's name is "Logging-Example-a2", then locate the place where your application is executed, and add them. Here's an example:

    cd ~/ Logging-Example-a2/build/Logging-Example-a2.woa
    ./Logging-Example-a2 -DNSDebugLevel=2 -DNSDebugGroups=196608
    

    Don't forget though that changing the level or groups programmatically of will override these settings.


    Emmanuel Proulx is a Course Writer, Author and Web Developer, working in the domain of Java Application Servers. He can be reached at emmanuelp@theglobe.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.