简体   繁体   English

使用 logging.info 在日志文件中写入浮点值

[英]use logging.info to write float values inside a log file

I am using logging package to write some error values and a matrix inside a log file.我正在使用日志包在日志文件中写入一些错误值和矩阵。

logging.info("Error = %.4f"%err)
logging.info(error_mat) #error_mat is a NxN matrix

However, the matrix gets written in a different manner:但是,矩阵以不同的方式写入:

2014-09-08 14:10:20,107 - root - INFO - [[  8.30857546   0.69993454   0.20645551  
77.01797674  13.76705776]
 [  8.35205432   0.53417203   0.19969048  76.78598173  14.12810144]
 [  8.37066492   0.64428449   0.18623849  76.4181809   14.3806312 ]
 [  8.50493296   0.5110043    0.19731849  76.45838604  14.32835821]
 [  8.18900791   0.4955451    0.22524777  76.96966663  14.12053259]]

or要么

2014-09-08 14:12:22,211 - root - INFO - [[  3.25142253e+01   1.11788106e+00   1.51065008e-02   6.16496299e+01
    4.70315726e+00]
 [  3.31685887e+01   9.53522041e-01   1.49767860e-02   6.13449154e+01
    4.51799710e+00]
 [  3.31101827e+01   1.09729703e+00   5.03347259e-03   6.11818594e+01
    4.60562742e+00]
 [  3.32506957e+01   1.13837592e+00   1.51783456e-02   6.08651657e+01
    4.73058437e+00]
 [  3.26809490e+01   1.06617279e+00   1.00110121e-02   6.17429172e+01
    4.49994994e+00]]

How can we specify the precision for the float values inside the error_mat, eg %.3f for a 3 decimal point precision?我们如何指定 error_mat 中浮点值的精度,例如 %.3f 表示 3 个小数点精度? Also this will ensure the matrix values to be written in a single without line breaks.此外,这将确保矩阵值被写入一个没有换行符的单个。

If error_mat is a NumPy array, then you could use np.set_printoptions (as Padraic Cunningham commented):如果error_mat是一个 NumPy 数组,那么您可以使用np.set_printoptions (如 Padraic Cunningham 所评论的):

import numpy as np
arr = np.random.random((3, 4))-0.5
np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
print(arr)

prints something like打印出类似的东西

[[ 0.019  0.351 -0.138 -0.183]
 [-0.087  0.322  0.490 -0.407]
 [ 0.357  0.353 -0.077  0.411]]

Floating point number formatting is supported now:现在支持浮点数格式:

you can use %.nf where n is the number of floating point numbers after the dot.您可以使用%.nf其中n是点后的浮点数。

example :- _logger.info("Client started in %.4f seconds", end-start)示例 :- _logger.info("Client started in %.4f seconds", end-start)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM