0%

Linux_log重定向添加时间戳

执行Linux命令时,log重定向时在每行前面加入时间戳信息。

命令如下:

1
2
3
4
5
6
7
8
# 加入时间戳,直接输出到控制台
<command> | ts "[%d-%m-%y] %H:%M:%.S"

# 加入时间戳,输出到控制台,同时重定向到指定log
<command> | ts "[%d-%m-%y] %H:%M:%.S" 2>&1|tee <rel.log>

# log输出到控制台,加入时间戳重定向到指定log
<command> 2>&1|tee >(ts "[%d-%m-%y] %H:%M:%.S" > <rel.log>)

参数说明:

  • command: 运行的命令
  • rel.log: log重定向的文件

注:ts是timestamp的缩写,使用ts命令需要安装moreutils包。ts是一个脚本,也可以从已安装的机器中复制/usr/bin/ts来使用。

测试效果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
$ cat test.sh
#!/bin/bash

count=0

while true; do
count=$((count+1))
echo "count: ${count}"
sleep 1
done

$ ./test.sh | ts "[%y-%m-%d] %H:%M:%.S"
[23-08-15] 09:10:04.574804 count: 1
[23-08-15] 09:10:05.558411 count: 2
[23-08-15] 09:10:06.559441 count: 3
^C

$ ./test.sh | ts "[%y-%m-%d] %H:%M:%.S" 2>&1|tee 1.log
[23-08-15] 09:10:17.630634 count: 1
[23-08-15] 09:10:18.613956 count: 2
[23-08-15] 09:10:19.615041 count: 3
^C

$ cat 1.log
[23-08-15] 09:10:17.630634 count: 1
[23-08-15] 09:10:18.613956 count: 2
[23-08-15] 09:10:19.615041 count: 3

$ ./test.sh 2>&1|tee >(ts "[%d-%m-%y] %H:%M:%.S" > 2.log)
count: 1
count: 2
count: 3
^C

$ cat 2.log
[15-08-23] 09:10:28.792188 count: 1
[15-08-23] 09:10:29.773346 count: 2
[15-08-23] 09:10:30.774403 count: 3
-------------本文结束 感谢阅读-------------
赏☕