简体   繁体   English

为日志文件写头

[英]Writing a header for the log file

My logger looks like this: 我的记录器如下所示:

import logging

logfile = 'name.log'

formatter = logging.Formatter('%(asctime)s\t%(message)s')


def setup_logger(name, log_file, level=logging.INFO):


    handler = logging.FileHandler(log_file)
    handler.setFormatter(formatter)

    logger = logging.getLogger(name)
    logger.setLevel(level)
    logger.addHandler(handler)

    return logger

logger = setup_logger('first_logger', logfile)


logger.info("Col1: {}\t : Col2 {}\t Col3: {}".format(a, str(b), c))

The output looks like: 输出如下:

2018-01-01 19:03:23,126 Col1:106 Col2:"some string"  Col3: 12
2018-01-01 19:03:24,127 Col1:7676 Col2:"some string"  Col3: 80
2018-01-01 19:03:10,12  Col1:2 Col2:"some string"  Col3: 7

I would like to write the logger so that I get such an output format: 我想编写记录器,以便获得这样的输出格式:

Timestamp Col1 Col2 Col3
2018-01-01 19:03:23,126  106 "some string" 12
2018-01-01 19:03:24,127 7676 "some string"  80
2018-01-01 19:03:10,12  2 "some string"  7

So instead of logging key-values I would like to print the keys (column names) as a header. 因此,我不想记录键值,而是将键(列名)打印为标题。

Is it possible do to so? 有可能这样做吗?

I agree with Norrius that the logging might not be the right tool, but if you insist for whatever reason, you can log the header first, and then log only the values: 我同意Norrius的观点,即日志记录可能不是正确的工具,但是如果出于任何原因坚持执行,则可以先记录标头,然后仅记录值:

logger.info("Col1 Col2 Col3")

logger.info("{}\t {}\t {}".format(a, str(b), c))

Although this would log the timestamp at the header as well, so you need to play with the format between lines. 尽管这也会将时间戳记在标头中,但是您需要在行之间使用格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM