I have a webserver with a git repo containing a website. I have made a CMS using PHP where PHP automatically commits to git when files are changed. I would like to track these commits (preferably in a form close to git log --name-status to show added/deleted files) using Logwatch. I have read about creating custom Logwatch services, but Logwatch is all really new to me and that didn't really get me anywhere.
- 175
- 4
1 Answers
Note: Instead of the PHP code below, if you wanted to track all git commits (and not only those committed using PHP), it should be possible to set up a post-commit hook with similar output.
Just after writing the question I came across this really simple guide. Based on that, here's what I did:
Create log directory and set permissions
I haven't tested this without setting permissions, but I assume it's needed.
sudo mkdir /var/log/gitweb
sudo chown: www-data /var/log/gitweb
PHP git log function
This line of code is run whenever I run git commit in the php code. Newlines are replaced with a custom string so that each commit is on its own line (as far as I know, Logwatch can only operate on a line-by-line basis). This will be replaced back with newlines when parsing with Logwatch.
shell_exec('(git log -1 --date=iso --name-status | awk 1 ORS="[NEWLINE_HERE]" ; echo) >> /var/log/gitweb/gitweb.log');
Logwatch log file group
# /etc/logwatch/conf/logfiles/gitweb.conf
LogFile = gitweb/*.log
Archive = gitweb/*.gz
*ExpandRepeats
Not really sure what *ExpandRepeats does, but it was in the guide I linked to.
Logwatch service
# /etc/logwatch/conf/services/gitweb.conf
Title = "Git commits"
LogFile = gitweb
Logwatch parser
This does two things:
- Time filtering (it only prints lines/commits with the correct date)
- Convert custrom string back to newlines (see the PHP code above)
I know absolutely zero perl (I looked at other Logwatch scripts for help), so I apologize if this is a sacrilege against all things perl-y.
use Logwatch ':dates';
my $filter = TimeFilter('%Y-%m-%d %H:%M:%S');
while (defined(my $ThisLine = <STDIN>)) {
if ($ThisLine =~ /$filter/) {
$ThisLine =~ s/\[NEWLINE_HERE\]/\n/g;
print $ThisLine;
}
}
exit(0);
Set up log rotation
# /etc/logrotate.d/gitweb
/var/log/gitweb/*log {
daily
# keep 10 old logs
rotate 10
# don't do anything if the log is missing
missingok
# don't do anything if the log is empty
notifempty
# zip the archived logs
compress
}
- 175
- 4