Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I log to a specific file in linux using logger command?

Tags:

bash

logging

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?

like image 502
alwbtc Avatar asked Nov 16 '12 19:11

alwbtc


People also ask

How to use Linux logger command?

Linux logger Command Usage Tutorial with Examples 1 logger Command Syntax 2 Linux Syslog 3 Print Logs From Syslog 4 Add Log To Syslog File 5 Specify Log Priority or Facility 6 Use TCP As Syslog Protocol 7 Redirect Command Output As Log 8 Log Specified File 9 Set or Limit Log Size 10 Ignore Blank or Empty Lines

How do I add a log file in Linux?

The logger command provides an easy way to add messages to the /var/log/syslog file from the command line or from other files. The Linux logger command provides an easy way to add log files to /var/log/syslog — from the command line, from scripts, or from other files.

How to view Linux logs?

Use the following command to see the log files: To view the logs, type the following command: This will display all the Linux log files such as kern.log, and boot.log. These files contain the necessary information for the proper function of the operating system.

How do I log a message in Linux?

You can log a messages string on the command line or provide a file as input that can contain the message to be logged.


2 Answers

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:

echo "Exit code of my program is $exitvalue" >> /some/file/that/you/can/write/to
like image 140
twalberg Avatar answered Sep 20 '22 06:09

twalberg


If you want to use logger so that the message appears both in the system logs and in some file of yours, you might do

  logger -s your message 2> $HOME/somefile

since the -s option to logger also outputs on stderr which is redirected to the file with 2>

You could want to use 2>> $HOME/somefile to append (not overwrite) your $HOME/somefile (read about bash redirections), and (see logger(1) for details) you may prefer to pass the program option --id=$$ to logger.

like image 43
Basile Starynkevitch Avatar answered Sep 17 '22 06:09

Basile Starynkevitch