pythonlogginglog-level

Python different log level for outputfile an terminal


Is there a way, without using an external module, to set the logging level for terminal output to info, and the logging level for writing a *.log to warning?

Why do I ask? I have a script that will run over a long period of time. Therefore I want to see in the terminal that my code is still running, but don't want to get all the info stuff inside the *.log file. Only if the logging level is 30 or higher it should print to my logging file.


Solution

  • This is pretty standard logging configuration. Just create a logger and add a streamhandler with info level and a filehandler with error level.

    import logging
    
    fh = logging.FileHandler('logs.txt')
    fh.setLevel(logging.ERROR)
    
    sh = logging.StreamHandler()
    sh.setLevel(logging.INFO)
    
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    logger.addHandler(fh)
    logger.addHandler(sh)
    
    logger.info('this is only on console')
    logger.error('this is in file too')