Python的日志是通過logging模塊實現(xiàn)的
一、日志的基本使用
1. 日志輸出到控制臺
import logging
logging.warning('This is a warning message') # will print a message to the console
logging.info('This is a nomal message') # will not print anything
運行結果:
WARNING:root:This is a warning message
日志的默認級別是
warning
驮俗,所以上例中吨述,只有warning
的信息打印出來澎羞。
1. 日志輸出到文件
import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This is a debug message')
logging.info('This is a nomal message')
logging.warning('This is a warning message')
運行代碼后驯镊,會在根目錄生成一個example.log
,打開該日志文件缘缚,可以看到如下結果:
DEBUG:root:This is a debug message
INFO:root:This is a nomal message
WARNING:root:This is a warning message
注意:
basicConfig()
調(diào)用前不能進行任何日志的輸出勾笆,否則basicConfig()
的配置信息全部失效。
二桥滨、多模塊使用日志
1. 日志輸出到一個終端
# myapp.py
import logging
import mylib
def main():
logging.basicConfig(filename='myapp.log', level=logging.INFO)
logging.info('In myapp.py, Started')
mylib.do_something()
logging.info('In myapp.py, Finished')
if __name__ == '__main__':
main()
# mylib.py
import logging
def do_something():
logging.info('In mylib.py, Doing something')
運行myapp.py后窝爪,打開生成的日志文件myapp.log
,可以看到如下結果:
INFO:root:In myapp.py, Started
INFO:root:In mylib.py, Doing something
INFO:root:In myapp.py, Finished
從運行結果可以看出齐媒,如上例實現(xiàn)的多模塊日志蒲每,會根據(jù)方法調(diào)用的先后順序打印日志信息。
2. 日志輸出到一個終端
上面的例子都只能輸出到一個終端喻括,要么是控制臺邀杏,要么是日志文件。
下面的例子將會展示如何將日志信既輸出到控制臺唬血,又輸出到日志文件中:
# myapp.py
import logging
import mylib
# create logger with 'myapp'
logger = logging.getLogger('myapp')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
# file mode set write. myapp.log will be rewrite when every time myapp.py is runned.
fh = logging.FileHandler('myapp.log', mode='w')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)
logger.info('In myapp.py, Started')
logger.error('This is a error message')
mylib.do_something()
logger.info('In myapp.py, Finished')
# mylib.py
import logging
# getLogger named myapp
mylib_logger = logging.getLogger('myapp')
def do_something():
mylib_logger.info('In mylib.py, Doing something')
運行myapp.py望蜡,因為控制臺的日志級別為ERROR
,所以控制臺只輸出ERROR
級別的信息:
2017-07-05 11:07:36,721 - myapp - ERROR - This is a error message
因為日志文件的日志級別為DEBUG
拷恨,所以文件中包含DEBUG
及DEBUG
以上級別的信息:
2017-07-05 11:07:36,721 - myapp - INFO - In myapp.py, Started
2017-07-05 11:07:36,721 - myapp - ERROR - This is a error message
2017-07-05 11:07:36,721 - myapp - INFO - In mylib.py, Doing something
2017-07-05 11:07:36,721 - myapp - INFO - In myapp.py, Finished
了解以上內(nèi)容就可以實現(xiàn)基本的日志功能了脖律,但是如果想要有效的使用Python的日志功能,還有很多東西需要學習腕侄。