繁体   English   中英

Python 基于参数的双重日志记录

[英]Python dual logging based on an 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参数运行脚本时,它会正常工作,但是当我希望随时将所有日志保存在那里时,没有创建提供程序日志文件。

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

PS。 我已将一些代码移至

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)

这将一直记录到日志文件,然后 output 详细但日志文件仅保存 output 日志记录设置为INFO没有作为DEBUG出现,当以详细-vv运行时可以看到

如果未提供任何选项,您会丢失 loglevel 的默认值。

parser.add_argument(
    "-v",
    "--verbose",
    dest="loglevel",
    help="set loglevel to INFO",
    action="store_const",
    default=logging.DEBUG, # <---- You are missing this line here
    const=logging.INFO)

我通过更新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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM