Log function.

I have to make a log function which will take any statement and write it to a file along with the time stamp.Right now I have the following code:

log()
{
 echo "`date` `hostname`: $1" >> logfile
}
 
echo "Some statement."
log  "Some statement."
 

This way I can see "Some statement." on my console and it will be written to logfile along with timestamp and hostname.

So is there any way to make that echo and log into one statement.
This seems to solve the issue:

log()
{
 echo "$1"
 echo "`date` `hostname`: $1" >> logfile
}
 
log  "Some statement."
 

Is there any other way?

The thing is I want "Some statement" displayed on console without timestamp and written to a file along with the timestamp.

Thanks in advance.

I think you would have to show us some sample of what you want, it is still confused in my mind...

Since you want two different outputs for console & log file then you do not have any other option other than using two echo statements.

But if your requirement is just one output, then have a look at tee command manual.

Its simple.Let's say we have some function log() .So when I do this:

log "Called log."

I want Called log. displyed on console and I want a log file in which the function makes an entry like this:

Wed Jan 30 23:25:02 MST 2013 : Called log.

I already have a code for log() function.

log()
{
 echo "$1"
 echo "`date` `hostname`: $1" >> logfile
}
 
log  "Some statement."

My question is can I have a log() function without using two seperate echo statements?

---------- Post updated at 01:29 AM ---------- Previous update was at 01:27 AM ----------

But I do want a timestamp in logfile, and displaying timestamp on console kinda feels bad.

You can - read man tee as bipinajith suggests.

Then you can do things like

echo "this will be displayed on my console, and will be appended to the log" | tee -a $somelog

But - as you want two different pieces of output (i.e. the console output does NOT contain date and hostname, but the log output does) you will need two separate statements, and tee will not work for you.

Cheers,
ZB

put the echo inside your function

log()
{
          echo "$1" 
          echo "`date` `hostname`: $1" >> logfile
} 
 
log  "Some statement."

I'm already using tee -a .But it doesn't help me in this case.So I think its better to use two dihhrent statements,I guess.:frowning:

$ echo "`date` `hostname`: $1" | tee -a logfile | awk '{$1=$2=$3="";$0=$0;$1=$1}1'
1 Like