多行变量记录 Python

Multi-line variable logging Python

我有一个 Python (3.9.7) 日志记录模块,可以在多行中打印我的一些变量。一个例子:

[   DEBUG] [SERVER_NAME] 2022-01-03 11:19:11,371 RMS re-projection error: 0.49781799970689544
[   DEBUG] [SERVER_NAME] 2022-01-03 11:19:11,371 Camera matrix: [[2.99470903e+04 0.00000000e+00 4.20193475e+02]
 [0.00000000e+00 3.02086634e+04 5.72796134e+02]
 [0.00000000e+00 0.00000000e+00 1.00000000e+00]]
[   DEBUG] [SERVER_NAME] 2022-01-03 11:19:11,373 Distortion coefficients: [[-6.06561628e+00  6.57303938e+02  1.90820141e-02  6.50947473e-02
   1.01373218e+00]]
[   DEBUG] [SERVER_NAME] 2022-01-03 11:19:11,373 Rotation vectors: (array([[ 0.01367595],
       [-3.13001593],
       [-0.10945951]]), array([[ 0.00776643],
       [-3.1302109 ],
       [-0.1329642 ]]), array([[ 0.01940937],
       [-3.13779723],
       [-0.12255833]]), array([[ 0.00404013],
       [-3.13138946],
       [-0.14486612]]))
[   DEBUG] [SERVER_NAME] 2022-01-03 11:19:11,376 Translation vectors: (array([[ 251.01501206],
       [-340.13064488],
       [8311.74652117]]), array([[ 247.35806988],
       [-119.53774136],
       [8265.26765344]]), array([[ 576.15864844],
       [-336.33047539],
       [8258.25314664]]), array([[ 571.09850597],
       [-118.67818482],
       [8269.13533797]]))

虽然我更喜欢:

[   DEBUG] [SERVER_NAME] 2022-01-03 11:19:11,371 RMS re-projection error: 0.49781799970689544
[   DEBUG] [SERVER_NAME] 2022-01-03 11:19:11,371 Camera matrix: [[2.99470903e+04 0.00000000e+00 4.20193475e+02][0.00000000e+00 3.02086634e+04 5.72796134e+02][0.00000000e+00 0.00000000e+00 1.00000000e+00]]
[   DEBUG] [SERVER_NAME] 2022-01-03 11:19:11,373 Distortion coefficients: [[-6.06561628e+00  6.57303938e+02  1.90820141e-02  6.50947473e-02       1.01373218e+00]]
[   DEBUG] [SERVER_NAME] 2022-01-03 11:19:11,373 Rotation vectors: (array([[ 0.01367595],           [-3.13001593],           [-0.10945951]]), array([[ 0.00776643],           [-3.1302109 ],           [-0.1329642 ]]), array([[ 0.01940937],           [-3.13779723],           [-0.12255833]]), array([[ 0.00404013],           [-3.13138946],           [-0.14486612]]))
[   DEBUG] [SERVER_NAME] 2022-01-03 11:19:11,376 Translation vectors: (array([[ 251.01501206],       [-340.13064488],       [8311.74652117]]), array([[ 247.35806988],       [-119.53774136],       [8265.26765344]]), array([[ 576.15864844],       [-336.33047539],       [8258.25314664]]), array([[ 571.09850597],       [-118.67818482],       [8269.13533797]]))

我使用以下日志格式化程序:

formatter = logging.Formatter('[%(levelname)8s] [SERVER_NAME] %(asctime)s %(message)s')

记录器中变量的调用是通过以下方式完成的: 自我.

logger.debug("RMS re-projection error: %s", ret)
self.logger.debug("Camera matrix: %s", mtx)
self.logger.debug("Distortion coefficients: %s", dist)
self.logger.debug("Rotation vectors: %s", rvecs)
self.logger.debug("Translation vectors: %s", tvecs)

我试图找到一个解决方案来在一行上打印更长的变量,但我还没有找到任何东西。 如果您错过任何信息,我非常乐意与您分享! 非常感谢任何帮助!

正如 Olvin Roght 所建议的,我将变量转换为字符串,其中我通过 str(ret).replace("\n", "")

删除了带有空字符串的新行