【发布时间】:2016-07-05 09:31:42
【问题描述】:
我正在使用标准库中的记录器,并希望将进度语句记录到它自己的文件中。我将记录器设置为记录到控制台和文件。设置如下所示。
def setup_logging(args):
try:
numeric_level = getattr(logging, args.loglevel.upper())
# If they provide a full path, ensure that the path is valid.
log_dir = os.path.dirname(args.logfile)
if log_dir and not os.path.isdir(log_dir):
# If the provided path doesn't exist, write the log file
# using the provided name to the current directory
args.logfile = os.path.basename(args.logfile)
sys.stderr.write("Invalid logfile path. Defaulting to current directory\n")
logging.basicConfig(level=numeric_level,
format='%(asctime)s - %(name)s - %(levelname)s - %(funcName)s - %(message)s',
datefmt='%m-%d-%Y %H:%M:%S',
filename=args.logfile,
filemode='w')
console = logging.StreamHandler()
console.setLevel(logging.ERROR)
formatter = logging.Formatter('%(name)s - %(funcName)s - %(levelname)s - %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
except Exception as e:
logging.critical("Failed to configure logging for the following reason: %s", e.message)
return False
return True
这非常适合记录到控制台并将给定级别或更高级别的所有语句记录到文件中。问题来自于我想将进度语句(并且只有该语句)记录到单独的文件中。我目前正在通过以下方式将语句打印到控制台。
if current < num_file:
print("Processing file {:.0f} of {} ({:.2%} Completed)".format(current + 1, num_file, current/num_file),
end='\r')
else:
print("Finished file {:.0f} of {} ({:.2%} Completed)".format(current, num_file, current/num_file))
不幸的是,该语句似乎并未在所有控制台上打印,并且当记录器将错误语句记录到控制台时会被覆盖。因此,我想另外将语句写入文件。
我知道我可以使用以下方法来完成此操作,但我想知道是否有办法使用日志库来做到这一点。如果可以避免,我宁愿不必担心自己处理文件。
prog_file = open("progress.txt", 'w')
...
print("Processing file {:.0f} of {} ({:.2%} Completed)".format(current + 1, num_file, current/num_file),
end='\r', file=prog_file)
【问题讨论】:
-
通过使用a custom logging handler,有一些方法可以显示不会被日志覆盖的自定义进度语句。