如何在日志文件中打印命令行本身以进行日志跟踪?

时间:2019-06-17 14:09:16

标签: batch-file

我有一个通过.bat文件调用的Java代码。该批次工作正常。有什么方法可以将我正在执行的命令行打印到stdout(log)文件中?

例如,我的命令是

call dpp.bat -r %BASE_URL% views -af xyz.csv >> creation.log 2>&1

在我的bat文件中,我有多种不同类型的多种命令。在执行该单个批处理文件时,所有内容都会被一个一个地执行,所有日志都将写入该单个文件creation.log。而且用户迷失了日志,哪个命令行执行了什么!

是否有一种简单的方法,例如添加一些行,该行也将命令行打印到日志文件中?

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您想将命令回显和命令输出都写入日志文件。

要实现此目的,您可以执行以下操作:

  • 将要登录的代码放入子程序,然后由call调用。
  • Redirect仅将call命令的输出输出到日志文件。
  • @echo off放入批处理文件的主要部分。
  • @echo on放入子例程。
  • 不要忘记将exit /B放在主要部分的末尾。

这里是一个例子:

@rem // Turn command echoes off in the main section:
@echo off
@rem // Redirect only the output of `call` to the log file:
call :SUB >> "creation.log" 2>&1
@rem // Terminate main section:
@exit /B

:SUB
    @rem // Turn command echoes on in the sub-section:
    @echo on
    @rem /* Place all command lines you want to log here;
    @rem    ensure NOT to precede these lines with `@`: */
    call dpp -r %BASE_URL% views -af xyz.csv
    @rem // Terminate sub-section:
    @exit /B

或者,您可以将每个命令放入仅迭代一次的for loop中:

@rem // Turn command echoes on:
@echo on
@rem // Place all command lines you want to log into `for` loops that iterate once:
@(for %%# in (.) do call dpp -r %BASE_URL% views -af xyz.csv) > "creation.log" 2>&1
@rem // Terminate script:
@exit /B

答案 1 :(得分:0)

实际上,这非常简单,只需输入echo %*,即可打印在命令行中传递的参数。