Php log

Uit De Vliegende Brigade
Naar navigatie springen Naar zoeken springen is a simple script, included in the usual GitHub repository: It reduces file /var/log/php_error.log to its 100 last lines and deleted the rest.

Why a script?

Effectively, it's only 2 lines long. Then why turn this into a script?

  • I wouldn't be able to memorize it, or easily reproduce it myself - And why would I?
  • It's rather critical code. I rather once take the time to do it right, rather than everytime hurringly give it a change
  • I probably need this functionality at critical moments. Like when a database server is down due to storage issues - Not the moment to develop critical code.
  • It's probably code that I don't need very regularly, so I wouldn't memorize stuff
  • However, memorizing stuff sometimes works really better. Like memorizing the shebang or the MediaWiki code for including an image or creating a table - Quite tiring to have my working flow interrupted by having to look up something.

Script vs. alias

I could have turned this into an alias rather than a script. Considerations:

  • The more it looks like a 'real' program, the more a script is preferred
  • In this case, it's only 2 lines, but I find the comments quite important
  • It has a parameter in it + maybe some comments about it
  • I tend to overlook aliases as a source of real functionality; The usual GitHub repository is a more obvious and intuitive place for me to look for stuff
  • Easier to distribute: this one GitHub repository is intended to be available on all servers + some workstations (where relevant). Alias need to be created on each computer (in each account, if relevant)

Script - Programming considerations

What I like about the script below:

  • It's really short - Just two lines
  • It's pure Bash, not using sed or any other tools
  • Simple & intuitive, not using commands that I'm unfamiliar with and that might have issues, like truncate or fallocate - It wouldn't be bad at all to learn about these commands, but there seem to issues with [1]
  • Something that's new for me and I quite happy to now have learn about: sudo sh -c instead of just sudo.

sudo subshell

This was my initial approsch. It gave an error:

$ sudo tail -n 10 /var/log/php_errors.log > /var/log/php_errors.tmp.log

-bash: /var/log/php_errors.tmp.log: Permission denied

The "Permission denied" error occurs because the user executing the command does not have the necessary write permissions to create or modify files in the /var/log directory. When using sudo, only the command itself is run with elevated permissions, but the redirection part (> /var/log/php_errors.tmp.log) is still executed with the user's permissions.

To solve this, you need to run the entire command with sudo. You can achieve this by using a subshell with sudo:

sudo sh -c 'tail -n 10 /var/log/php_errors.log > /var/log/php_errors.tmp.log'