python logging使用

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')

转载于:https://my.oschina.net/u/3316387/blog/3000057

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值