Search code examples
bashloggingsyslog

How to log messages to a log file in a specific path from a bash script


How do you log messages to a log file in a specific path from a bash script?

A naive implementation would be commands like:

echo My message >>/my/custom/path/to/my_script.log

But this probably has many disadvantages (no log rotation for example). I could use the 'logger' command, but it does not support logs in custom paths as far as I know and is not easy to configure if you have lots of bash scripts that could use a custom log file.

In a scripting language like Ruby all this is quite easy: https://github.com/rudionrails/yell/wiki/101-the-datefile-adapter I could also make my own logger command based on this ruby library and call it from my bash scripts, but I guess there is already a well known solution that provides similar behavior for shell scripts?


Solution

  • You can simply append text to a log file from a bash script in that way:

    echo "My message" >> /my/custom/path/to/my_script.log
    

    Rotation is handled by logrotate, you just need to add the settings to the .conf in /etc/logrotate.conf. The config is pretty self explanatory and the man page is also quite helpful, but in short if you want to rotate weekly and keep 4 weeks worth of logs in compressed format and create a new empty log as it rotates out the last, you would simply put in the .conf:

    /my/custom/path/to/my_script.log {
        rotate 4
        weekly
        create
        compress
        endscript
    }
    

    There are many other options you can check out at the man page (man logrotate) such as emailing the log files, executing commands on rotation, rotate when the files reach a certain size, etc.