首页 > 代码库 > Python Logging模块

Python Logging模块

1.about logging

a.Logging is performed by calling methods on instances of the Logger class (hereafter called loggers).

logging通过调用Logger类的对象的方法实现。

Loggers指logger类的实例(对象),是实现Logging的核心元素。

b.Logger names can be anything you want, and indicate the area of an application in which a logged message originates.

Loggers对象的名称可以任意取,目的是标识Log信息源自于应用的哪个区域

c.The key benefit of having the logging API provided by a standard library module is that all Python modules can participate in logging.

logging API由标准库提供,这样的好处在于所有的Python模块都能进行logging。

2.logging的基本元素

a.日志记录对象logger

logger的相关配置:

 

logger=logging.getLogger(name)#获取Logger对象logger.setLevel(logging.DEBUG)#设置logger对象等级

 

b.声明句柄类对象

句柄类对象有多种类型,包括StreamHandler,FileHandler,RotatingFileHandler,SysLogHandler,SocketHandler等等

句柄控制logger的输出,使其更多样化的输出。

 

 

 

3.logging 例子

a.简单的例子

 1 import logging 2  3 logging.basicConfig(level=logging.DEBUG, 4                     format=%(asctime)s %(levelname)-8s %(message)s, 5                     datefmt=%a, %d %b %Y %H:%M:%S, 6                     filename=/temp/myapp.log, 7                     filemode=w) 8 logging.debug(A debug message) 9 logging.info(Some information)10 logging.warning(A shot across the bows)

其中basicConfig方法设置默认的输出形式,包括输出到哪个文件,消息输出的格式和级别

 1 import logging 2  3 # set up logging to file - see previous section for more details 4 logging.basicConfig(level=logging.DEBUG, 5                     format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s, 6                     datefmt=%m-%d %H:%M, 7                     filename=/temp/myapp.log, 8                     filemode=w) 9 # define a Handler which writes INFO messages or higher to the sys.stderr10 console = logging.StreamHandler()11 console.setLevel(logging.INFO)12 # set a format which is simpler for console use13 formatter = logging.Formatter(%(name)-12s: %(levelname)-8s %(message)s)14 # tell the handler to use this format15 console.setFormatter(formatter)16 # add the handler to the root logger17 logging.getLogger(‘‘).addHandler(console)18 19 # Now, we can log to the root logger, or any other logger. First the root...20 logging.info(Jackdaws love my big sphinx of quartz.)21 22 # Now, define a couple of other loggers which might represent areas in your23 # application:24 25 logger1 = logging.getLogger(myapp.area1)26 logger2 = logging.getLogger(myapp.area2)27 28 logger1.debug(Quick zephyrs blow, vexing daft Jim.)29 logger1.info(How quickly daft jumping zebras vex.)30 logger2.warning(Jail zesty vixen who grabbed pay from quack.)31 logger2.error(The five boxing wizards jump quickly.)