If you are familiar with the Unix command line and shell scripting, then you will be right at home using the OS X Terminal, and can throw together a number of scripts to automate routines, and customize a number of functions on your Mac. When creating your scripts, as is common practice, you might wish to log various actions and activity, and while you might consider doing so in classic ways, there is an easy approach to simply log messages to the OS X system console.
The classic approach to logging behavior is to use a simple redirect to a designated log file, where you can quickly create such a file and tack on messages to it using the greater-than character, such as the following:
echo "my message" > /Library/Logs/mylog.log
To append data to an existing log instead of replacing the current file, simply use two greater-than symbols:
echo "my message" >> /Library/Logs/mylog.log
- Piping command output to logger
echo "my message" | logger
- Logging specific phrases
logger "my message"
Finally, if you want to output messages to the console in addition to redirecting them to your own log files, you can do so by using the “-s” flag for the logger command, which will have it show in the console but also output it to standard output so you can redirect it elsewhere. For instance, the following two commands will both output to the console and append the output to a specified log file:
echo "my message" | logger -s >> /Library/Logs/mylog.log
logger -s "my message" >> /Library/Logs/mylog.log
Easy as falling off a Log! :groan:
i have found very useful the * tee * command. so itwill show up in terminal and get logged to a file of your choice
Very nice tip. I had no idea about the logger command, nor the tee command mentioned by venicejeff.
logger does have a small inconvenience for me and probably for others: it writes the message to the System Log, which is fine except for the fact that only administrators can read the System Log. So for example if you are testing a shell script that is run by regular users and reports its outcome via logger, you need to switch to an admin account in order to see the report.
That is inconvenient for those of us who chose to run day-to-day operations in non-admin accounts, and furthermore is useless if you are running the script on a Mac for which you don’t have administrative privileges.
I wish you could choose the log file to write to.
if you want to be brutish, in my experience you can sudo write to any log you want — just like the text file that it is.
and i haven’t been in a situation where i couldn’t read logs, but i know i have changed permissions on log files so someone other than root can write to them. this was good for a user’s crontab or something along these lines. (this might need to be reapplied after a permissions repair command)