python - 在 Python 中使用日志记录模块进行颜色记录

标签 python logging

让我们简化一下。我的目标是使用 logging 在终端中输出颜色Python 中的模块。我希望信息有一个绿色前缀,警告有一个黄色前缀,错误有一个红色前缀。为了简单起见,我们使用 *** 作为前缀,即

*** log text
*** another message with another prefix color

到目前为止我做了什么

# declaration of function (global scope)
log = None
warn = None
error = None 
def build_log_funcs():
    # why I initialize it inside the function ?
    # because script doesnt have to know about logging method
    # the function just provide log  functions
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)

    sh = logging.StreamHandler()
    # LOG_FORMAT just global variable with pattern including %(levelmarks)s
    # it will be replaced with ** with proper color 
    formatter = logging.Formatter(LOG_FORMAT)
    sh.setFormatter(formatter)
    logger.addHandler(sh)

    def make_log_func(func, color, is_exit = False):
        color_string = "\x1b[{};1m***\x1b[0m".format(color)
        def newfunc(*args, **kwargs):
            func(*args, extra={'levelmarks':color_string}, **kwargs)
            if is_exit:
                sys.exit(-1)

        return newfunc
    # 32, 33, 31 are color codes
    log = make_log_func(logger.info, 32)
    warn = make_log_func(logger.warning, 33)
    error = make_log_func(logger.error, 31, is_exit = True)

    return log, warn, error

并将其用作

log, warn, error = build_log_funcs()

它有效,但我不喜欢:(从小问题到大问题)

  1. 我隐藏了logging 模块的功能。例如启用/禁用调试消息
  2. 我应该在初始化之前使用函数的全局声明,因为我不能在声明之前调用函数。
  3. 阅读和维护代码太难了。我相信一切都应该尽可能简单。

为什么我不做简单的日志,警告,简单的功能?我不知道。 logging 是一个非常全面的模块,所以我将来可能会需要它的功能。

我的问题是您将如何解决这个问题?可能有一种我不知道的简单明显的方法。

最佳答案

感谢 Dominic Kexel this关联。我看到这个但没有注意答案。 以下代码或多或少适合我

def setup_logger(logger):
    logger.setLevel(logging.DEBUG)

    sh = logging.StreamHandler()
    formatter = logging.Formatter(LOG_FORMAT)
    sh.setFormatter(formatter)

    def decorate_emit(fn):
    # add methods we need to the class
        def new(*args):
            levelno = args[0].levelno
            if(levelno >= logging.CRITICAL):
                color = '\x1b[31;1m'
            elif(levelno >= logging.ERROR):
                color = '\x1b[31;1m'
            elif(levelno >= logging.WARNING):
                color = '\x1b[33;1m'
            elif(levelno >= logging.INFO):
                color = '\x1b[32;1m'
            elif(levelno >= logging.DEBUG):
                color = '\x1b[35;1m'
            else:
                color = '\x1b[0m'
            # add colored *** in the beginning of the message
            args[0].msg = "{0}***\x1b[0m {1}".format(color, args[0].msg)

            # new feature i like: bolder each args of message 
            args[0].args = tuple('\x1b[1m' + arg + '\x1b[0m' for arg in args[0].args)
            return fn(*args)
        return new
    sh.emit = decorate_emit(sh.emit)
    logger.addHandler(sh)

这里有一个缺陷:我无法控制 *** 在模式中的位置,但正如我所说,它是合适的。

关于python - 在 Python 中使用日志记录模块进行颜色记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20706338/

相关文章:

python - 在 matplotlib 中更改填充颜色

Python 字符串格式 - 限制字符串长度,但修剪字符串开头

python - PyGame 和 Unicode - 一个永无休止的故事

python - 带有 --python 标志的 mkvirtualenv 使用了错误的 python 版本

python - 登录django项目的最佳实践

java - 在 Java 中创建 XML 日志文件

hadoop - 在Hive UDF中记录消息

database - 你会在预写日志中记录什么?

Python IRC 客户端 : write from scratch or write plugin for existing framework?

python - 选择列具有最小值的 Pandas 数据框行