• 技术文章 >Python技术 >Python基础教程

    python中如何用logging把日志输出到文件和控制台?

    宋雪维宋雪维2020-12-09 14:58:03原创7257

    还记得小编小时候,发生什么事情,遇到什么委屈或者高兴的事情,喜欢写在QQ日志中表达自己的情绪。虽然QQ日志现在已经不使用,但是日志的作用还在发挥。在计算机里,我们可以日志里记录自己的日常琐事或者是写的代码。那你知道如和将写好的日志输出到文件和控制台,便于我们存储使用吗?本文小编将简单向大家介绍python中通用的日志系统logging模块,并向大家演示用logging模块把日志输出到文件和控制台的过程。

    1、python的logging模块

    python的logging模块提供了通用的日志系统,可以方便第三方模块或者是应用使用。这个模块提供不同的日志级别,并可以采用不同的方式记录日志,比如文件,HTTP GET/POST,SMTP,Socket等,甚至可以自己实现具体的日志记录方式。

    2、logging模块基本使用

    1

    2

    3

    4

    5

    6

    7

    8

    import logging

     

    logging.basicConfig()

    logging.debug('This is a debug message')

    logging.info('This is an info message')

    logging.warning('This is a warning message')

    logging.error('This is an error message')

    logging.critical('This is a critical message')

    3、将日志输出到文件和控制台

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    import logging

     

    LOG_FILE = 'mylog.log'

     

    file_handler = logging.FileHandler(LOG_FILE) #输出到文件

    console_handler = logging.StreamHandler()  #输出到控制台

    file_handler.setLevel('ERROR')     #error以上才输出到文件

    console_handler.setLevel('INFO')   #info以上才输出到控制台

     

    fmt = '%(asctime)s - %(funcName)s - %(lineno)s - %(levelname)s - %(message)s' 

    formatter = logging.Formatter(fmt)

    file_handler.setFormatter(formatter) #设置输出内容的格式

    console_handler.setFormatter(formatter)

     

    logger = logging.getLogger('updateSecurity')

    logger.setLevel('DEBUG')     #设置了这个才会把debug以上的输出到控制台

     

    logger.addHandler(file_handler)    #添加handler

    logger.addHandler(console_handler)

    以上就是对python的logging模块的介绍和用logging模块把日志输出到文件和控制台的过程,希望能对你有所帮助哦~

    专题推荐:pythonlogging
    上一篇:_str_如何在python中进行重载? 下一篇:_repr_在python中是正式还是非正式

    相关文章推荐

    • 在python的dict中判断key是否存在• python不同版本中的_new_有何不同• python中的对数log函数如何表示?• python中如何画对数函数图?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网