一个添加日志处理模块的python实例

日志模块在一个完整项目中必不可少,平时在工作中遇到系统报错等,也是首先到服务器查看报错日志(ps.即使看不懂,也会把报错部分copy出来当做bug附件)

下面通过一个调用天气接口API查询天气的例子,来说一下如何在python中添加日志模块

准备工作

因为这次是调用一个查询天气接口,所以需要先找个提供免费查询的网站

随便点进去一个可以发现很多网站都提供个人免费查询,任意选一个即可
我选择了『天气查询API网站』:https://www.tianqiapi.com/index

要先注册一个账号,然后查阅下『免费实况天气API文档』,学会如何使用,这里不展开讲了(这个挺简单,根据api文档调用下接口就成)

项目代码结构

一个简单的目录结构如下

utils目录中的 logger.py 是添加日志模块的代码

# coding: utf-8
import logging
import os
from everyday_wether.utils import get_path
​
​
log_path = os.path.dirname(get_path.get_cwd())
print(log_path)
​
​
#创建一个logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
​
#创建一个handler,用于写入日志文件
log_path = os.path.dirname(get_path.get_cwd())+"/logs/" # 指定文件输出路径,注意logs是个文件夹,一定要加上/,不然会导致输出路径错误,把logs变成文件名的一部分了
logname = log_path + 'out.log' #指定输出的日志文件名
fh = logging.FileHandler(logname,encoding = 'utf-8')  # 指定utf-8格式编码,避免输出的日志文本乱码
fh.setLevel(logging.DEBUG)  # 设置日志器将会处理的日志消息的最低严重级别,设置为DEBUG
#创建一个handler,用于将日志输出到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
​
# 定义handler的输出格式
formatter = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
​
# 给logger添加handler
logger.addHandler(fh)
logger.addHandler(ch)
​
​
if __name__ == '__main__':
    logger.debug("User %s is loging" % 'admin')

然后在 query_weather.py 中调用日志模块

# coding: utf-8
# author: hmk
import requests
import json
import yaml
from everyday_wether.utils.get_path import get_path
from everyday_wether.utils.logger import logger
​
class QueryWeather:
    def __init__(self):
​
        with open(get_path()+"/data/weather_api.yaml", "r", encoding="utf-8") as self.weather_api_file:
            """读取天气接口配置文件"""
            self.weather_api = yaml.load(self.weather_api_file, Loader=yaml.FullLoader)  # self.config_data表示配置文件的数据
        # print(self.weather_api)
        # print(type(self.weather_api))
​
        with open(get_path()+"/data/city.json", "r", encoding="utf-8") as self.city_file:
            """读取城市数据文件"""
            self.city_data = json.load(self.city_file)
        # print(self.city_data)
        # print(type(self.city_data))
# 调用实况天气的请求信息
        self.live_dates_weather_url = self.weather_api["live_dates_weather"]["url"]
        self.live_dates_weather_payload = self.weather_api["live_dates_weather"]["payload"]
​
​
    def live_dates_weather(self, city_id=None, city=None):
        """查询实况天气(1天)"""
​
        payload = self.live_dates_weather_payload
        payload["cityid"] = city_id
        payload["city"] = city
​
        response = requests.get(self.live_dates_weather_url, params=payload)
​
        if response.status_code == 200:
            data = response.json()
            try:
                print(data)
                logger.debug(data)  # 调用日志模块
            except Exception as e:
                print("请求失败,错误信息为 %d", e)
​
    def main(self):
        self.live_dates_weather(city="北京")
​
​
​
if __name__ == '__main__':
    t = QueryWeather()
    t.main()

logs目录下的out.log是日志输出文件 
运行一下,会看到里面写入了日志

GitHub传送门:

https://github.com/Archerhhh/everyday_weather

猜你喜欢

转载自www.cnblogs.com/hanmk/p/12511453.html