python的日志

官方文档如下:

This module defines functions and classes which implement a flexible event logging system for applications and libraries.

这个模块定义函数和类可以用于应用程序和类库去实现灵活的日志系统。
The key benefit of having the logging API provided by a standard library module is that all Python modules can participate in logging,

使用标准库模块提供的日志API的主要好处是所有Python模块都可以参与日志

so your application log can include your own messages integrated with messages from third-party modules.

所以你的应用日志可以包含从第三方模型的消息中集成你自己的消息。
The module provides a lot of functionality and flexibility. If you are unfamiliar with logging, the best way to get to grips with it is to see the tutorials .这个模块提供了很多灵活的方法,如果你不熟悉这个logging,最好的方式去点击查看这些教程

一、Basic Logging Tutorial

     Logging is a means of tracking events that happen when some software runs. The software’s developer adds logging calls to their code to indicate that certain events have occurred. An event is described by a descriptive message which can optionally contain variable data (i.e. data that is potentially different for each occurrence of the event). Events also have an importance which the developer ascribes to the event; the importance can also be called the level or severity.

  日志意味着当一些软件在跑的时候跟踪一些发生的事件。软件开发者将日志添加到自己的代码中表明某些已经发生的时间。一个事件是由描述性消息描述,该消息可以选择性包含变量数据(对于事件的每次发生,数据可能是不同的)事件还具有开发人员赋予该事件的重要性;重要性也可以称为级别或严重性。

 

LevelWhen it’s used
DEBUGDetailed information, typically of interest only when diagnosing problems.(详细信息,通常只有在诊断问题时才感兴趣。)
INFOConfirmation that things are working as expected.(确认一切正常)
WARNINGAn indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.(表示发生了意想不到的事情,或者表示在不久的将来出现了某个问题(例如“磁盘空间不足”)。该软件仍按预期工作)
ERRORDue to a more serious problem, the software has not been able to perform some function.(由于一个更严重的问题,软件无法执行一些功能)
CRITICALA serious error, indicating that the program itself may be unable to continue running.(严重错误,指示程序本身可能无法继续运行。)

 1.0 

logging.warning('Watch out!')  # will print a message to the console
logging.info('I told you so')

printed out on the console. The INFO message doesn’t appear because the default level is WARNING.

1.1简单消息实现

logging.basicConfig(filename='example.log', level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

1.3如果输出日志相同不需要重复输出:

    logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)

1.4 简单统一日志:

   

import logging
import mylib

def main():
    logging.basicConfig(filename='myapp.log', level=logging.INFO)
    logging.info('Started')
    mylib.do_something()
    logging.info('Finished')

if __name__ == '__main__':
    main()
# mylib.py
import logging

def do_something():
    logging.info('Doing something')

高级实现:

 

1.5:变量值如何在日志中输出:

     logging.warning('%s before you %s', 'Look', 'leap!')

1.6 上面总是显示root:如何改变格式呢(format参数):

    logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)

这些参数哪里找,源代码Formatter类说明:

%(name)s            Name of the logger (logging channel)
%(levelno)s         Numeric logging level for the message (DEBUG, INFO,
                    WARNING, ERROR, CRITICAL)
%(levelname)s       Text logging level for the message ("DEBUG", "INFO",
                    "WARNING", "ERROR", "CRITICAL")
%(pathname)s        Full pathname of the source file where the logging
                    call was issued (if available)
%(filename)s        Filename portion of pathname
%(module)s          Module (name portion of filename)
%(lineno)d          Source line number where the logging call was issued
                    (if available)
%(funcName)s        Function name
%(created)f         Time when the LogRecord was created (time.time()
                    return value)
%(asctime)s         Textual time when the LogRecord was created
%(msecs)d           Millisecond portion of the creation time
%(relativeCreated)d Time in milliseconds when the LogRecord was created,
                    relative to the time the logging module was loaded
                    (typically at application startup time)
%(thread)d          Thread ID (if available)
%(threadName)s      Thread name (if available)
%(process)d         Process ID (if available)
%(message)s         The result of record.getMessage(), computed just as
                    the record is emitted

1.7 conf的方式:

     

[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=

代码实现:

  

import logging
import logging.config

logging.config.fileConfig('C:\Users\Administrator\Desktop\lnl\logging.conf')

# create logger
logger = logging.getLogger('simpleExample')

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

1.8纯代码方式:

import logging

# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python日志模块是标准库中的一个模块,可以用来记录应用程序的日志信息。封装Python日志可以方便地统一管理应用程序的日志信息,使得应用程序的开发和维护更加容易。 以下是一个简单的Python日志封装的例子: ```python import logging class Logger(object): def __init__(self, logger_name): self.logger = logging.getLogger(logger_name) self.logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(formatter) self.logger.addHandler(console_handler) def info(self, msg): self.logger.info(msg) def error(self, msg): self.logger.error(msg) def warning(self, msg): self.logger.warning(msg) def debug(self, msg): self.logger.debug(msg) ``` 上面的代码定义了一个Logger类,该类封装了Python的logging模块。在类的构造函数中,我们设置了日志的级别为INFO,并且添加了一个控制台输出的处理器。在类的方法中,我们分别封装了info、error、warning和debug级别的日志输出。在应用程序中,我们可以通过该类来统一管理应用程序的日志信息,例如: ```python logger = Logger('my_logger') logger.info('This is an info message.') logger.error('This is an error message.') logger.warning('This is a warning message.') logger.debug('This is a debug message.') ``` 通过上述代码,我们可以在控制台中看到相应级别的日志信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值