zoukankan      html  css  js  c++  java
  • python开发_logging_日志处理

    在很多编程语言中,都会出现日志处理操作,python也不例外...

    接下来我们来看看python中的logging模块

    '''
        python中,logging模块主要是处理日志的。
        所谓日志,可理解为在软件运行过程中,所记录的的一些运行情况信息
        软件开发人员可以根据自己的需求添加日志,日志可以帮助软件开发人员
        了解软件的运行信息,对软件的维护尤为重要。
    
        日志级别:
    
           Level                              When it's used
          DEBUG                         detailed information,typically of interest only when diagnosing problems
          INFO                          confirmation that things are working as expected
          WARNING                       An indication that something unexpected happended,or indicative of some problem in the near future.The software is still working as expected
          ERROR                         Due to a more serious problem,the software has not been able to perform some funciton
          CRITICAL                      A serious error, indication that the program itself may be unable to continue running.
    
        The default level is WARNING.
    
        Here is an Example:
        
        import logging
        logging.info('this is an info log!')
        logging.warning('this is a warn log!')
    
        you can see the result:
        WARNING:root:this is a warn log!
    
        如果你想看到级别比较低的一些日志,你可以这样做:
    
        Here is an Example:
        import logging
        logging.basicConfig(filename = 'c:\test\hongten.log', level = logging.DEBUG)
        logging.debug('this is a debug log!')
        logging.info('this is an info log!')
        logging.warning('this is a warn log!')
    
        you can see the result:
        DEBUG:root:this is a debug log!
        INFO:root:this is an info log!
        WARNING:root:this is a warn log!
    
        如果你想格式化输出日志,你可以这样做:
        
        Here is an Example:
        import logging
        logging.basicConfig(format = '%(levelname)s:%(message)s', level = logging.DEBUG)
        logging.debug('this is a debug log!')
        logging.info('this is an info log!')
        logging.warning('this is a warn log!')
    
        you can see the result:
        DEBUG:this is a debug log!
        INFO:this is an info log!
        WARNING:this is a warn log!
    
        下面是LogRecord attributes,在格式化输出日志的时候需要用到:
        Attribute name                     Format                                   Description 
        args                              You shouldn’t need to format              The tuple of arguments merged into msg to produce message.
                                          this yourself.       
        asctime                           %(asctime)s                               时间格式
        created                           %(created)s                               创建时间
        filename                          %(filename)s                              文件名称
        levelname                         %(levelname)s                             日志级别
        levelno                           %(levelno)s                               日志id号
        lineno                            %(lineno)s                                行号
        module                            %(module)s                                模块名称
        mescs                             %(mescs)s                                 Millisecond portion of the time when the LogRecord was created.
        message                           %(message)s                               日志信息
        name                              %(name)s                                  日志名称
        pathname                          %(pathname)s                              文件绝对路径
        process                           %(process)s                               进程id
        processName                       %(processName)s                           进程名称
        relativeCreated                   %(relativeCreated)s                       Time in milliseconds when the LogRecord was created,
                                                                                    relative to the time the logging module was loaded.
        thread                            %(thread)s                                线程id
        threadName                        %(threadName)s                            线程名称
    
    '''

    以下是我做的demo:

    运行效果:

    Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
    Type "copyright", "credits" or "license()" for more information.
    >>> ================================ RESTART ================================
    >>> 
    ##################################################
    ##################################################
    ##################################################
    ##################################################
    2013-08-26 11:01:58,076 - root - DEBUG - this is a debug log!
    2013-08-26 11:01:58,080 - root - INFO - this is an info log!
    2013-08-26 11:01:58,085 - root - WARNING - this is a warn log!
    2013-08-26 11:01:58,088 - root - ERROR - this is an error log!
    2013-08-26 11:01:58,091 - root - CRITICAL - this is a critical log!
    >>> 

    ============================================================

    代码部分:

    ============================================================

      1 #python logging
      2 
      3 #Author  : Hongten
      4 #Mailto  : hongtenzone@foxmail.com
      5 #Blog    : http://www.cnblogs.com/hongten
      6 #QQ      : 648719819
      7 #Create  : 2013-08-26
      8 #Version : 1.0
      9 
     10 import logging
     11 import logging.config
     12 
     13 '''
     14     python中,logging模块主要是处理日志的。
     15     所谓日志,可理解为在软件运行过程中,所记录的的一些运行情况信息
     16     软件开发人员可以根据自己的需求添加日志,日志可以帮助软件开发人员
     17     了解软件的运行信息,对软件的维护尤为重要。
     18 
     19     日志级别:
     20 
     21        Level                              When it's used
     22       DEBUG                         detailed information,typically of interest only when diagnosing problems
     23       INFO                          confirmation that things are working as expected
     24       WARNING                       An indication that something unexpected happended,or indicative of some problem in the near future.The software is still working as expected
     25       ERROR                         Due to a more serious problem,the software has not been able to perform some funciton
     26       CRITICAL                      A serious error, indication that the program itself may be unable to continue running.
     27 
     28     The default level is WARNING.
     29 
     30     Here is an Example:
     31     
     32     import logging
     33     logging.info('this is an info log!')
     34     logging.warning('this is a warn log!')
     35 
     36     you can see the result:
     37     WARNING:root:this is a warn log!
     38 
     39     如果你想看到级别比较低的一些日志,你可以这样做:
     40 
     41     Here is an Example:
     42     import logging
     43     logging.basicConfig(filename = 'c:\test\hongten.log', level = logging.DEBUG)
     44     logging.debug('this is a debug log!')
     45     logging.info('this is an info log!')
     46     logging.warning('this is a warn log!')
     47 
     48     you can see the result:
     49     DEBUG:root:this is a debug log!
     50     INFO:root:this is an info log!
     51     WARNING:root:this is a warn log!
     52 
     53     如果你想格式化输出日志,你可以这样做:
     54     
     55     Here is an Example:
     56     import logging
     57     logging.basicConfig(format = '%(levelname)s:%(message)s', level = logging.DEBUG)
     58     logging.debug('this is a debug log!')
     59     logging.info('this is an info log!')
     60     logging.warning('this is a warn log!')
     61 
     62     you can see the result:
     63     DEBUG:this is a debug log!
     64     INFO:this is an info log!
     65     WARNING:this is a warn log!
     66 
     67     下面是LogRecord attributes,在格式化输出日志的时候需要用到:
     68     Attribute name                     Format                                   Description 
     69     args                              You shouldn’t need to format              The tuple of arguments merged into msg to produce message.
     70                                       this yourself.       
     71     asctime                           %(asctime)s                               时间格式
     72     created                           %(created)s                               创建时间
     73     filename                          %(filename)s                              文件名称
     74     levelname                         %(levelname)s                             日志级别
     75     levelno                           %(levelno)s                               日志id号
     76     lineno                            %(lineno)s                                行号
     77     module                            %(module)s                                模块名称
     78     mescs                             %(mescs)s                                 Millisecond portion of the time when the LogRecord was created.
     79     message                           %(message)s                               日志信息
     80     name                              %(name)s                                  日志名称
     81     pathname                          %(pathname)s                              文件绝对路径
     82     process                           %(process)s                               进程id
     83     processName                       %(processName)s                           进程名称
     84     relativeCreated                   %(relativeCreated)s                       Time in milliseconds when the LogRecord was created,
     85                                                                                 relative to the time the logging module was loaded.
     86     thread                            %(thread)s                                线程id
     87     threadName                        %(threadName)s                            线程名称
     88 
     89 
     90 '''
     91 
     92 def test_log1():
     93     '''因为logging的默认级别是:WARNING
     94     所以,这里只会输出:this is a warn log!'''
     95     logging.warning('this is a warn log!')
     96     logging.info('this is an info log!')
     97 
     98 def test_log_2_file(path):
     99     '''把运行的日志信息记录到指定的日志文件中
    100     并且把日志的操作级别设置为:DEBUG模式'''
    101     logging.basicConfig(filename = path, level = logging.DEBUG)
    102     logging.debug('this is a debug log!')
    103     logging.info('this is an info log!')
    104     logging.warning('this is a warn log!')
    105 
    106 def logging_variable_data():
    107     '''可变数据的日志'''
    108     logging.warning('%s + %s = %s', 3, 4, 3+4)
    109 
    110 def logging_format():
    111     '''格式化日志'''
    112     logging.basicConfig(format='%(asctime)s --%(lineno)s -- %(levelname)s:%(message)s', level=logging.DEBUG)
    113     logging.debug('This message should appear on the console')
    114     logging.info('So should this')
    115     logging.warning('And this, too')
    116 
    117 def logging_from_config():
    118     '''
    119     c:\hongten_logging.conf配置文件信息如下:
    120     [loggers]
    121     keys=root,simpleExample
    122 
    123     [handlers]
    124     keys=consoleHandler
    125 
    126     [formatters]
    127     keys=simpleFormatter
    128 
    129     [logger_root]
    130     level=DEBUG
    131     handlers=consoleHandler
    132 
    133     [logger_simpleExample]
    134     level=DEBUG
    135     handlers=consoleHandler
    136     qualname=simpleExample
    137     propagate=0
    138 
    139     [handler_consoleHandler]
    140     class=StreamHandler
    141     level=DEBUG
    142     formatter=simpleFormatter
    143     args=(sys.stdout,)
    144 
    145     [formatter_simpleFormatter]
    146     format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
    147     datefmt=
    148     '''
    149     logging.config.fileConfig('c:\hongten_logging.conf')
    150     logger = logging.getLogger('root')
    151     logger.debug('this is a debug log!')
    152     logger.info('this is an info log!')
    153     logger.warn('this is a warn log!')
    154     logger.error('this is an error log!')
    155     logger.critical('this is a critical log!')
    156 
    157 def main():
    158     '''在这里,请一个一个的打开测试'''
    159     #test_log_2_file('c:\hongten.log')
    160     print('#' * 50)
    161     #test_log1()
    162     print('#' * 50)
    163     #logging_variable_data()
    164     print('#' * 50)
    165     #logging_format()
    166     print('#' * 50)
    167     logging_from_config()
    168     
    169 
    170 if __name__ == '__main__':
    171     main()
  • 相关阅读:
    JavaSE学习(二):进制转换—数据类型转换—Java运算符
    JavaSE学习(五):数组及其基础操作
    iOS工作中的经验总结—马甲包审核以及常见审核问题!!!(干货)
    月薪过万不是梦!2018年最全/最新Python面试题(整理汇总)
    Python:爬虫技巧总结!
    【转】maven学习(下) 利用Profile构建不同环境的部署包
    【转】maven学习(上) 基本入门用法
    Java从控制台获取数据的方法
    【转】LinkedHashMap实现由插入集合的顺序输出
    浅谈String/StringBuffer/StringBuilder字符串的拼接
  • 原文地址:https://www.cnblogs.com/hongten/p/hongten_python_logging.html
Copyright © 2011-2022 走看看