I will run the following script:
#!/bin/bash
./myprogram
#get exit code
exitvalue=$?
#log exit code value to /var/log/messages
logger -s "exit code of my program is " $exitvalue
But I don't want log message to be written in /var/log/messages
because I don't have root privileges. Instead I want it to be written to a file in my home directory: /home/myuser/mylog
How should I modify logger
command above?
Unfortunately, you can't.
The
logger
command is just a thin frontend for the system logger. This means that anything you feed to it goes right over tosyslogd
, which then does all sorts of processing (like adding timestamp, hostname, priority, tag etc.) as well as complex dispatching to various outlets (various files, sockets, other servers etc.).It even does bridge permission levels, so in your example you could still log to
syslog
oruser.log
, for instance, with no problem, even though you may not modify those files directly.If
logger
could log to a file directly, it would either be as dumb as a simple echo one-liner, or would have to reimplement many of the message processing duties done by syslog. Either way, that would be a bad idea.It would be much better if the standard syslog interface had a way to specify an ad-hoc outlet parameter (like a filename) along with the message, so one could log to custom files without reconfiguring the system (which normal users have no permission to do anyway).
You'll need to change your syslog configuration if you want it to log things to other places. You could establish a certain facility that has an output file in your home directory, for example. You would need to be root to do that, though.
I don't think you really need to (or want to) involve
logger
/syslog
for this. Simply replace the last line of the script with:I think your better choice would be to use the
date
command rather thenlogger
in cases where you don't want to write to the syslog files (and don't have privs to do so).See "timestamp before an echo" for details on how to use
date
to prefix a message with a date and write it to a file.You create a bash function that looks like the following, adjusting the
date
format string to get what you want:In your bash script, you would then use:
Which would put the following in your
${LOGFILE}
file:If you want to use
logger
so that the message appears both in the system logs and in some file of yours, you might dosince the
-s
option tologger
also outputs on stderr which is redirected to the file with2>