我正在使用具有以下格式字符串的 python 日志记录:
'format': '%(asctime)s %(levelname)s %(name)s - %(message)s'
%(name)s
部分打印记录器名称:
2017-10-26 13:17:58,019 INFO device_gps.comm.protocol - GPSProtocol(port=COM13) - Starting GPS serial communications (port: COM13) 2017-10-26 13:17:58,022 INFO scs_control.context - Starting component: DeviceGPS 2017-10-26 13:17:58,033 INFO scs_elevation.elevation - Initializing ElevationModel engine instance.
与其他日志记录工具(如 log4j)一样,为了简洁起见,我只想打印记录器名称的最后一部分(在上面的示例中以粗体显示)。
这other answer建议更改记录器名称,但这样做会破坏父子记录器关系,这对于为一组记录器配置日志记录非常有用。
如何让 python 日志记录打印记录器名称的最后一部分?
最佳答案
您可以设置过滤器以将 LogRecord
属性设置为记录器名称的最后一部分,并在您的格式字符串中使用它。例如,运行这个脚本:
import logging
class LastPartFilter(logging.Filter):
def filter(self, record):
record.name_last = record.name.rsplit('.', 1)[-1]
return True
logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter('%(name_last)s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
handler.addFilter(LastPartFilter())
logging.getLogger('foo').warning('Watch out - foo!')
logging.getLogger('foo.bar').warning('Watch out - foo.bar!')
logging.getLogger('foo.bar.baz').warning('Watch out - foo.bar.baz!')
产生这个:
foo Watch out - foo!
bar Watch out - foo.bar!
baz Watch out - foo.bar.baz!
关于Python 日志记录格式 : how to print only the last part of logger name?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46954855/