Python日志

来源:互联网 发布:超级mac炮 编辑:程序博客网 时间:2024/05/16 15:31

为什么要日志

日志对于系统开发、调试、运维都是非常重要的,它有助于我们分析程序。

和print的比较

The logging package has a lot of useful features:

  • Easy to see where and when (even what line no.) a logging call is being made from.
  • You can log to files, sockets, pretty much anything, all at the same time.
  • You can differentiate your logging based on severity.

Print doesn`t have any of these.

Also, if your project is meant to be imported by other python tools, it’s bad practice for your package to print things to stdout, since the user likely won’t know where the print messages are coming from.

使用logging模块记日志

打印日志到控制台

import logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)logger.info('Start reading database')# read database hererecords = {'john': 55, 'tom': 66}logger.debug('Records: %s', records)logger.info('Updating records ...')# update records herelogger.info('Finish updating records')

output

INFO:__main__:Start reading databaseINFO:__main__:Updating records ...INFO:__main__:Finish updating records

There are different importance levels you can use, debug, info, warning, error and critical. By giving different level to logger or handler, you can write only error messages to specific log file, or record debug details when debugging.

Let’s change the logger level to DEBUG and see the output again
logging.basicConfig(level=logging.DEBUG)
(这个函数会默认为日志创建一个输出到stdout的handler)

output

INFO:__main__:Start reading databaseDEBUG:__main__:Records: {'john': 55, 'tom': 66}INFO:__main__:Updating records ...INFO:__main__:Finish updating records

我们发现换成debug模式,会打印出debug类型的日志。

将日志写入文件

you can use a FileHandler to write records to a file.(这个时候就不需要使用basicConfig()方法了)

import logginglogger = logging.getLogger(__name__)logger.setLevel(logging.INFO)# create a file handlerhandler = logging.FileHandler('hello.log')handler.setLevel(logging.INFO)# create a logging formatformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')handler.setFormatter(formatter)# add the handlers to the loggerlogger.addHandler(handler)logger.info('Hello baby')

上述代码只会把日志写到文件,控制台不会有任何输出。

如果你想既写日志到标准输出(console),也要写到文件,那么请加上basicConfig()它来再创建一个新的stdout Handler

代码如下

import logginglogging.basicConfig(level=logging.DEBUG)logger = logging.getLogger(__name__)# create a file handlerhandler = logging.FileHandler('hello.log')handler.setLevel(logging.DEBUG)# create a logging formatformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')handler.setFormatter(formatter)# add the handlers to the loggerlogger.addHandler(handler)logger.info('Hello baby')logger.debug('debug')

There are different handlers, you can also send records to you mailbox or even a to a remote server. You can also write your own custom logging handler.



More Info
https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python
https://docs.python.org/2/howto/logging.html#logging-basic-tutorial



Ref
http://stackoverflow.com/questions/6918493/in-python-why-use-logging-instead-of-print
https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python

0 0