[英]How to format elapsed time (timedelta) in loguru?
Elapsed time in loguru is a datetime.timedelta object. loguru 中的经过时间是一个datetime.timedelta对象。 ( loguru docs )
( loguru 文档)
I want the time to be formatted as minutes and seconds.我希望将时间格式化为分钟和秒。 So, if
elapsed.seconds = 123
, it would become 2m3s
.因此,如果
elapsed.seconds = 123
,它将变为2m3s
。
This would normally be attainable by {elapsed.seconds//60}m{elapsed.seconds%60}s
in an f-string or using .format()
.这通常可以通过 f-string 中的
{elapsed.seconds//60}m{elapsed.seconds%60}s
或使用.format()
来实现。
But if I use f-string in loguru's format argument string, it obviously does not recognise the variable elapsed.seconds
as that belongs to loguru and not the current scope.但是如果我在 loguru 的格式参数字符串中使用 f-string,它显然无法识别变量
elapsed.seconds
因为它属于 loguru 而不是当前范围。 And so it gives the error AttributeError: 'datetime.timedelta' object has no attribute 'seconds//60'
in case of f-strings and NameError: name 'elapsed' is not defined
in case of trying to use .format()
Here's the code to replicate-所以它给出了错误
AttributeError: 'datetime.timedelta' object has no attribute 'seconds//60'
in case of f-strings and NameError: name 'elapsed' is not defined
in case of the case of try to use .format()
Here's要复制的代码-
from loguru import logger
logger_format = ('{time:DD-MMM-YYYY HH:mm:ss}'
'|{level:<8}| '
'({elapsed.seconds}s)')
logger.add('test.log', delay=True, format=logger_format, level='DEBUG')
def print_something(x):
if type(x) == int:
print(x)
logger.debug('Printing int')
print_something(2)
Here's the log it could print if running time was 123s:这是运行时间为 123 秒时它可以打印的日志:
07-Jul-2022 18:20:19|DEBUG | (123s) Printing int
Here's the log I want it to print:这是我希望它打印的日志:
07-Jul-2022 18:20:19|DEBUG | (2m3s) Printing int
The format
argument can be a format string, but it can also be a callable that takes a record dictionary and returns a string, like so: format
参数可以是一个格式字符串,但它也可以是一个可调用的,它接受一个记录字典并返回一个字符串,如下所示:
from loguru import logger
def my_format(record):
mins = record['elapsed'].seconds // 60
secs = record['elapsed'].seconds % 60
return '|{level:<8}| ({mins}m{secs}s)\n{exception}'.format(**record, mins=mins, secs=secs)
logger.add('test.log', delay=True, format=my_format, level='DEBUG')
You could also use an f-string if you prefer.如果您愿意,也可以使用 f 字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.