How to write to a file, using the logging Python module?

后端 未结 9 2024
天涯浪人
天涯浪人 2020-11-27 10:34

How can I use the logging module in Python to write to a file? Every time I try to use it, it just prints out the message.

相关标签:
9条回答
  • 2020-11-27 10:59

    http://docs.python.org/library/logging.html#logging.basicConfig

    logging.basicConfig(filename='/path/to/your/log', level=....)
    
    0 讨论(0)
  • 2020-11-27 10:59

    Here is two examples, one print the logs (stdout) the other write the logs to a file:

    import logging
    import sys
    
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')
    
    stdout_handler = logging.StreamHandler(sys.stdout)
    stdout_handler.setLevel(logging.DEBUG)
    stdout_handler.setFormatter(formatter)
    
    file_handler = logging.FileHandler('logs.log')
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(formatter)
    
    
    logger.addHandler(file_handler)
    logger.addHandler(stdout_handler)
    

    With this example, all logs will be printed and also be written to a file named logs.log

    0 讨论(0)
  • 2020-11-27 11:00

    http://docs.python.org/library/logging.handlers.html#filehandler

    The FileHandler class, located in the core logging package, sends logging output to a disk file.

    0 讨论(0)
提交回复
热议问题