记录模块不写入文件

时间:2022-06-01 18:59:41

I'm using logging module, and I've passed in the same parameters that I have on other jobs that are currently working:

我正在使用日志记录模块,并且我已经传递了与当前正在运行的其他作业相同的参数:

import logging
from inst_config import config3

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] - %(message)s',
    filename=config3.GET_LOGFILE(config3.REQUESTS_USAGE_LOGFILE))
logging.warning('This should go in the file.')

if __name__ == '__main__':
    logging.info('Starting unload.')

Using this method to create the filename:

使用此方法创建文件名:

REQUESTS_USAGE_LOGFILE = r'C:\RunLogs\Requests_Usage\requests_usage_runlog_{}.txt'.format(
        CUR_MONTH)
def GET_LOGFILE(logfile):
    """Truncates file and returns."""
    with open(logfile, 'w'):
        pass
    return logfile

When I run it, however, it is creating the file, and then still outputting the logging info to the console. I'm running in Powershell.

但是,当我运行它时,它正在创建文件,然后仍然将日志信息输出到控制台。我在Powershell中运行。

Just tried putting it inside the main statement like this:

刚尝试将它放在主语句中,如下所示:

if __name__ == '__main__':
    logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] - %(message)s',
    filename=config3.GET_LOGFILE(config3.REQUESTS_USAGE_LOGFILE))

    logging.warning('This should go in the file.')

Still no luck.

仍然没有运气。

2 个解决方案

#1


1  

Can you try run this in your main file:

你可以尝试在你的主文件中运行它:

import logging 
logging.basicConfig(
    level=logging.INFO, 
    format='%(asctime)s [%(levelname)s] - %(message)s',
    filename='filename.txt')  # pass explicit filename here 
logger = logging.get_logger()  # get the root logger
logger.warning('This should go in the file.')
print logger.handlers   # you should have one FileHandler object

#2


1  

I add the following lines before the logging.basicConfig() and it worked for me.

我在logging.basicConfig()之前添加以下行,它对我有用。

for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)

#1


1  

Can you try run this in your main file:

你可以尝试在你的主文件中运行它:

import logging 
logging.basicConfig(
    level=logging.INFO, 
    format='%(asctime)s [%(levelname)s] - %(message)s',
    filename='filename.txt')  # pass explicit filename here 
logger = logging.get_logger()  # get the root logger
logger.warning('This should go in the file.')
print logger.handlers   # you should have one FileHandler object

#2


1  

I add the following lines before the logging.basicConfig() and it worked for me.

我在logging.basicConfig()之前添加以下行,它对我有用。

for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)