python?import?logging問題
創(chuàng)建日志類并使用
如何使用python自帶的 logging 模塊實(shí)現(xiàn)日志功能
1.初始化一個(gè)logger對(duì)象
1)引入模塊
import os import logging import sys
2)初始化變量,聲明logger對(duì)象
LOG_PATH = 'logs' ? #設(shè)置log路徑 LOG_FILE = 'text.txt' ? ?#設(shè)置log文件名 #設(shè)置根路徑為起始位置 logger = logging.getLogger(__name__)
3)生成路徑
#生成log指定路徑 if os.path.exists(LOG_PATH): ? ? pass else: ? ? os.mkdir(LOG_PATH)
4)指定logger輸出格式
? ? formatter = logging.Formatter('%(asctime)s %(levelname)-8s: %(message)s') ? ? file_handler = logging.FileHandler("%s/%s" % (LOG_PATH, LOG_FILE)) ? ? # 可以通過setFormatter指定輸出格式 ? ? file_handler.setFormatter(formatter) ? ? logger.addHandler(file_handler)
5)指定日志文件的輸出級(jí)別
分為如下幾個(gè)級(jí)別:
_nameToLevel = { ? ? 'CRITICAL': CRITICAL, ? ? 'FATAL': FATAL, ? ? 'ERROR': ERROR, ? ? 'WARN': WARNING, ? ? 'WARNING': WARNING, ? ? 'INFO': INFO, ? ? 'DEBUG': DEBUG, ? ? 'NOTSET': NOTSET, }?
使用setLevel函數(shù)指定輸出級(jí)別 指定之后將只顯示級(jí)別以上的日志類型
logger.setLevel(logging.DEBUG)
2.輸入日志內(nèi)容
#輸出debug類型日志 logger.debug("debug") #多參數(shù)傳遞 ?輸入info類型日志 pam= "dshck" pam2="cxjkdhc" logger.info("%s%s"%(pam,pam2))
log.py 代碼如下
import os import logging from logging.handlers import TimedRotatingFileHandler import datetime import json LOG_PATH = "log" LOG_INFO = '_info.log' LOG_ERROR = '_error.log' class logger: ? ? def __init__(self,prefix_name = "flask"): ? ? ? ? if os.path.exists(LOG_PATH): ? ? ? ? ? ? pass ? ? ? ? else: ? ? ? ? ? ? os.mkdir(LOG_PATH) ? ? ? ? self.prefix = prefix_name ? ? ? ? self.info_logger = logging.getLogger("info") ? ? ? ? self.error_logger = logging.getLogger("error") ? ? ? ? self.format = logging.Formatter('[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s]\ [%(filename)s:%(lineno)d]' '[%(levelname)s] : %(message)s') ? ? ? ? #指定文件位置文件名以及輸出格式 ? ? ? ? info_file_handler = logging.FileHandler("%s/%s%s" % (LOG_PATH, prefix_name,LOG_INFO)) ? ? ? ? info_file_handler.setFormatter(self.format) ? ? ? ? error_file_handler = logging.FileHandler("%s/%s%s" % (LOG_PATH, prefix_name,LOG_ERROR)) ? ? ? ? error_file_handler.setFormatter(self.format) ? ? ? ? self.info_logger.addHandler(info_file_handler) ? ? ? ? self.error_logger.addHandler(error_file_handler) ? ? ? ? # 指定日志的最低輸出級(jí)別 ? ? ? ? self.info_logger.setLevel(logging.NOTSET) ? ? ? ? self.error_logger.setLevel(logging.ERROR) ? ? def debug(self, msg, *args, **kwargs): ? ? ? ? self.info_logger.debug(msg, *args, **kwargs) ? ? def info(self, msg, *args, **kwargs): ? ? ? ? self.info_logger.info(msg, *args, **kwargs) ? ? def warn(self, msg, *args, **kwargs): ? ? ? ? self.info_logger.warning(msg, *args, **kwargs) ? ? def warning(self, msg, *args, **kwargs): ? ? ? ? self.info_logger.warning(msg, *args, **kwargs) ? ? def error(self, msg, *args, **kwargs): ? ? ? ? self.error_logger.error(msg, *args, **kwargs) ? ? def fatal(self, msg, *args, **kwargs): ? ? ? ? self.error_logger.fatal(msg, *args, **kwargs) ? ? def critical(self, msg, *args, **kwargs): ? ? ? ? self.error_logger.critical(msg, *args, **kwargs) # log =logger() # log.info("jdshskh") # log.error("hdskck") # log.debug("1122debug") # log.warn("warn") # log.warning("warning") # log.critical("critical") # log.fatal("fatal") log =logger("celery") log.info("jdshskh") log.error("hdskck") log.debug("1122debug") log.warn("warn") log.warning("warning") log.critical("critical") log.fatal("fatal")
python3 import logging報(bào)錯(cuò):RecursionError: maximum recursion depth exceeded while calling a Python
python3不用import logging,因?yàn)閘ogging已經(jīng)內(nèi)置了。
參考:https://stackoverflow.com/questions/32386469/logging-module-not-working-with-python3
報(bào)錯(cuò):RecursionError: maximum recursion depth exceeded while calling a Python object
# python3 運(yùn)行 import logging報(bào)錯(cuò)
Traceback (most recent call last):
File "/home/xxx/folder1/utee/misc.py", line 32, in info
self.init('/tmp', 'tmp.log')
File "/home/xxx/folder1/utee/misc.py", line 22, in init
print(log_file)
File "/home/xxx/folder1/utee/misc.py", line 32, in info
self.init('/tmp', 'tmp.log')
...
File "/home/xxx/folder1/utee/misc.py", line 32, in info
self.init('/tmp', 'tmp.log')
File "/home/xxx/folder1/utee/misc.py", line 17, in init
import logging
RecursionError: maximum recursion depth exceeded while calling a Python object
python3 pip3 安裝 logging報(bào)錯(cuò):
url: /simple/logging/ (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)'),))
$ sudo -H pip3 --proxy=xx.xxx.xx.xxx:8080 install logging
# 報(bào)錯(cuò)內(nèi)容:SSL報(bào)錯(cuò)。
Collecting logging
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)'),)': /simple/logging/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)'),)': /simple/logging/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)'),)': /simple/logging/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)'),)': /simple/logging/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)'),)': /simple/logging/
Could not fetch URL https://pypi.org/simple/logging/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/logging/ (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)'),)) - skipping
ERROR: Could not find a version that satisfies the requirement logging (from versions: none)
ERROR: No matching distribution found for logging
# 解決:設(shè)置可信的域名。 (--trusted-host pypi.org --trusted-host files.pythonhosted.org)
$ sudo -H pip3 --proxy=xx.xxx.xx.xxx:8080 --trusted-host pypi.org --trusted-host files.pythonhosted.org install logging
還是報(bào)錯(cuò): raise NotImplementedError, 'emit must be implemented '\
# 報(bào)錯(cuò)內(nèi)容
Collecting logging
Downloading https://files.pythonhosted.org/packages/93/4b/979db9e44be09f71e85c9c8cfc42f258adfb7d93ce01deed2788b2948919/logging-0.4.9.6.tar.gz (96kB)
|????????????????????????????????????????????????????????????????| 102kB 529kB/s
ERROR: Command errored out with exit status 1:
command: /usr/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-u8g87k38/logging/setup.py'"'"'; __file__='"'"'/tmp/pip-install-u8g87k38/logging/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info
cwd: /tmp/pip-install-u8g87k38/logging/
Complete output (44 lines):
running egg_info
creating pip-egg-info/logging.egg-info
writing pip-egg-info/logging.egg-info/PKG-INFO
writing dependency_links to pip-egg-info/logging.egg-info/dependency_links.txt
writing top-level names to pip-egg-info/logging.egg-info/top_level.txt
writing manifest file 'pip-egg-info/logging.egg-info/SOURCES.txt'
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-install-u8g87k38/logging/setup.py", line 13, in <module>
packages = ["logging"],
File "/usr/lib/python3.5/distutils/core.py", line 148, in setup
dist.run_commands()
File "/usr/lib/python3.5/distutils/dist.py", line 955, in run_commands
self.run_command(cmd)
File "/usr/lib/python3.5/distutils/dist.py", line 974, in run_command
cmd_obj.run()
File "/usr/local/lib/python3.5/dist-packages/setuptools-19.6-py3.5.egg/setuptools/command/egg_info.py", line 186, in run
File "/usr/local/lib/python3.5/dist-packages/setuptools-19.6-py3.5.egg/setuptools/command/egg_info.py", line 209, in find_sources
File "/usr/local/lib/python3.5/dist-packages/setuptools-19.6-py3.5.egg/setuptools/command/egg_info.py", line 293, in run
File "/usr/local/lib/python3.5/dist-packages/setuptools-19.6-py3.5.egg/setuptools/command/egg_info.py", line 322, in add_defaults
File "/usr/local/lib/python3.5/dist-packages/setuptools-19.6-py3.5.egg/setuptools/command/sdist.py", line 120, in add_defaults
File "/usr/lib/python3.5/distutils/cmd.py", line 298, in get_finalized_command
cmd_obj = self.distribution.get_command_obj(command, create)
File "/usr/lib/python3.5/distutils/dist.py", line 846, in get_command_obj
klass = self.get_command_class(command)
File "/usr/local/lib/python3.5/dist-packages/setuptools-19.6-py3.5.egg/setuptools/dist.py", line 430, in get_command_class
File "/usr/local/lib/python3.5/dist-packages/setuptools-19.6-py3.5.egg/pkg_resources/__init__.py", line 2370, in load
File "/usr/local/lib/python3.5/dist-packages/setuptools-19.6-py3.5.egg/pkg_resources/__init__.py", line 2376, in resolve
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 664, in _load_unlocked
File "<frozen importlib._bootstrap>", line 634, in _load_backward_compatible
File "/usr/local/lib/python3.5/dist-packages/setuptools-19.6-py3.5.egg/setuptools/command/build_py.py", line 15, in <module>
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 664, in _load_unlocked
File "<frozen importlib._bootstrap>", line 634, in _load_backward_compatible
File "/usr/local/lib/python3.5/dist-packages/setuptools-19.6-py3.5.egg/setuptools/lib2to3_ex.py", line 12, in <module>
File "/usr/lib/python3.5/lib2to3/refactor.py", line 19, in <module>
import logging
File "/tmp/pip-install-u8g87k38/logging/logging/__init__.py", line 618
raise NotImplementedError, 'emit must be implemented '\
^
SyntaxError: invalid syntax
----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章

pytorch查看torch.Tensor和model是否在CUDA上的實(shí)例

python+pygame簡(jiǎn)單畫板實(shí)現(xiàn)代碼實(shí)例

通過5個(gè)例子讓你學(xué)會(huì)Pandas中的字符串過濾

pygame實(shí)現(xiàn)俄羅斯方塊游戲(基礎(chǔ)篇2)

Python數(shù)據(jù)分析:手把手教你用Pandas生成可視化圖表的教程