如何在Shell脚本中管理日志详细程度? [英] How do I manage log verbosity inside a shell script?

查看:188
本文介绍了如何在Shell脚本中管理日志详细程度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很长的bash脚本,它会调用很多外部命令(git clonewgetapt-get等),这些命令会将很多内容打印到标准输出中.

I have a pretty long bash script that invokes quite a few external commands (git clone, wget, apt-get and others) that print a lot of stuff to the standard output.

我希望脚本具有一些详细信息选项,以便它可以打印外部命令中的所有内容,其摘要版本(例如,正在安装依赖项...",正在编译..."等),或者什么都不显示全部.但是,如何在不弄乱我所有代码的情况下做到这一点呢?

I want the script to have a few verbosity options so it prints everything from the external commands, a summarized version of it (e.g. "Installing dependencies...", "Compiling...", etc.) or nothing at all. But how can I do it without cluttering up all my code?

我已经考虑过可能的解决方案:一种是创建一个包装函数,该函数运行外部命令并根据开始时设置的选项将所需的内容打印到标准输出中.这些代码似乎更易于实现,但这意味着在代码中增加了很多额外的混乱.

I've thought about to possible solutions to this: One is to create a wrapper function that runs the external commands and prints what's needed to the standard output, depending on the options set at the start. This ones seems easier to implement, but it means adding a lot of extra clutter to the code.

另一种解决方案是将所有输出发送到几个外部文件,并在脚本开始时解析参数时,如果指定了详细程度,则对该文件运行tail -f.这将很容易实现,但对我来说似乎很棘手,我担心它的性能影响.

The other solution is to send all the output to a couple of external files and, when parsing the arguments at the start of the script, running tail -f on that file if verbosity is specified. This would be very easy to implement, but seems pretty hacky to me and I'm concerned about the performance impact of it.

哪个更好?我也欢迎其他解决方案.

Which one is better? I'm also open to other solutions.

推荐答案

您已经有了问题中最干净的主意(包装函数),但您似乎认为这很麻烦.我建议你重新考虑.可能看起来像以下内容(不一定是完整的解决方案,仅是为了提供基本概念):

You already have what seems to be the cleanest idea in your question (a wrapper function), but you seem to think it would be messy. I would suggest you reconsider. It could look like the following (not necessarily a full-fledged solution, just to give you the basic idea) :

#!/bin/bash

# Argument 1 : Logging level for that command
# Arguments 2... : Command to execute
# Output suppressed if command level >= current logging level 
log()
{
if
  (($1 >= logging_level))
then
  "${@:2}" >/dev/null 2>&1
else
  "${@:2}"
fi
}

logging_level=2

log 1 command1 and its args
log 2 command2 and its args
log 3 command4 and its args

您可以安排在包装函数中处理任何必需的重定向(如果需要,可以使用文件描述符),以便其余脚本保持可读性,并且不受所选记录级别的重定向和条件限制.

You can arrange for any required redirection (with file descriptors if you want) to be handled in the wrapper function, so that the rest of the script remains readable and free from redirections and conditions depending on the selected logging level.

这篇关于如何在Shell脚本中管理日志详细程度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆