python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python import logging

python import logging问题

作者:IT小海豚

这篇文章主要介绍了python import logging问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

创建日志类并使用

如何使用python自带的 logging 模块实现日志功能

1.初始化一个logger对象

1)引入模块

import os
import logging
import sys

2)初始化变量,声明logger对象

LOG_PATH = 'logs'   #设置log路径
LOG_FILE = 'text.txt'    #设置log文件名
#设置根路径为起始位置
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)指定日志文件的输出级别

分为如下几个级别:

_nameToLevel = {
    'CRITICAL': CRITICAL,
    'FATAL': FATAL,
    'ERROR': ERROR,
    'WARN': WARNING,
    'WARNING': WARNING,
    'INFO': INFO,
    'DEBUG': DEBUG,
    'NOTSET': NOTSET,
} 

使用setLevel函数指定输出级别 指定之后将只显示级别以上的日志类型

logger.setLevel(logging.DEBUG)

2.输入日志内容

#输出debug类型日志
logger.debug("debug")
#多参数传递  输入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)
        # 指定日志的最低输出级别
        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报错:RecursionError: maximum recursion depth exceeded while calling a Python

python3不用import logging,因为logging已经内置了。

参考:https://stackoverflow.com/questions/32386469/logging-module-not-working-with-python3

报错:RecursionError: maximum recursion depth exceeded while calling a Python object

# python3 运行 import logging报错

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报错:

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

# 报错内容:SSL报错。

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

# 解决:设置可信的域名。 (--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

还是报错:  raise NotImplementedError, 'emit must be implemented '\

# 报错内容 

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.

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文