Python标准模块logging
2014-01-03 16:28
218 查看
#!/usr/bin/python #coding:utf-8 import logging import time def log(error_msg): #获取时间 fm = '%Y-%m-%d %H:%M:%S' YMD = time.strftime(fm,time.localtime()) #设置文件的存储路径,及文件 save_log_file = 'error.log' # 第一步创建一个logger的句柄 logger = logging.getLogger('error') #创建一个处理写入日志文件的handler,参数保存的"日志文件 handler = logging.FileHandler(save_log_file) #设置日志输出的格式 formatter = logging.Formatter("%(asctime)s-%(levelname)s-%(message)s") handler.setFormatter(formatter) #将处理文件的的handler假如到logger中去 logger.addHandler(handler) # Logging有如下级别: DEBUG,INFO,WARNING,ERROR,CRITICAL # 默认级别是WARNING, logging模块只会输出指定level以上的log # 这样的好处, 就是在项目开发时debug用的log, 在产品release阶段不用一一注释, # 只需要调整logger的级别就可以了, 很方便的. logger.setLevel(logging.INFO) #写入日志 logger.info(error_msg) #其他的写入方法 logger.debug(error_msg) logger.warn(error_msg) logger.error(error_msg) logger.critical(error_msg) logger.removeHandler(handler) if __name__ == '__main__': log_info = '传入日志信息' log(log_info)
GetLogger
GetLogger() returns a reference to a logger instance with the specified name if it is provided, or root if not. The names are period-separated hierarchical structures. Multiple calls to getLogger() with the same name will return a reference to the same logger
object.
后面会看到这种以'.'分隔的hierarchical structures有什么用.
Formatter
Formatter对象定义了最终log信息的顺序,结构和内容, 后面会详细解释.
Handler
这儿用到了StreamHandler和FileHandler, 用于向不同的输出端打log.
SetLevel
Logging有如下级别: DEBUG,INFO,WARNING,ERROR,CRITICAL
默认级别是WARNING, logging模块只会输出指定level以上的log
这样的好处, 就是在项目开发时debug用的log, 在产品release阶段不用一一注释, 只需要调整logger的级别就可以了, 很方便的.
Formatter
Formatter对象定义了最终log信息的顺序,结构和内容.于基本的logging.Handler类不同,应用可以直接实例化formatter类,当然,如果需要你也可以子例化formatter以便定制它的一些行为.构造函数接受两个可选参数:一个信息格式字符串和一个日期格式字符串.如果没有信息格式字符串,直接输出log信息.如果没有日期格式字符串,默认的格式是:%Y-%m-%d %H:%M:%S
相关文章推荐
- Python标准模块logging
- Python标准模块logging
- Python标准模块logging2
- Python标准模块logging
- Python标准模块logging
- 【转】Python标准模块logging
- Python标准模块logging
- Python标准模块logging(转)
- 【python】python标准模块logging
- Python标准模块logging
- Python标准模块--logging
- 使用Python的logging.config
- Python日志输出——logging模块
- python改变日志(logging)存放位置的示例
- 使用python的logging模块
- python--logging
- Python logging模块详解
- Python 模块学习 logging
- Python标准模块--asyncio
- Python日志输出——logging模块