基于参数的Python双重日志记录 [英] Python dual logging based on an argument

查看:92
本文介绍了基于参数的Python双重日志记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据提供的参数将日志记录到文件日志以及控制台.

I'm trying to get logging to the file log as well to the console based on provided argument.

该部分的代码如下:

logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s")
_logger = logging.getLogger(__name__)

fileHandler = logging.FileHandler("{0}/{1}.log".format(logPath, fileName), mode='a')
fileHandler.setLevel(logging.DEBUG)
fileHandler.setFormatter(logFormatter)
_logger.addHandler(fileHandler)

def parse_args(args):
    parser = argparse.ArgumentParser(
        description="My Script")
    parser.add_argument(
        "-v",
        "--verbose",
        dest="loglevel",
        help="set loglevel to INFO",
        action="store_const",
        const=logging.INFO)
    parser.add_argument(
        "-vv",
        "--very-verbose",
        dest="loglevel",
        help="set loglevel to DEBUG",
        action="store_const",
        const=logging.DEBUG)
    return parser.parse_args(args)

def setup_logging(loglevel):
    logformat = "%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s"
    logging.basicConfig(level=loglevel, stream=sys.stdout, format=logformat, datefmt="%Y-%m-%d %H:%M:%S")

def main(args):
    args = parse_args(args)
    setup_logging(args.loglevel)
    _logger.info("Script starts here")
    """main code"""
    _logger.info("Script ends here")

def run():
    """Entry point for console_scripts
    """
    main(sys.argv[1:])

if __name__ == "__main__":
    run()

当我运行带有-v-vv参数的脚本时,它运行良好,但是当我希望随时将所有日志保存在那里时,也不创建提供者日志文件.

it will works fine when I run script with -v or -vv argument but when is not provider log file is not created either when I expect to have all logs saved there at any time.

如何指定每次都会创建日志文件,并且仅在详细请求时指定stdout?

How can I have it specified that log file will be created each time and stdout only on verbose request?

PS. 我已经将一些代码移至

PS. I have moved some code to

def setup_logging(loglevel):
    logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s")

    if loglevel is not None:
        logformat = "%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s"
        logging.basicConfig(level=loglevel, stream=sys.stdout, format=logformat, datefmt="%Y-%m-%d %H:%M:%S")

    _logger.setLevel(logging.DEBUG)
    fileHandler = logging.handlers.TimedRotatingFileHandler("{0}/{1}.log".format(logPath, logFileName), when="midnight")
    fileHandler.setFormatter(logFormatter)
    _logger.addHandler(fileHandler)

会一直记录到日志文件,然后以详细记录输出,但日志文件仅保存设置为INFO的输出记录,不会显示为DEBUG,就像以详细-vv

that will log to the log file all the time and then output on verbose but log file is saving only output logging set as INFO nothing which comes as DEBUG as can be seen when running as verbose -vv

推荐答案

我已通过更新setup_logging()对其进行了修复:

I have it fixed by updating setup_logging():

_logger = logging.getLogger()
http_client_logger = logging.getLogger("http.client")

def print_to_log(*args):
    http_client_logger.debug(" ".join(args))


def setup_logging(loglevel, logPath, logFile):
    fileHandler = logging.handlers.TimedRotatingFileHandler("{0}/{1}.log".format(logPath, logFile), when="midnight")
    fileHandler.setLevel(logging.DEBUG)
    handlers = [fileHandler]

    if loglevel is not None:
        # if a log level is configured, use that for logging to the console
        stream_handler = logging.StreamHandler(sys.stdout)
        stream_handler.setLevel(loglevel)
        handlers.append(stream_handler)

    if loglevel == logging.DEBUG:
        # when logging at debug level, make http.client extra chatty too
        http.client.HTTPConnection.debuglevel = 1

    logformat = "%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s"
    logging.basicConfig(format=logformat, datefmt="%Y-%m-%d %H:%M:%S", handlers=handlers, level=logging.DEBUG)

这篇关于基于参数的Python双重日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆