有选择地设置控制台日志记录级别

selectively setting the console logging level

我正在尝试在测试期间使用 FTP 服务器存根。我不想要控制台输出,但我想将日志记录捕获到文件中。

我希望 FTP 服务器在不同的进程中 运行,所以我使用多处理。

我的如下代码将所有日志记录设置为级别 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()

如何仅将控制台日志记录设置为 WARNING 级别,或者更好的是,在不放弃文件日志记录的情况下完全关闭?

所以,在深入挖掘代码后,我发现了以下提示:

# 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()

所以,我所要做的就是定义我自己合适的处理程序:

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

现在,有文件日志记录,但控制台日志记录不会启动。

像这样:

import logging

date_format = "%Y/%m/%d %H:%M:%S"
log_file_path = "my_file.txt"

root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)

# own_module_logger = logging.getLogger(__name__)
pyftpdlib_logger = logging.getLogger("pyftpdlib")

# Setup logging to file (Only pyftpdlib)
filehandler = logging.FileHandler(filename = log_file_path)
filehandler.setLevel(logging.DEBUG)
fileformatter = logging.Formatter(fmt = "%(asctime)s - %(levelname)-8s - %(name)s.%(funcName)s - %(message)s",
                                  datefmt = date_format)
filehandler.setFormatter(fileformatter)
pyftpdlib_logger.addHandler(filehandler)
pyftpdlib_logger.propagate = False

# Setup logging to console (All other)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
consoleformatter = logging.Formatter(fmt = "%(asctime)s - %(levelname)-8s - %(name)s.%(funcName)s - %(message)s",
                                     datefmt = date_format)
console.setFormatter(consoleformatter)
root_logger.addHandler(console)

# Do your loggings
a = logging.getLogger()
a.info('root I')
a.debug('root D')

b = logging.getLogger("pyftpdlib")
b.info('P I')
b.debug('P D')

logging.shutdown()

因此 pyftpdlib 的日志记录进入文件。从您的模块到控制台的一切。这里的关键之一是传播!