{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# logging 模块:记录日志" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`logging` 模块可以用来记录日志:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import logging" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`logging` 的日志类型有以下几种:\n", "\n", "- `logging.critical(msg)`\n", "- `logging.error(msg)`\n", "- `logging.warning(msg)`\n", "- `logging.info(msg)`\n", "- `logging.debug(msg)`\n", "\n", "级别排序为:`CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET`\n", "\n", "默认情况下,`logging` 的日志级别为 `WARNING`,只有不低于 `WARNING` 级别的日志才会显示在命令行。" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "CRITICAL:root:This is critical message\n", "ERROR:root:This is error message\n", "WARNING:root:This is warning message\n" ] } ], "source": [ "logging.critical('This is critical message')\n", "logging.error('This is error message')\n", "logging.warning('This is warning message')\n", "\n", "# 不会显示\n", "logging.info('This is info message')\n", "logging.debug('This is debug message')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "可以这样修改默认的日志级别:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "INFO:root:This is info message\n" ] } ], "source": [ "logging.root.setLevel(level=logging.INFO)\n", "\n", "logging.info('This is info message')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "可以通过 `logging.basicConfig()` 函数来改变默认的日志显示方式:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "CRITICAL:this program:This is critical message\n" ] } ], "source": [ "logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s')\n", "\n", "logger = logging.getLogger(\"this program\")\n", "\n", "logger.critical('This is critical message')" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.6" } }, "nbformat": 4, "nbformat_minor": 0 }