Search code examples
pythonloggingpyftpdlib

selectively setting the console logging level


I am trying to use an FTP server stub during tests. I don't want the console output, but I would like to capture the logging to a file.

I want the FTP server to run in a different process, so I use multiprocessing.

My code as follows sets all logging to level WARNING:

from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
import pyftpdlib.log as pyftpdliblog
import os
import logging
import multiprocessing as mp

authorizer = DummyAuthorizer()
authorizer.add_user('user', '12345', '.', perm='elradfmwM')
handler = FTPHandler
handler.authorizer = authorizer

pyftpdliblog.LEVEL = logging.WARNING
logging.basicConfig(filename='pyftpd.log', level=logging.INFO)
server = FTPServer(('', 2121), handler)

def main():
    p = mp.Process(target=server.serve_forever)
    p.start()


if __name__ == '__main__':
    main()

How do I set only the console logging to level WARNING, or even better, completely shutdown without giving up the file logging?


Solution

  • So, after digging inside the code, I found out the following hint:

    # This is a method of FTPServer and it is called before 
    # server.serve_forever
    def _log_start(self):
        if not logging.getLogger('pyftpdlib').handlers:
            # If we get to this point it means the user hasn't
            # configured logger. We want to log by default so
            # we configure logging ourselves so that it will
            # print to stderr.
            from pyftpdlib.ioloop import _config_logging
            _config_logging()
    

    So, all I had to do is to define my own appropriate handlers:

    logger = logging.getLogger('pyftpdlib')
    logger.setLevel(logging.INFO)
    hdlr = logging.FileHandler('pyftpd.log' )
    logger.addHandler(hdlr)
    

    Now, there is file logging, but console logging will not start.