In Linux, I know how to write a simply message to the /var/log/messages
file, in a simple shell script I created:
#!/bin/bash
logger "have fun!"
I want to stop throwing messages into the default /var/log/messages
file, and create my own.
I tried this:
#!/bin/bash
logger "have more fun" > /var/log/mycustomlog
It still logs to /var/log/messages
. It did create the /var/log/mycustomlog
, but it's empty.
Anyone see what I'm missing?
the shortcut is Ctrl + Shift + S ; it allows the output to be saved as a text file, or as HTML including colors!
logger
logs to syslog facilities. If you want the message to go to a particular file you have to modify the syslog configuration accordingly. You could add a line like this:
local7.* -/var/log/mycustomlog
and restart syslog. Then you can log like this:
logger -p local7.info "information message"
logger -p local7.err "error message"
and the messages will appear in the desired logfile with the correct log level.
Without making changes to the syslog configuration you could use logger
like this:
logger -s "foo bar" >> /var/log/mycustomlog
That would instruct logger
to print the message to STDERR as well (in addition to logging it to syslog), so you could redirect STDERR to a file. However, it would be utterly pointless, because the message is already logged via syslog anyway (with the default priority user.notice
).
@chepner make a good point that logger
is dedicated to logging messages.
I do need to mention that @Thomas Haratyk simply inquired why I didn't simply use echo
.
At the time, I didn't know about echo, as I'm learning shell-scripting
, but he was right.
My simple solution is now this:
#!/bin/bash
echo "This logs to where I want, but using echo" > /var/log/mycustomlog
The example above will overwrite the file after the >
So, I can append to that file with this:
#!/bin/bash
echo "I will just append to my custom log file" >> /var/log/customlog
Thanks guys!
/var/log/
, but I'm sure there are other good ideas out there. And since I didn't create a daemon, /var/log/
probably isn't the best place for my custom log file. (just saying)There's good amount of detail on logging for shell scripts via global varaibles of shell. We can emulate the similar kind of logging in shell script: http://www.cubicrace.com/2016/03/efficient-logging-mechnism-in-shell.html The post has details on introdducing log levels like INFO , DEBUG, ERROR. Tracing details like script entry, script exit, function entry, function exit.
Sample Log:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With