V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
hanssx
V2EX  ›  Python

logging format 如何优雅地对齐

  •  
  •   hanssx · 2018-11-05 15:53:40 +08:00 · 4580 次点击
    这是一个创建于 1970 天前的主题,其中的信息可能已经有所发展或是发生改变。

    [%(asctime)-15s] [%(levelname)s] - %(message)s (%(filename)s:%(lineno)s) 得到的结果是

    [2018-11-02 09:56:14] [INFO]  - start flask app (manage.py:21)
    [2018-11-02 09:56:14] [WARNING]  -  * Debugger is active! (_internal.py:88)
    [2018-11-02 09:56:14] [INFO]  -  * Debugger PIN: 323-630-998 (_internal.py:88)
    

    加上右对齐(左对齐一样), [%(asctime)-15s] [%(levelname)8s] - %(message)s (%(filename)s:%(lineno)s) 得到的结果是

    [2018-11-02 09:58:30] [    INFO] - start flask app (manage.py:21)
    [2018-11-02 09:58:30] [ WARNING] -  * Debugger is active! (_internal.py:88)
    [2018-11-02 09:58:30] [    INFO] -  * Debugger PIN: 323-630-998 (_internal.py:88)
    

    而我想要得是

    [2018-11-02 09:58:30] [INFO]    - start flask app (manage.py:21)
    [2018-11-02 09:58:30] [WARNING] -  * Debugger is active! (_internal.py:88)
    [2018-11-02 09:58:30] [INFO]    -  * Debugger PIN: 323-630-998 (_internal.py:88)
    
    5 条回复    2018-11-30 14:47:14 +08:00
    tinyproxy
        1
    tinyproxy  
       2018-11-05 16:10:32 +08:00
    ```python
    import logging
    logging.basicConfig(level=logging.DEBUG, format="%(levelname)s %(message)s")
    logging.debug('it works') # DEBUG it works
    logging.addLevelName(logging.DEBUG, '[my debug name]{BLANK PADDINGS}')
    logging.debug('it works') # [my debug name]{BLANK PADDINGS} it works
    ```
    chinawrj
        2
    chinawrj  
       2018-11-05 16:20:31 +08:00   ❤️ 1
    你要的是"]"之后的制表符\t
    hanssx
        3
    hanssx  
    OP
       2018-11-05 16:52:13 +08:00
    @chinawrj 感谢感谢,是我要的答案,嘿嘿。
    lolizeppelin
        4
    lolizeppelin  
       2018-11-08 16:22:29 +08:00 via Android
    最好不要用制表符 自己算长度呗
    类似的代码可以看 prettytable
    hanssx
        5
    hanssx  
    OP
       2018-11-30 14:47:14 +08:00
    @lolizeppelin 为何不要用制表符呢?能详细说下吗
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3559 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 04:56 · PVG 12:56 · LAX 21:56 · JFK 00:56
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.