几种不同的级别(信息的重要性依次递增)
- DEBUG
- INFO
- WARNING
- ERROR
- CRITICAL
基本用法(Python代码)
import logging
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')
logging.critical('This is a critical message')
输入的消息(引号部分)将在终端输出。默认情况下输出WARNING及以上级别的信息。
WARNING:root:This is a warning message
ERROR:root:This is an error message
CRITICAL:root:This is a critical message
基本配置
一个简单的例子——修改日志信息级别
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('This will get logged')
终端输出
DEBUG:root:This will get logged
basicConfig中可以配置的内容
-level: The root logger will be set to the specified severity level. 设置安全级别
-filename: This specifies the file. 日志文件名
-filemode: If filename is given, the file is opened in this mode. The default is a, which means append. 文件的打开模式,默认是a
-format: This is the format of the log message. 日志内容的输出格式
另一个例子——将日志信息输出到文件中
import logging
logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
logging.warning('This will get logged to a file')
上面的例子把日志信息写入文件app.log;写入模式是'w',意味着每次调用覆盖app.log中的原有信息;format指定了输出的日志信息的格式。logging.basicConfig只需要调用一次即可。
格式化输出
import logging
logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)
logging.info('Admin logged in')
2018-07-11 20:12:06,288 - Admin logged in
import logging
logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')
logging.warning('Admin logged out')
12-Jul-18 20:53:19 - Admin logged out
import logging
name = 'John'
logging.error(f'{name} raised an error')
ERROR:root:John raised an error
网友评论