Python logging to stdout and log file

前端 未结 3 450
一个人的身影
一个人的身影 2021-02-07 00:34

I am fairly new in python and starting to get into the logging module. I would like to have the message logged into a log file and outputting to the console. The code below prin

3条回答
  •  盖世英雄少女心
    2021-02-07 01:22

    Expanding on @Brendan's answer.

    Your logger currently outputs to the console using a StreamHandler.

    By adding a FileHandler, you can log to a file.

    Each handler instance can be customized to have its own format and logging level.

    If you want to log using the same format, you will have to set the format on the new FileHandler as well.

    fh = logging.FileHandler(r'/path/to/log.txt')
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    

    Read more: Python logging cookbook

提交回复
热议问题