如何格式化日志以便在列中打印出来?

时间:2014-04-28 14:32:05

标签: python logging string-formatting

我有一个项目,其中不同的线程和函数使用不同的日志级别登录到控制台中的相同StreamHandler()日志,其中一些是自定义的。

我的日志格式化为:

streamformatter = logging.Formatter(fmt='%(levelname)s:\t%(threadName)s:\t%(funcName)s:\t\t%(message)s', datefmt='%H:%M:%S')

这使我的日志默认看起来像这样的乱码,看起来很容易看到或者很容易看到什么函数被调用以及从哪个线程。

INFO:   COM14-fwcif-listener :  _receive_v32:       my_success: Sending 24 lines to formatter
DB_TRACE:   COM14-fwcif-listener :  _format_and_log_v32:        {"prompt": "undef-COM14", "x_type": "tracelogentry", "y_time": 1392695506.044583, "z_msg": "...."}
INFO:   COM13-fwutil-listener:  _receive_v32:       my_success: Sending 10 lines to formatter
DB_TRACE:   COM13-fwutil-listener:  _format_and_log_v32:        {"prompt": "undef-COM13", "x_type": "tracelogentry", "y_time": 1392695507.356714, "z_msg": "...."}
INFO:   MainThread: _parse:     my_resolve after 4.9784979820251465 seconds and 29 vs 8 attempts
MY_INFO:    MainThread: _parse:     my_success for cmd "trig" =>> "not ready". COM12.ISREADY now set to True
INFO:   MainThread: send:       my_success. Lock being released: <_thread.RLock owner=7512 count=1> with cmd "format c:" and state COM12.ISREADY = False
INFO:   COM12-fwmain-listener:  _receive_v32:       my_success: Number of lines split by S65 is 2 of 16 total lines
INFO:   COM12-fwmain-listener:  _format_and_log_v32:        my_resolve "S65>" added as COM12.lastlinefragment
INFO:   COM12-fwmain-listener:  _format_and_log_v32:        my_success: 575 chars written to log.   Prompt and type detected is "S65>" and "replylogentry: format"
DB_REPLY:   COM12-fwmain-listener:  _format_and_log_v32:        {"prompt": "S65>", "x_type": "replylogentry: format", "y_time": 1392695510.41302, "z_msg": "..."}
INFO:   MainThread: _parse:     my_resolve  searching for "format"=>"Unknown command" in string "..."

1 个答案:

答案 0 :(得分:2)

可以通过这种方式在streamformatter中指定每个标记的宽度,以生成固定冒号的日志输出:

streamformatter = logging.Formatter(fmt='%(levelname)-10s:  %(threadName)-20s: %(funcName)-20s:  %(message)s', datefmt='%H:%M:%S')