今天就跟大家聊聊有关如何学习Python logging源码,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

1、基本使用

import logging

# logging 日志配置

logging.basicConfig(filename='exampe.log',level=logging.DEBUG)

logging.debug("helloworld - debug")

logging.info('hello info')

logging.warning('hello warning')

logging.error('hello error')logging.critical('hello critical')

2、文件存储与日志打印

import logging

# create logger

logger = logging.getLogger('simple_example')

logger.setLevel(logging.DEBUG)

# create console handler and set level to debug

ch = logging.StreamHandler()

ch.setLevel(logging.DEBUG)

fl = logging.FileHandler('app.log')

fl.setLevel(logging.DEBUG)

# create formatter

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch

ch.setFormatter(formatter)

fl.setFormatter(formatter)

# add ch to logger

logger.addHandler(ch)

logger.addHandler(fl)

# 'application' code

logger.debug('debug message')

logger.info('info message')

logger.warning('warn message')

logger.error('error message')

logger.critical('critical message')

3、API

import requests

import logging

logging.basicConfig(format='%(levelname)s %(asctime)s %(message)s',level=logging.DEBUG)

base_url = "http://39.107.96.138:3000/api/v1/"

testdata = {

"accesstoken":"49b2e830-4305-475d-b6b5-52287

cc5daaa",

"title":"2313131231231232",

"tab":"ask",

"content":"xxxxxxxxxxxxx"

}

def test_new_topic():

"""

测试发布话题

:return:

"""

url = base_url+'topics'

logging.info(f"开始发送Post请求{url},请求数据为{str(testdata)}")

r = requests.post(url,json=testdata)

jsonData = r.json()

logging.info(f'发送请求完成,结果为{str(jsonData)}')

assert r.status_code == 200

assert jsonData['success']

logging.info(f"test_new_topic, topicid: {jsonData['topic_

id']}")

assert jsonData['topic_id'] is not None

return jsonData['topic_id']

看完上述内容,你们对如何学习Python logging源码有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。