我想将命令及其输出记录到日志文件中。看起来很容易。只需将标准输出重定向到日志文件即可。
myrule:
mycommand >> logfile
但这仅记录命令的输出。不是命令本身。
我是否还回显该命令并将输出重定向到日志文件?
myrule:
@echo mycommand >> logile
mycommand >> logfile
“mycommand”的重复看起来不太好,而且它占用了配方中的空间。特别是如果食谱很长。
我应该创建一个函数并为我想要记录的每个命令调用它吗?
define log_and_run
@echo $(1) >> logfile
$(1) >> logfile
endef
myrule:
$(call log_and_run,mycommand)
现在我不必重复“mycommand”。但现在“mycommand”在配方中不太明显了。注意“call”,而不是“mycommand”。
如果“mycommand”类似于
$(CC) -o $@ -Wl,--linkeroption $<
调用“log_and_run”时,逗号会将命令拆分为两个参数。
有没有人有一个解决方案,不会将注意力从命令上移开,并且适用于任意命令?
最佳答案
也许让 shell 完成所有繁重的工作? IE。像这样的东西:
.PHONY: all myrule myrule-with-macro
all: myrule myrule-with-macro
mycommand = echo "Running $@..."
myrule:
(set -x; $(mycommand)) >><a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0327432d6f6c64" rel="noreferrer noopener nofollow">[email protected]</a> 2>&1
define log_and_run
(set -x; $(1)) >><a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6541254b090a02" rel="noreferrer noopener nofollow">[email protected]</a> 2>&1
endef
myrule-with-macro:
$(call log_and_run,$(mycommand))
测试运行:
$ make
(set -x; echo "Running myrule...") >>myrule.log 2>&1
(set -x; echo "Running myrule-with-macro...") >>myrule-with-macro.log 2>&1
$ ls myrule*.log
myrule.log myrule-with-macro.log
$ cat myrule*.log
+ echo 'Running myrule...'
Running myrule...
+ echo 'Running myrule-with-macro...'
Running myrule-with-macro...
关于logging - 如何制作 Makefile 将命令及其输出记录到文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54933242/