Problem

You want to log user activity or errors in a text file.

Solution

Use the StanfordLogFile class to log messages to a file. Each log entry is automatically populated with the date and time, remote host IP, script name, and query string. Log files are stored in CSV format for easy parsing.

Warning about AFS performance

AFS, the file system used at Stanford, is not suitable for reliable high-volume reading and writing of files, such as in the case of a log. For all mid-to-high traffic sites, we recommend logging to a database table. If you do not have access to a database and do not experience heavy spikes in traffic, StanfordLogFile is a suitable alternative.

Basic usage

Include the class and initialize it with the path to the log file to which to append. Call append to save a new message to the file.

Truncating the log

To truncate the log to zero length, call the truncate function.

// Truncate the log$log->truncate();

Adding logging capabilities to StanfordApp

You may attach a StanfordLog object to StanfordApp by calling the function set_logger, as shown below. Then, you may call $app->log() in the same manner that you would call $log->append(). Using StanfordApp to manage logging may be desirable for aesthetic purposes and storage type independence, since it is easy to swap out a different type of logging object if a change is necessary in the future.

// Include StanfordApp and StanfordLogFileinclude_once("stanford.app.php");
include_once("stanford.log.file.php");
// Create a new app$app = new StanfordApp();
// Create a new log$log = new StanfordLogFile("/path/to/file.log");
// Attach logger to app$app->set_logger($log);
// Append a message to the log file$app->log("a message");

// Include StanfordTextFileinclude_once("stanford.textfile.php");
// Create new StanfordTextFile and point it to the log file$data = new StanfordTextFile("/path/to/file.log");
// Set file has headings to false since the log file does not have headings on the first line$data->set_file_has_headings(false);
// Set field names (each parameter corresponds, in order, to the columns in the log file)$data->set_field_names("log_time","remote_addr","script","query_string","message");
// Sort by timestamp, newest first$data->sort_by("log_time", StanfordData::DESCENDING);
// Limit to 20$data->set_limit(20);
// Display table$data->display_as_html_table();