logging模块的简单使用以及tornado中的log简单介绍

刚知道tornado原来是facebook开源的。

logging的简单介绍和使用

python内置模块logging,用于记录日志,格式化输出。通过getLogger()获得的是单例且线程安全的(进程不安全),下文会简单介绍logging的常用方法和简单logging源码分析,以及tornado中的日志模块。

使用basicConfig()(给root handler添加基本配置),除了levelfilename参数外还有filemode(默认a),format(输出格式),handlers(给root logger添加handlers)

import logging

logging.basicConfig(level=logging.DEBUG, filename='main.log')
logging.debug('bug log')

logging的日志分为这几种级别:

CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0

logging.info()等实际上是根looger(root logger)的info()方法。

利用logger的相对应的infodebugwaring等可以输出日志,只有当方法级别>日志级别时才能够输出(如level=logging.INFO时,用logging.error('error')能够输出,而logging.debug('debug')无输出)。

值得一提的是还有一个logging.exception()方法,能够简单的记录Traceback信息(实际上是相当于logging.error(e, exc_info=True)),所有的输出方法最终都是调用了logger的_log()方法。

getLogger()
import logging

root_logger = logging.getLogger()
mine_logger = logging.getLogger('mine')

参数缺省时默认获取的是root_logger,是所有logger的最终父logger。
在未作任何配置时,root_logger的日志级别是warning

阅读getLogger()源码可以发现

root = RootLogger(WARNING)
Logger.root = root
Logger.manager = Manager(Logger.root)

def getLogger(name=None):
    """
    Return a logger with the specified name, creating it if necessary.

    If no name is specified, return the root logger.
    """
    if name:
        return Logger.manager.getLogger(name)
    else:
        return root

执行logging.getLogger('mine')方法,即Manager(Logger.root).getLogger('mine'),再来看一下ManagergetLogger()

    def getLogger(self, name):
        """
        Get a logger with the specified name (channel name), creating it
        if it doesn't yet exist. This name is a dot-separated hierarchical
        name, such as "a", "a.b", "a.b.c" or similar.

        If a PlaceHolder existed for the specified name [i.e. the logger
        didn't exist but a child of it did], replace it with the created
        logger and fix up the parent/child references which pointed to the
        placeholder to now point to the logger.
        """
        rv = None
        if not isinstance(name, str):
            raise TypeError('A logger name must be a string')
        _acquireLock()
        try:
            if name in self.logg
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python logging 模块Python 标准库的一个模块,用于记录程序运行时的日志信息。使用 logging 模块可以方便地记录程序的运行状态,以便在出现问题时进行排查。 使用 logging 模块需要先导入模块,然后创建一个 logger 对象,设置日志级别和输出格式,最后在程序使用 logger 对象记录日志信息。 下面是一个简单的示例代码: ``` import logging # 创建 logger 对象 logger = logging.getLogger('mylogger') # 设置日志级别 logger.setLevel(logging.DEBUG) # 创建一个输出到控制台的 handler console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG) # 创建一个输出到文件的 handler file_handler = logging.FileHandler('mylog.log') file_handler.setLevel(logging.INFO) # 设置输出格式 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') console_handler.setFormatter(formatter) file_handler.setFormatter(formatter) # 将 handler 添加到 logger 对象 logger.addHandler(console_handler) logger.addHandler(file_handler) # 记录日志信息 logger.debug('debug message') logger.info('info message') logger.warning('warning message') logger.error('error message') logger.critical('critical message') ``` 在上面的示例代码,我们创建了一个名为 `mylogger` 的 logger 对象,并设置了日志级别为 `DEBUG`。然后创建了一个输出到控制台的 handler 和一个输出到文件的 handler,并设置了输出格式。最后将这两个 handler 添加到 logger 对象。 在程序使用 logger 对象记录日志信息时,可以使用 `debug()`、`info()`、`warning()`、`error()`、`critical()` 等方法,分别对应不同的日志级别。例如,`logger.debug('debug message')` 就会记录一条 DEBUG 级别的日志信息。 以上就是 Python logging 模块的基本使用方法。 ### 回答2: Pythonlogging模块是一个强大的日志记录工具。它提供了一种灵活的方式来在程序记录日志,以便在程序运行过程获取有用的信息和诊断数据。下面是如何使用Python logging模块的基本步骤。 1. 导入logging模块: ```python import logging ``` 2. 配置日志记录器: ```python logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='app.log', filemode='w') ``` 在配置方法,level参数设置日志级别,可选项包括DEBUG、INFO、WARNING、ERROR和CRITICAL。format参数定义日志记录的格式,其asctime表示日志记录的时间,levelname表示日志级别,message表示要记录的消息。filename参数指定日志文件的名称,filemode参数定义日志写入模式,例如'w'表示写入模式,'a'表示追加模式。 3. 记录日志: ```python logging.debug('Debug message') logging.info('Info message') logging.warning('Warning message') logging.error('Error message') logging.critical('Critical message') ``` 使用logging模块的不同方法来记录不同级别的日志。 4. 进一步配置日志记录器: ```python logger = logging.getLogger('my_logger') logger.setLevel(logging.DEBUG) ``` 如果需要更多的配置选项,可以创建一个logger对象,并使用setLevel方法设置日志级别。 通过这些步骤,可以在程序使用logging模块记录日志。这样,可以根据需要记录不同级别的日志,并通过指定的格式将日志写入到文件。日志记录对于程序的调试和问题排查非常有帮助。 ### 回答3: Pythonlogging模块是一个内置的日志记录工具。它提供了一种简单而灵活的方式来记录运行时的信息,帮助我们调试程序和追踪错误。下面是使用logging模块的一些主要步骤: 1. 导入logging模块: ```python import logging ``` 2. 设置日志记录的级别: ```python logging.basicConfig(level=logging.DEBUG) ``` 这里设置的是日志记录的最低级别为DEBUG,即记录所有级别的日志信息。还有其他的级别可选择,如:INFO、WARNING、ERROR等,可以根据需要设置。 3. 编写日志信息: ```python logging.debug("This is a debug message") logging.info("This is an info message") logging.warning("This is a warning message") logging.error("This is an error message") ``` 4. 输出日志信息: 日志信息可以输出到控制台、文件或其他地方。默认情况下,日志信息会输出到控制台。 ```python logging.debug("This is a debug message") ``` 可以通过配置logging模块将日志信息输出到文件。 ```python logging.basicConfig(filename='example.log', level=logging.DEBUG) ``` 这里将日志信息输出到文件"example.log"。 以上是使用logging模块的基本步骤。logging模块还支持更高级的用法,如添加时间戳、设置日志的格式等。可以通过查阅官方文档来了解更多关于logging模块的详细信息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值