A python instance of adding log processing module

Keywords: JSON encoding github Python

The log module is essential in a complete project. When encountering system error in work, it is also the first time to check the error log on the server (ps. even if you can't understand it, you will copy the error part as a bug attachment)

Here is an example of using weather interface API to query weather. Let's talk about how to add log module in python

Preparation

Because this time we call a weather query interface, we need to find a website that provides free query first

Click in any website to find out that many websites provide free personal inquiry, and you can choose any one
I chose "weather query API website": https://www.tianqiapi.com/index

You need to register an account first, and then check the "free live weather API document" to learn how to use it. I won't talk about it here (it's quite simple, just call the next interface according to the API document)

Project code structure

A simple directory structure is as follows

logger.py in the utils directory is the code to add the log module

# 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)
​
​
#Create a logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
​
#Create a handler,For writing log files
log_path = os.path.dirname(get_path.get_cwd())+"/logs/" # Specify the file output path, note logs It's a folder. It must be added/,Otherwise, the output path will be wrong logs It's part of the file name
logname = log_path + 'out.log' #Specify the log file name for the output
fh = logging.FileHandler(logname,encoding = 'utf-8')  # Appoint utf-8 Format coding to avoid the output log text garbled
fh.setLevel(logging.DEBUG)  # Set the minimum severity of log messages that the logger will process to DEBUG
#Create a handler,Used to output logs to the console
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
​
# Definition handler Output format of
formatter = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
​
# to logger Add to handler
logger.addHandler(fh)
logger.addHandler(ch)
​
​
if __name__ == '__main__':
    logger.debug("User %s is loging" % 'admin')

Then call the log module in 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:
            """Read weather interface profile"""
            self.weather_api = yaml.load(self.weather_api_file, Loader=yaml.FullLoader)  # self.config_data Data representing the profile
        # print(self.weather_api)
        # print(type(self.weather_api))
​
        with open(get_path()+"/data/city.json", "r", encoding="utf-8") as self.city_file:
            """Read city data file"""
            self.city_data = json.load(self.city_file)
        # print(self.city_data)
        # print(type(self.city_data))
# Call request information for live weather
        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):
        """Query live weather (1 day)"""
​
        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)  # Call log module
            except Exception as e:
                print("Request failed with error message %d", e)
​
    def main(self):
        self.live_dates_weather(city="Beijing")
​
​
​
if __name__ == '__main__':
    t = QueryWeather()
    t.main()

out.log in the logs directory is the log output file
Run it and you will see that the log is written in it

GitHub portal:

https://github.com/Archerhhh/everyday_weather

Posted by carmasha on Mon, 13 Apr 2020 07:07:36 -0700