tylerhayes.tools
Class Log

java.lang.Object
  extended by tylerhayes.tools.Log

public class Log
extends java.lang.Object

The Log Class defines an object that logs messages to a log file. The user of the Log object can either specify their own file name and path, or use the default file name given by the default Constructor Log().

In addition, the user can switch over to a new file during the use of the Log object, if, for example, the file is growing too large by using the setFile(String) method, or the setFileDefault() method. The latter is if you want the Log object to create the default file name for you (using the current directory and current time).

By default, Log only outputs to the log file, but the user can have it also output to stdout--either all messages (excluding the header and footer) or only error messages. This can be done using the enableStdoutForAll() and enableStdoutForErrorsOnly() methods.

INDICATORS

The Log object writes its messages with indicators. These indicators are two-character strings that prepend the logged messages to make it easier to locate certain kinds of messages when reading the log file.
Here is an example of a log file with the message indicators:

CURRENT URL ID: 1347
    __ Parsing page contents...
    ~~ WARNING: server was redirected.
    ## link found: "http://link"
    ** ERROR: could not save link in database.
    !! FATAL ERROR: IOException caught

The Constructors set the indicators to the following default values:

General messages: "__"
Error messages: "**"
Fatal error messages: "!!"
Warning messages: "~~"
Data value messages: "##"
Kill message: "XX"

The user can, however, set their own indicator values by calling any of the set[indicator] methods, such as setDataIndicator(String).

The user also has the option of not using indicators at all, in which case one would call disableIndicators(). If the user wanted to turn the use of indicators back on, a call to enableIndicators() would set the indicators back to whatever they were before the call to disableIndicators(). There is also the option of resetting the indicators to their default values with a call to resetIndicators().

To use custom indicators, one would call the logGeneralMessageWithoutIndicator(String, int, boolean) method and simply include the indicator within the message being passed in. For example, if one was logging a web crawler and wanted an indicator for logging every link extracted from each web page, the above method could be called like so: logObj.logGeneralMessageWithoutIndicator("-> Link extracted: " + link, 2, true);, where "-> " is the indicator. Unfortunately, you will have to include that indicator every time you want to use it.


Constructor Summary
Log()
          Creates a Log object that writes to a default log file.
Log(java.lang.String fileName)
          Creates a Log object that writes to the file given as the parameter, fileName.
Log(java.lang.String fileName, boolean append)
          Creates a Log object that appends to the file given as the parameter, fileName.
 
Method Summary
 void close()
          Properly closes the resources used with the Log object--in this case just a private BufferedWriter object used to write to the specified file.
 void close(java.lang.String footerText)
          This version of close() takes a String parameter that is passed to logFooter(String) so that a footer is output to the file before closing.
 void disableIndicators()
          Turns off the use of message indicators.
 void disableStdoutForAll()
          Disables the directing of messages to stdout.
 void enableIndicators()
          Turns the use of indicators back on (they are on by default).
 void enableStdoutForAll()
          Enables the output of all logged messages (excluding header and footer) to be directed to stdout as well as the log file.
 void enableStdoutForErrorsOnly()
          Enables the output of error messages to be directed to stdout as well as the log file.
 void logData(java.lang.String message, int tabs, boolean usingTime)
          Logs a data message to the log file.
 void logError(java.lang.String message, int tabs, boolean usingTime)
          Logs an error message to the log file.
 void logFatalError(java.lang.String message, int tabs, boolean usingTime)
          Logs a fatal error message to the log file.
 void logFooter(java.lang.String footerText)
          Outputs a formatted footer marking the end of a log session.
 void logGeneralMessage(java.lang.String message, int tabs, boolean usingTime)
          Logs a general message to the log file.
 void logGeneralMessageWithoutIndicator(java.lang.String message, int tabs, boolean usingTime)
          Logs a general message to the log file without an indicator.
 void logHeader(java.lang.String headerText)
          Outputs a formatted header marking the beginning of the log session.
 void logKill(int tabs, boolean usingTime)
          Logs that the program has been killed.
 void logTimestamp(int tabs)
          Logs the current timestamp to the log file.
 void logWarning(java.lang.String message, int tabs, boolean usingTime)
          Logs a warning message to the log file.
 void resetIndicators()
          Resets the indicator values to the default values:
 void setDataIndicator(java.lang.String indicator)
          Sets the data message indicator.
 void setErrorIndicator(java.lang.String indicator)
          Sets the error message indicator.
 void setFatalIndicator(java.lang.String indicator)
          Sets the fatal error message indicator.
 void setFile(java.lang.String fileName)
          Sets the Log object to write to the given file.
 void setFileAppend(java.lang.String fileName)
          Sets the Log object to write to the given file for appending.
 void setFileDefault()
          Sets the Log object to write to a log file with a default file name.
 void setGeneralIndicator(java.lang.String indicator)
          Sets the general message indicator.
 void setKillIndicator(java.lang.String indicator)
          Sets the kill message indicator.
 void setTabSize(int size)
          Sets the tab size (number of spaces) for message indentation.
 void setWarningIndicator(java.lang.String indicator)
          Sets the warning message indicator.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Log

public Log()
Creates a Log object that writes to a default log file. The default file is placed in the current directory and named "[current timestamp].log". The timestamp is of the format: MM-DD-YYYY_[time in milliseconds].

Example: 8-20-2010_1282332840418.log for a log file created on August 20th, 2010, at around 12:34 pm.

By default, output will only be directed to the log file. If you would like to also output the log messages to stdout (either all messages, or only error messages), use the enableStdoutForAll() or enableStdoutForErrorsOnly() methods.


Log

public Log(java.lang.String fileName)
Creates a Log object that writes to the file given as the parameter, fileName. If the file already exists, the original file will be overridden, so be careful.

If you wish to append to the given file, use the following Constructor, Log(String, boolean).

By default, output will only be directed to the log file. If you would like to also output the log messages to stdout (either all messages, or only error messages), use the enableStdoutForAll() or enableStdoutForErrorsOnly() methods.

Parameters:
fileName - A String for the path and filename of the log file.

Windows example (forward slashes need escaping): "C:\\dir\\program.log"
Unix/Linux example ('~' means home directory): "~/logfiles/program.log"

To create the log file in the current directory, just give a name without the system-specific slashes, e.g. "filename.log".


Log

public Log(java.lang.String fileName,
           boolean append)
Creates a Log object that appends to the file given as the parameter, fileName.

By default, output will only be directed to the log file. If you would like to also output the log messages to stdout (either all messages, or only error messages), use the enableStdoutForAll() or enableStdoutForErrorsOnly() methods.

Parameters:
fileName - A String for the path and filename of the log file.
append - A boolean specifying whether or not to append to the file given as fileName. This should always be true, because if you do not want to append, then just use the previous Constructor, Log(String).
Method Detail

close

public void close()
Properly closes the resources used with the Log object--in this case just a private BufferedWriter object used to write to the specified file.


close

public void close(java.lang.String footerText)
This version of close() takes a String parameter that is passed to logFooter(String) so that a footer is output to the file before closing. This is just a shortcut for having to call logFooter(String), followed by close()

Parameters:
footerText - Text to be placed inside the footer block.

setFile

public void setFile(java.lang.String fileName)
Sets the Log object to write to the given file. Since all constructors instantiate a BufferedWriter object to a file, these setFile methods first close that BufferedWriter object before instantiating a new one to the file given.

The purpose of these setFile methods is to give the caller the option of switching to a new file, if, for example, the file it was previously writing to was getting substantially large.

Parameters:
fileName - A String representing the file to write the log entries to.

NOTE: if the file already exists, the original file will be written over and lost, so be careful.

If you would like to append to a file use the setFileAppend(String) method. There is also a Constructor to set up the given file for appending: Log(String, boolean).

See Also:
Log(), Log(String), Log(String, boolean), setFileAppend, setFileDefault

setFileAppend

public void setFileAppend(java.lang.String fileName)
Sets the Log object to write to the given file for appending. The only difference between this method and setFile(String) is that this method sets the BufferedWriter for appending rather than implicitly writing over the file if it already exists. If you don't care about writing over the file, you should just call setFile(String).

The purpose of these setFile methods is to give the caller the option of switching to a new file, if, for example, the file it was previously writing to was getting substantially large.

Parameters:
fileName - A String representing the file to append the log entries to.

NOTE: there is also a Constructor, Log(String, boolean), that initializes the BufferedWriter for appending.

See Also:
Log(), Log(String), Log(String, boolean), setFile, setFileDefault

setFileDefault

public void setFileDefault()
Sets the Log object to write to a log file with a default file name. The default file name is of the form MM-DD-YYYY_[current time in milliseconds].log and is placed in the current directory (where the program .class file resides).

Example: 8-20-2010_1282332840418.log for a log file created on August 20th, 2010, at around 12:34 pm.

This is usually only used when the Log object was first constructed with the default Constructor, Log().

The purpose of these setFile methods is to give the caller the option of switching to a new file, if, for example, the file it was previously writing to was getting substantially large.

See Also:
Log(), Log(String), Log(String, boolean), setFile, setFileAppend

setTabSize

public void setTabSize(int size)
Sets the tab size (number of spaces) for message indentation. Indenting certain messages can really make the log file more organized and more readable--especially when logging activities within nested loops.

NOTE: the constructors set the tab size to 4 as the default.

Parameters:
size - The number of spaces to use for indenting.

NOTE: The tab size will be set to zero for any integer passed in that is less than or equal to zero. On the flip side, 25 is the maximum (although I can't imagine wanting a tab size bigger than 8 or possibly 12), so the tab size will be set to 25 for any integer passed in that is greater than or equal to 25.


setGeneralIndicator

public void setGeneralIndicator(java.lang.String indicator)
Sets the general message indicator.

Parameters:
indicator - A String representing the message indicator.

setDataIndicator

public void setDataIndicator(java.lang.String indicator)
Sets the data message indicator.

Parameters:
indicator - A String representing the message indicator.

setWarningIndicator

public void setWarningIndicator(java.lang.String indicator)
Sets the warning message indicator.

Parameters:
indicator - A String representing the message indicator.

setErrorIndicator

public void setErrorIndicator(java.lang.String indicator)
Sets the error message indicator.

Parameters:
indicator - A String representing the message indicator.

setFatalIndicator

public void setFatalIndicator(java.lang.String indicator)
Sets the fatal error message indicator.

Parameters:
indicator - A String representing the message indicator.

setKillIndicator

public void setKillIndicator(java.lang.String indicator)
Sets the kill message indicator.

Parameters:
indicator - A String representing the message indicator.

logHeader

public void logHeader(java.lang.String headerText)
Outputs a formatted header marking the beginning of the log session. This is especially useful when the Log object is appending to a file, so that one can easily spot the beginnings of each logging session. When the Log is not appending this will always just be at the top of the file.

The header looks like this:

================================================================================
==                           {headerText centered}                            ==
================================================================================

It is 80 characters wide, and 3 lines, followed by an empty line.

Parameters:
headerText - Text to be placed inside the header block.
See Also:
logFooter

logFooter

public void logFooter(java.lang.String footerText)
Outputs a formatted footer marking the end of a log session. This is especially useful when the Log object is appending to a file, so that one can easily spot the beginnings and endings of each logging session. When the Log is not appending this will always just be at the bottom of the file, unless the program terminated unexpectedly and was not able to output a footer.

This is a wrapper for logHeader.

The footer looks like this:

================================================================================
==                           {footerText centered}                            ==
================================================================================

It follows an empty line, and is 80 characters wide, and 3 lines long.

Parameters:
footerText - Text to be placed inside the footer block.
See Also:
logHeader

logGeneralMessage

public void logGeneralMessage(java.lang.String message,
                              int tabs,
                              boolean usingTime)
Logs a general message to the log file. A "general" message is basically one that is not data, an error, nor a warning.

The given message will be prepended by the general message indicator (indicators are described in the opening description of the Log Class). If you do not want the indicator to be logged with the message, you can set it to the empty string ("") by calling setGeneralIndicator(String), disabling all indicators by calling disableIndicators(), or, in this case, calling logGeneralMessageWithoutIndicator(String, int, boolean).

By default, the indicator for this type of message is "__".

All of these log methods require the number of tabs to indent and whether or not to prepend the entry with a timestamp (in addition to the message itself).

Parameters:
message - The message to log (following the indicator).
tabs - The number of tabs to indent the message. The indentation begins after the timestamp if a timestamp is to be included.
usingTime - true will cause a timestamp to be output before the message, and false will not.

logGeneralMessageWithoutIndicator

public void logGeneralMessageWithoutIndicator(java.lang.String message,
                                              int tabs,
                                              boolean usingTime)
Logs a general message to the log file without an indicator. This gives you the option of using your own indicators. Simply include them at the beginning of the messages you pass in.

All of these log methods require the number of tabs to indent and whether or not to prepend the entry with a timestamp (in addition to the message itself).

Parameters:
message - The message to log.
tabs - The number of tabs to indent the message. The indentation begins after the timestamp if a timestamp is to be included.
usingTime - true will cause a timestamp to be output before the message, and false will not.

logData

public void logData(java.lang.String message,
                    int tabs,
                    boolean usingTime)
Logs a data message to the log file. A "data" message is primarily used to output values of one or more variables. For example, if you want to know the value of the i variable in a for loop, you should log it with this method to distinguish the log entry from another type of message.

The given message will be prepended by the data message indicator (indicators are described in the opening description of the Log Class). If you do not want the indicator to be logged with the message, you can set it to the empty string ("") by calling setDataIndicator(String), or disabling all indicators by calling disableIndicators().

By default, the indicator for this type of message is "##".

All of these log methods require the number of tabs to indent and whether or not to prepend the entry with a timestamp (in addition to the message itself).

Parameters:
message - The message to log (following the indicator).
tabs - The number of tabs to indent the message. The indentation begins after the timestamp if a timestamp is to be included.
usingTime - true will cause a timestamp to be output before the message, and false will not.

logWarning

public void logWarning(java.lang.String message,
                       int tabs,
                       boolean usingTime)
Logs a warning message to the log file. A "warning" message is something worthy of attention--could be bad, could be irrelevant.

The given message will be prepended by the warning message indicator (indicators are described in the opening description of the Log Class). If you do not want the indicator to be logged with the message, you can set it to the empty string ("") by calling setWarningIndicator(String), or disabling all indicators by calling disableIndicators().

By default, the indicator for this type of message is "~~".

All of these log methods require the number of tabs to indent and whether or not to prepend the entry with a timestamp (in addition to the message itself).

Parameters:
message - The message to log (following the indicator).
tabs - The number of tabs to indent the message. The indentation begins after the timestamp if a timestamp is to be included.
usingTime - true will cause a timestamp to be output before the message, and false will not.

logError

public void logError(java.lang.String message,
                     int tabs,
                     boolean usingTime)
Logs an error message to the log file. An "error" message indicates that something wrong has occurred, but not too bad that the program should terminate as a result. you could call this a "soft" error.

The given message will be prepended by the error message indicator (indicators are described in the opening description of the Log Class). If you do not want the indicator to be logged with the message, you can set it to the empty string ("") by calling setErrorIndicator(String), or disabling all indicators by calling disableIndicators().

By default, the indicator for this type of message is "**".

All of these log methods require the number of tabs to indent and whether or not to prepend the entry with a timestamp (in addition to the message itself).

Parameters:
message - The message to log (following the indicator).
tabs - The number of tabs to indent the message. The indentation begins after the timestamp if a timestamp is to be included.
usingTime - true will cause a timestamp to be output before the message, and false will not.

logFatalError

public void logFatalError(java.lang.String message,
                          int tabs,
                          boolean usingTime)
Logs a fatal error message to the log file. A "fatal error" message shows that a critical error has occurred causing the program to terminate. Of course, this method does not actually terminate the program--that is up to the caller, but this method should not be called if the caller does not intend to terminate the program shortly after (it wouldn't be a fatal error, otherwise).

The given message will be prepended by the fatal error message indicator (indicators are described in the opening description of the Log Class). If you do not want the indicator to be logged with the message, you can set it to the empty string ("") by calling setFatalIndicator(String), or disabling all indicators by calling disableIndicators().

By default, the indicator for this type of message is "!!".

All of these log methods require the number of tabs to indent and whether or not to prepend the entry with a timestamp (in addition to the message itself).

Parameters:
message - The message to log (following the indicator).
tabs - The number of tabs to indent the message. The indentation begins after the timestamp if a timestamp is to be included.
usingTime - true will cause a timestamp to be output before the message, and false will not.

logTimestamp

public void logTimestamp(int tabs)
Logs the current timestamp to the log file. When logging messages with timestamps, the timestamp always comes first--at the start of a new line. This method, however, can be used to simply log a timestamp without an indicator or message, with any amount of indentation.

Parameters:
tabs - The number of tabs to indent before logging the timestamp.

logKill

public void logKill(int tabs,
                    boolean usingTime)
Logs that the program has been killed. It does not distinguish what killed the program, however, just that it has been killed. Of course, in order to use this practically, your program needs some sort of signal handling mechanism to intercept the kill signal. As of the time of this writing (Aug, 2010), this proved helpful: Do a Graceful Shutdown of Your Java-Application. NOTE: the approach given in that article does not catch the signal caused when clicking the "Terminate" button in Eclipse. It will catch CTRL-C when running through a command-line.

Unlike most of the other log methods, this one does not take a String as an argument for a caller-defined message. The kill message is always:

Program has been killed.

and the default indicator is "XX".

Parameters:
tabs - The number of tabs to indent before logging the kill message.
usingTime - true will cause a timestamp to be output before the message, and false will not.

disableIndicators

public void disableIndicators()
Turns off the use of message indicators. What this actually does is simply change all of the private indicators to the empty string (after saving the current values in case the caller wants to turn them back on).

See Also:
enableIndicators

enableIndicators

public void enableIndicators()
Turns the use of indicators back on (they are on by default). This returns the indicator values back to waht they were before the call to disableIndicators(). A call to this before without ever calling disableIndicators() does nothing (but waste cycles).


resetIndicators

public void resetIndicators()
Resets the indicator values to the default values:

General messages: "__"
Error messages: "**"
Fatal error messages: "!!"
Warning messages: "~~"
Data value messages: "##"
Kill message: "XX"


enableStdoutForAll

public void enableStdoutForAll()
Enables the output of all logged messages (excluding header and footer) to be directed to stdout as well as the log file.

NOTE: a client may accidentally enable stdout for both all messages and error messages by calling both this method and enableStdoutForErrorsOnly(). Log does not prevent this from happening. However, doing so does not output error messages twice--it only has the same effect of this method.


enableStdoutForErrorsOnly

public void enableStdoutForErrorsOnly()
Enables the output of error messages to be directed to stdout as well as the log file.

NOTE: a client may accidentally enable stdout for both all messages and error messages by calling both this method and enableStdoutForAll(). Log does not prevent this from happening. However, doing so does not output error messages twice--it only has the same effect of enableStdoutForAll().


disableStdoutForAll

public void disableStdoutForAll()
Disables the directing of messages to stdout. If output to stdout was never enabled, then this call has no effect. If all messages were enabled to be output to stdout, but it is now desired to only direct errors to stdout, then a call to this method followed by a call to enableStdoutForErrorsOnly() will do the job.