python logging使用

1.簡單使用:python

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.配置使用json

除了能夠在root.log裏輸出,與此同時還能在rootjson.log裏以json格式輸出。debug

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配置orm

#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')
相關文章
相關標籤/搜索