简体   繁体   中英

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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