如何制作Makefile来将命令及其输出记录到文件中? [英] How do I make a Makefile to log both command and its output to a file?
问题描述
我想将命令及其输出都记录到日志文件中.看起来很容易.只需将stdout重定向到日志文件即可.
I want to log both the command and its output to a log file. It seems easy. Just redirect stdout to the log file.
myrule:
mycommand >> logfile
但这仅记录命令的输出.不是命令本身.
我还会回显命令并将该输出重定向到日志文件吗?
But this only logs the output of the command. Not the command itself.
Do I also echo the command and redirect that output to the log file?
myrule:
@echo mycommand >> logile
mycommand >> logfile
这种"mycommand"的重复看起来不好,并且占用了食谱中的空间.尤其是食谱长的时候.
This duplication of 'mycommand' doesn't look good and it takes up space in the recipe. Especially if the recipe is long.
我应该创建一个函数并为我要记录的每个命令调用它吗?
Should I create a function and call it for every command I want to log?
define log_and_run
@echo $(1) >> logfile
$(1) >> logfile
endef
myrule:
$(call log_and_run,mycommand)
现在,我不必重复"mycommand".但是现在,"mycommand"在配方中变得不那么明显了.注意是在呼叫"上,而不是在"mycommand"上.
Now I don't have to duplicate 'mycommand'. But now 'mycommand' is less visible in the recipe. Attention is on the 'call', not on 'mycommand'.
如果'mycommand'是这样的话
And what if 'mycommand' is something like
$(CC) -o $@ -Wl,--linkeroption $<
在调用"log_and_run"时,逗号会将命令分为两个参数.
The comma will split the command into two arguments when calling 'log_and_run'.
有人对此有一个解决方案,可以不引起人们的注意,而可以处理任意命令吗?
Does anybody have a solution for this that doesn't take attention away from the commands and works for arbitrary commands?
推荐答案
也许让外壳程序完成所有繁重的工作吗?IE.像这样的东西:
Let the shell do all the heavy lifting, maybe? I.e. something like this:
.PHONY: all myrule myrule-with-macro
all: myrule myrule-with-macro
mycommand = echo "Running $@..."
myrule:
(set -x; $(mycommand)) >>$@.log 2>&1
define log_and_run
(set -x; $(1)) >>$@.log 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...
这篇关于如何制作Makefile来将命令及其输出记录到文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!