bash - The Best Elegant way to disable log file

最后都变了- 提交于 2019-12-11 22:26:57

问题


dear friends and colleges

the following code , is the basic concept of my log file in my bash script

this Code help me to understand each step in my bash script or in case we need to make troubleshooting

but some times I want to disable the Log creation because we not need the log and want to make the script more efficiency ( call to Log function each line in the script take time and make the script more heavy )

so my question my friends:

What the best elegant way to disable the log file?

Until now I disabled the log function by return inside my log function

But this solution not so good because I still call the function

 LOG=/tmp/BACKUP_PROCCESS.log
 LOG_DISABLE=FALSE
  MY_LOG ()
  {
   [ $LOG_DISABLE = TRUE ] && return
   echo "[`date +%d"/"%b"/"%G"-"%T`] INFO $1" >> $LOG
   }
   MY_LOG "START TO BACKUP FILES UNDER /VAR/LOG"

回答1:


Some would want to insert a condition checking everytime the logging function is called:

function log {
   if <not disabled>; then
       <show message>
   fi
}

And some like me would prefer removing any action to the function:

function log {
    :
}

This is what I do in my logging function.




回答2:


You could set your $LOG variable to /dev/null, which would cause the logs to go nowhere instead of into a file.

LOG_DISABLE=FALSE
if [[ $LOG_DISABLE = "TRUE" ]]; then
    LOG=/dev/null
fi

/dev/null is very fast so I wouldn't expect this to have any major performance disadvantages over your solution of returning from the function early.




回答3:


You can use some file descriptor redirections:

#!/bin/sh

log()
{
    echo >&3 $@
}

# Redirect all fd 3 in the file test.log
exec 3>$HOME/test.log

log this should be print

# Redirect all fd 3 in /dev/null
exec 3>/dev/null

log this sould not be print

and you will have in the file test.log

this should be print



回答4:


My way:

LOG_DISABLE="FALSE"
if [ $LOG_DISABLE = "TRUE" ]; then
   MY_LOG(){
      true
   }
else
   MY_LOG(){
      echo "[`date +%d"/"%b"/"%G"-"%T`] INFO $1" >> $LOG
   }
fi

Just defining the function differently based on the flag. You will call the function either way but I hope true is a quick builtin ;)




回答5:


I have smart solution to disable the log file

example ,

   unset  -f  MY_LOG
   shopt -s expand_aliases
   alias MY_LOG=true

the command unset disable the MY_LOG function

and I add alias MY_LOG to true command

the meaning of that is very time when MY_LOG will activate, actually it will activate the true command , and true command not really do anything



来源:https://stackoverflow.com/questions/24008629/bash-the-best-elegant-way-to-disable-log-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!