我正在使用标准库中的记录器,并希望将进度语句记录到自己的文件中。我将记录器设置为记录到控制台和文件。设置看起来像这样。
open ( my $input, '<', 'file.txt' ) or die $!;
这非常适合记录到控制台并将给定级别或更高级别的所有语句记录到文件中。问题来自于我想将进度语句(仅该语句)记录到单独的文件中。我目前正以下列方式将语句打印到控制台。
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))
答案 0 :(得分:1)
您可以尝试logging filter,例如:
class ProgressFilter(logging.Filter):
def filter(self, record):
if record.msg.endswith('Completed)'):
return True
logging.getLogger().handlers[0].addFilter(ProgressFilter())