1.简单使用:
import logging
# 通过下面的方式进行简单配置输出方式与日志级别 logging.basicConfig(filename='root.log', level=logging.INFO)
logging.debug('debug message') logging.info('info message') logging.warn('warn message') logging.error('error message') logging.critical('critical message')
2.配置使用
除了可以在root.log里输出,与此同时还能在rootjson.log里以json格式输出。
test.py:
import os import logging import logging.config from pythonjsonlogger import jsonlogger # 日志配置及将日志json格式化 def json_formatter(): log_format_keys = ['asctime', 'created', 'levelname', 'filename', 'lineno', 'module', 'message', 'name', 'pathname', 'process', 'processName', 'thread', 'threadName'] log_format = lambda x: ['%({0:s})'.format(i) for i in x] custom_format = ' '.join(log_format(log_format_keys)) log_json_format = jsonlogger.JsonFormatter(custom_format) return log_json_format # 配置文件路径 Logger_Conf_Path = '/Users/t/python/xxx/etc/logging.conf' logging.config.fileConfig(Logger_Conf_Path, disable_existing_loggers=False) # 设置一个格式化器formatter rootjson_logger = logging.getLogger("rootjson") rootjson_logger.handlers[0].setFormatter(json_formatter()) # 为root_logger实例增加一个处理器 root_logger = logging.getLogger("root") root_logger.addHandler(rootjson_logger.handlers[0]) root_logger.info('aaaa')
logging.conf配置
#logger.conf ############################################### [loggers] keys=root, rootjson [logger_root] level=INFO qualname=root handlers=roothand [logger_rootjson] level=INFO qualname=rootjson handlers=rootjsonhand propagate=0 ############################################### [handlers] keys=roothand, rootjsonhand [handler_roothand] class=handlers.WatchedFileHandler level=INFO formatter=commform args=('/Users/t/python/xxx/log/root.log', 'a') [handler_rootjsonhand] class=handlers.WatchedFileHandler level=INFO formatter=commform args=('/Users/t/python/xxx/log/rootjson.log', 'a')