Insert time stamp in a log file

Hi,

I have the following script placed in hotplug directory. Is it possible add timestamp in the log file which creates and writes every time it runs?

#!/bin/sh
set -x
exec >>/root/logfiles/hotplug/Wan1.log 2>&1

if [ "${ACTION}" == "ifup" ] && [ "${INTERFACE}" = "Wan1" ]
then
do something
fi

thanks

You can use the "logger" command in scripts.

"-t XXX" is the item shown as the notice source:
user.notice ntpd:

Below is example from my build, where I use hotplug to log NTP events to system log:

root@router1:~# cat /etc/hotplug.d/ntp/20-ntpd-logger
#!/bin/sh
[ $ACTION = "step" ]    && logger -t ntpd Time set, stratum=$stratum interval=$poll_interval offset=$offset
[ $ACTION = "stratum" ] && logger -t ntpd Stratum change, stratum=$stratum interval=$poll_interval offset=$offset

The output in system log looks like:

root@router1:~# logread | grep ntp
Tue Mar 24 08:24:51 2020 user.notice ntpd: Time set, stratum=16 interval=32 offset=41280.463320
Tue Mar 24 08:24:52 2020 user.notice ntpd: Stratum change, stratum=3 interval=32 offset=-0.000191
Tue Mar 24 10:17:57 2020 user.notice ntpd: Stratum change, stratum=4 interval=512 offset=0.007282
Tue Mar 24 10:26:39 2020 user.notice ntpd: Stratum change, stratum=3 interval=512 offset=0.002756
Tue Mar 24 11:46:07 2020 user.notice ntpd: Stratum change, stratum=4 interval=1024 offset=0.008404
Tue Mar 24 12:01:00 2020 user.notice ntpd: Stratum change, stratum=3 interval=1024 offset=0.002724
1 Like

hi hnyman,

I don't want to use the system's logging. Instead I want to have a specific log file for each script.

How I can alter the script using logger to write on specific log file and have the timestamp?

Maybe by using date?

Hi Tmomas,

date sounds good and in fact I tried that and played around but below you can see an example in the output of the script in the log file when it runs.

root@HyperGW:~# cat /root/logfiles/hotplug/Wan1.log 
+ '[' ifdown '==' ifup ]
+ date
Wed Mar 25 00:24:16 EET 2020
+ '[' ifup '==' ifup ]
+ '[' Wan1 '=' Wan1 ]
+ jsonfilter -e '@["ipv4-address"][0].address'
+ ubus call network.interface.Wan1 status
+ INET=172.16.100.2
+ uci set 'openvpn.Wan1.local=172.16.100.2'
+ uci commit openvpn
+ /etc/init.d/openvpn restart Wan1
+ date
Wed Mar 25 00:24:20 EET 2020
+ '[' ifdown '==' ifup ]
+ date
Wed Mar 25 00:24:20 EET 2020

No matter where I use the date it pops up in the log several times and that because of the transitions that the interface goes. So my idea was to have something at the start and at the end of the log.

------ START of log "date" ---------- 
output
------ END of log "date" ----------

Or something on each line. I might missing something.

CDBU=$(date +"%F_%H%M%S")