一個添加日志處理模塊的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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM