Skip to content

Commit 4a39af5

Browse files
committed
Logging functionality.
Logs to a JSON-serialised file, in two groupings: the first stores total counts of error messages, grouped by message; the second stores a chronological log of all entries.
1 parent 532cee8 commit 4a39af5

File tree

1 file changed

+54
-1
lines changed

1 file changed

+54
-1
lines changed

test/log.php

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,12 @@
88

99
define('IP_ADDRESS', $_SERVER['REMOTE_ADDR']);
1010

11+
if ( empty($_REQUEST['msg']) ) {
12+
die;
13+
}
14+
15+
$message = $_REQUEST['msg'];
16+
1117
// Initially, assume that this client hasn't logged anything in the last minute.
1218
$has_accessed = false;
1319

@@ -54,4 +60,51 @@ function($access) {
5460
// If the user has submitted a log in the last minute, bail out silently.
5561
if ( $has_accessed ) {
5662
die;
57-
}
63+
}
64+
65+
// Nonsense over! Let's log this baby.
66+
if ( !file_exists(LOG_FILE) ) {
67+
if ( is_writable(dirname(LOG_FILE)) ) {
68+
touch(LOG_FILE);
69+
} else {
70+
die;
71+
}
72+
}
73+
74+
$log = json_decode(file_get_contents(LOG_FILE));
75+
76+
if ( empty($log) ) {
77+
$log = (object) array(
78+
'incidence' => array(),
79+
'log' => array()
80+
);
81+
}
82+
83+
$entry = array(
84+
'time' => date('Y-m-d H:i:s'),
85+
'message' => $message,
86+
'hash' => sha1($message)
87+
);
88+
89+
$log_entry = json_encode($entry);
90+
91+
// First, increment our hitrate log for this entry.
92+
$incidence =& $log->incidence->{$entry['hash']};
93+
if ( !empty($incidence) ) {
94+
$incidence->count++;
95+
} else {
96+
$incidence = (object) array(
97+
'message' => $entry['message'],
98+
'count' => 1
99+
);
100+
}
101+
102+
// Now, insert a log entry.
103+
if ( empty($log->log) ) {
104+
$log->log = array();
105+
}
106+
107+
$log->log[] = $entry;
108+
109+
$json_log = json_encode($log);
110+
file_put_contents(LOG_FILE, $json_log);

0 commit comments

Comments
 (0)