This repository has been archived by the owner on Jan 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog_monitor.php
193 lines (152 loc) · 6.34 KB
/
log_monitor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
<?php
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
date_default_timezone_set('UTC');
include 'vendor/autoload.php';
$scanMode = INI_SCANNER_NORMAL;
if (version_compare(PHP_VERSION, '5.6.1') >= 0) {
$scanMode = INI_SCANNER_TYPED;
}
$commando = new \Commando\Command();
// Define CLI Args
$commando->option('l')
->aka('logname')
->describedAs('Single Log file to check. Must include full path. Will override the logfile Array found in the config.')
->must(function ($filename)
{
return file_exists($filename);
});
$commando->option('g')
->aka('glob')
->describedAs('Single filepath pattern to check. Will override the globList Array found in the config.');
$commando->option('t')
->aka('to')
->describedAs('Email address to send the log to if it has changed. Will append this email to the list in the array');
$commando->option('a')
->aka('age')
->describedAs('Age in seconds. Monitored files *NEWER* than this age will be emailed. (Will override value in config file.)');
$commando->option('o')
->aka('overrideTo')
->describedAs('Boolean. All other arguments are overrides, but by default --to is additive. Set this to true to make it override. NB: if --to is not also set this option does nothing.')
->boolean()
->default(false);
$commando->option('c')
->aka('config')
->describedAs('Full or Relative path to config file. A config file is INI based see ./sample.config.ini for an example. Defaults to \'config.ini\' in the log monitor directory.')
->default('config.ini');
$config = parse_ini_file($commando['config'],true,$scanMode);
if (!empty($commando['logname'])) {
$config['log_list']['logs'] = array($commando['logname']);
}
if (!empty($commando['glob'])) {
$config['log_list']['globList'] = array($commando['glob']);
}
if (!empty($commando['to'])) {
$config['mailer']['to'][] = $commando['to'];
if ($commando['overrideTo']) {
$config['mailer']['to'] = array($commando['to']);
}
}
if (!empty($commando['age'])) {
$config['log_list']['age'] = $commando['age'];
}
$now = new DateTime;
// Age in seconds.
$allowedAge = $config['log_list']['age'];
$logFiles = array();
// List of log files to monitor.
$filenames = $config['log_list']['logs'];
// Add in any files found via globbing:
$globList = $config['log_list']['globList'];
if (!empty($globList)) {
foreach ($globList as $globPattern) {
foreach (glob($globPattern, GLOB_BRACE) as $fileNamePath) {
if (file_exists($fileNamePath)) {
$filenames[] = $fileNamePath;
}
}
}
}
/**
* A Closure to send the email with any attachments.
*
* @param $attachments array
*/
$sendMail = function ($attachments) use ($now, $config)
{
$logger = new Logger('mailError');
$logger->pushHandler(new StreamHandler(__DIR__ . 'LogMonitor.log', Logger::INFO));
if (!empty($attachments)) {
$hostname = gethostname() ? : php_uname('n');
$subject = '[Log Monitor][' . $hostname . '] ' . $now->format('Y-m-d H:i:s O');
$message = 'This email was generated by the Log File Monitor running on ' . $hostname . '. The attached file(s) have changed within the set timeframe. This report was generated at ' . $now->format('Y-m-d H:i:s O') . '.';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = $config['mailer']['host']; // Specify main and backup SMTP servers
$mail->SMTPAuth = $config['mailer']['auth']; // Enable SMTP authentication
$mail->Username = $config['mailer']['username']; // SMTP username
$mail->Password = $config['mailer']['password']; // SMTP password
$mail->SMTPSecure = $config['mailer']['secure']; // Enable TLS encryption, `ssl` also accepted
$mail->Port = $config['mailer']['port']; // TCP port to connect to
$from = (!empty($config['mailer']['fromAddress']) ? $config['mailer']['fromAddress'] : $config['mailer']['username']);
$fromName = (!empty($config['mailer']['fromName']) ? $config['mailer']['fromAddress'] : '');
$mail->setFrom($from, $fromName);
foreach ($config['mailer']['to'] as $address) {
$mail->addAddress($address);
}
$replyTo = (!empty($config['mailer']['replyAddress']) ? $config['mailer']['replyAddress'] : null);
if (!is_null($replyTo)) {
$replyName = (!empty($config['mailer']['replyName']) ? $config['mailer']['replyName'] : '');
$mail->addReplyTo($replyTo, $replyName);
}
$mail->isHTML(true);
$message .= '<br>' . PHP_EOL;
$message .= 'Attachments:<br>'. PHP_EOL;
$message .= '<ul>'.PHP_EOL;
$attachList = [];
foreach ($attachments as $attachment) {
$attached = $mail->addAttachment($attachment->fullPath, $attachment->filename);
if ($attached) {
if (!in_array($attachment->fullPath, $attachList)) {
$message .= '<li>' . $attachment->fullPath . '</li>' . PHP_EOL;
}
$attachList[] = $attachment->fullPath;
}
}
$message .= '</ul>';
$mail->Subject = $subject;
$mail->Body = $message;
// TODO: Since echo isn't helpful during a cron (it is written to /var/spool/mail/[user] we should investigate a better alert for errors in sending.
if(!$mail->send()) {
$logger->error('Message could not be sent.');
$logger->error('Mailer Error: ' . $mail->ErrorInfo);
$logger->info($message);
} else {
$logger->info('Message has been sent');
$logger->info($message);
}
}
};
/**
* Closure to verify the age of a log file and add it to the attachment list if too recent.
*
* @param $filename string
*/
$verifyAndAttachLog = function ($filename) use (&$logFiles, $allowedAge)
{
if (file_exists($filename)) {
$rightNow = time();
$fileTime = filemtime($filename);
$fileAge = $rightNow - $fileTime;
if ($fileAge <= $allowedAge) {
$fileData = new stdClass;
$fileData->filename = basename($filename) . '-' . date('YmdHisO',$rightNow) . '.log';
$fileData->fullPath = $filename;
$logFiles[] = $fileData;
}
}
};
foreach ($filenames as $filename) {
$verifyAndAttachLog($filename);
}
$sendMail($logFiles);