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

时间:2015-03-09 14:06:25

标签: python logging pyftpdlib

我试图在测试期间使用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()

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

2 个答案:

答案 0 :(得分:0)

因此,在挖掘代码后,我发现了以下提示:

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

现在,有文件记录,但控制台记录将无法启动。

答案 1 :(得分:0)

这样的事情:

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的记录转到文件。从模块到控制台的一切。其中一个关键是传播!