Python日志记录模块未写入日志文件

时间:2019-06-24 13:01:40

标签: python logging

我的脚本有问题,我正在尝试为此函数的每次调用创建日志文件:

@begin.subcommand
def sample_mode(sample, folder = None, reference = None, dbsnp = None):
    """ creates a config file for 1 sample

    - setup logging system: {folder}/logs/{sample}_init.log
    - takes in a sample name
    - creates a file: {folder}/{sample}_config.yaml
    """
    # get the current folder if none is given
    if folder == None:
        folder = os.getcwd() 

    # create logs folder if necessary
    if not os.path.isdir("{}/logs".format(folder)):
        os.mkdir("{}/logs".format(folder))

    log_file = setup_log(sample, folder)

    for i in range(1,3):
        try:
            os.path.getsize("{}/{}.{}.fq.gz".format(folder, sample, i))
        except FileNotFoundError:
            log_file.error("{}/{}.{}.fq.gz doesn't exist".format(folder, sample, i))
            return -1

        if os.path.getsize("{}/{}.{}.fq.gz".format(folder, sample, i)) == 0:
            log_file.error("\"{}/{}.{}.fq.gz\" is empty\n".format(folder, sample, i))
            return -1

    # set up logging system
    # logging.basicConfig(filename = "{}/logs/{}_init.log".format(folder, sample), level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

    # create the config file
    with open("{}/{}_config.yaml".format(folder, sample), "w") as config:
        config.write("sample: \"{}\"\n\n".format(sample))
        log_file.info("Sample name: {}".format(sample))

setup_log函数供参考:

def setup_log(sample, folder):
    logger = logging.getLogger(__name__)

    log_format = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

    filename = "{}/logs/{}_init.log".format(folder, sample)

    log_handler = logging.FileHandler(filename)
    log_handler.setLevel(logging.DEBUG)
    log_handler.setFormatter(log_format)

    logger.addHandler(log_handler)

    return logger

日志文件已创建,但为空。但是,如果我输入了错误的样品名称,则会创建日志文件并写入错误消息。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些错误,这应该可以解决:

import logging

def setup_log(name):
    logger = logging.getLogger(name)   # > set up a new name for a new logger

    logger.setLevel(logging.DEBUG)  # here is the missing line

    log_format = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    filename = f"./test_{name}.log"
    log_handler = logging.FileHandler(filename)
    log_handler.setLevel(logging.DEBUG)
    log_handler.setFormatter(log_format)

    logger.addHandler(log_handler)

    return logger

def test_log(name):
    logger = setup_log(name)
    logger.info("Just logged from %s", name)   # > old formatting syntax is advised by the logging cookbook

test_log("log1")
test_log("log2")
test_log("log3")

未写入日志文件,因为您必须先设置记录器的级别,然后再设置处理程序的级别。

此外,您必须知道logging.getLogger(name)返回单例。如果您使用以前使用的相同名称调用getLogger功能,这将返回现有的记录器,这可能会导致您遇到一种非常奇怪的情况……示例:

def test_log(name):
    logger = setup_log(name)

等同于

def test_log(name):
    setup_log(name)
    logger = logging.getLogger(name)
  

更多内容:https://docs.python.org/3/howto/logging-cookbook.html