logging日志模块

logging模块是用来写日志的模块

1. 模块本质的使用流程:

# 创建一个logger对象
# 创建一个文件操作符(用来存储日志信息)
# 创建一个屏幕操作符(用来在屏幕打印信息)
# 创建一个格式(要写的日志或屏幕显示内容的格式:是否带有文件名或日期等)
 
# 给logger对象绑定 文件操作符
# 给logger对象绑定 屏幕操作符 
# 给文件操作符 设定格式
# 给屏幕操作符 设定格式
 
# 用logger对象来操作

 

示例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import logging

logger = logging.getLogger() # 创建一个logger对象
fh = logging.FileHandler("log.log") # 创建一个文件操作符
sh = logging.StreamHandler() # 创建一个屏幕操作符
fm = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # 创建一个格式

logger.addHandler(fh) # 给logger对象绑定 文件操作符
logger.addHandler(sh) # 给logger对象绑定 屏幕操作符
fh.setFormatter(fm) # 给文件操作符绑定 格式
sh.setFormatter(fm) # 给屏幕操作符绑定 格式

logger.error("出错了") # 输出错误信息
# logger.error("出错了",exc_info=True) # 输出错误信息,如果exc_info为True,在真正的出错日志记录中将保留详细的堆栈信息,下面有示例

输出结果:

2019-11-03 17:20:59,569 - root - ERROR - 出错了

2. 使用basicConfig方法写日志

示例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging

file_handler = logging.FileHandler(filename='x1.log',mode='a',encoding='utf-8') # 在这里定义文件名和编码格式,否则中文会显示乱码

logging.basicConfig(
    format = '%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s',
    datefmt='%Y-%m-%d %H-%M-%S %p',
    handlers=[file_handler,],
    level = logging.ERROR
)

logging.error('出错了')

输出结果:

2019-11-03 17-41-15 PM - root - ERROR - 文件名: 又出错了

  

打印所有错误信息,示例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging
import requests

file_handler = logging.FileHandler(filename='x1.log',mode='a',encoding='utf-8')
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s',
    datefmt='%Y-%m-%d %H-%M-%S %p',
    handlers=[file_handler, ],
    level=logging.ERROR
)

try:
    requests.get("http://www.xxx.com")
except Exception as e:
    msg = str(e)
    logging.error(msg,exc_info=True)
打印所有错误信息

输出结果展示:

2019-11-03 17-49-11 PM - root - ERROR - test: HTTPConnectionPool(host='www.xxx.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x03E2BD10>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。'))
Traceback (most recent call last):
  File "D:\software\python\lib\site-packages\urllib3\connection.py", line 160, in _new_conn
    (self._dns_host, self.port), self.timeout, **extra_kw)
  File "D:\software\python\lib\site-packages\urllib3\util\connection.py", line 80, in create_connection
    raise err
  File "D:\software\python\lib\site-packages\urllib3\util\connection.py", line 70, in create_connection
    sock.connect(sa)
TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\software\python\lib\site-packages\urllib3\connectionpool.py", line 603, in urlopen
    chunked=chunked)
  File "D:\software\python\lib\site-packages\urllib3\connectionpool.py", line 355, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "D:\software\python\lib\http\client.py", line 1229, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "D:\software\python\lib\http\client.py", line 1275, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "D:\software\python\lib\http\client.py", line 1224, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "D:\software\python\lib\http\client.py", line 1016, in _send_output
    self.send(msg)
  File "D:\software\python\lib\http\client.py", line 956, in send
    self.connect()
  File "D:\software\python\lib\site-packages\urllib3\connection.py", line 183, in connect
    conn = self._new_conn()
  File "D:\software\python\lib\site-packages\urllib3\connection.py", line 169, in _new_conn
    self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x03E2BD10>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\software\python\lib\site-packages\requests\adapters.py", line 449, in send
    timeout=timeout
  File "D:\software\python\lib\site-packages\urllib3\connectionpool.py", line 641, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "D:\software\python\lib\site-packages\urllib3\util\retry.py", line 399, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='www.xxx.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x03E2BD10>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:/software/pycharm/workspace/test.py", line 76, in <module>
    requests.get("http://www.xxx.com")
  File "D:\software\python\lib\site-packages\requests\api.py", line 75, in get
    return request('get', url, params=params, **kwargs)
  File "D:\software\python\lib\site-packages\requests\api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "D:\software\python\lib\site-packages\requests\sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "D:\software\python\lib\site-packages\requests\sessions.py", line 646, in send
    r = adapter.send(request, **kwargs)
  File "D:\software\python\lib\site-packages\requests\adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='www.xxx.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x03E2BD10>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。'))
2019-11-03 17-51-34 PM - root - ERROR - test: HTTPConnectionPool(host='www.xxx.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x03D2BC70>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。'))
Traceback (most recent call last):
  File "D:\software\python\lib\site-packages\urllib3\connection.py", line 160, in _new_conn
    (self._dns_host, self.port), self.timeout, **extra_kw)
  File "D:\software\python\lib\site-packages\urllib3\util\connection.py", line 80, in create_connection
    raise err
  File "D:\software\python\lib\site-packages\urllib3\util\connection.py", line 70, in create_connection
    sock.connect(sa)
TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\software\python\lib\site-packages\urllib3\connectionpool.py", line 603, in urlopen
    chunked=chunked)
  File "D:\software\python\lib\site-packages\urllib3\connectionpool.py", line 355, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "D:\software\python\lib\http\client.py", line 1229, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "D:\software\python\lib\http\client.py", line 1275, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "D:\software\python\lib\http\client.py", line 1224, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "D:\software\python\lib\http\client.py", line 1016, in _send_output
    self.send(msg)
  File "D:\software\python\lib\http\client.py", line 956, in send
    self.connect()
  File "D:\software\python\lib\site-packages\urllib3\connection.py", line 183, in connect
    conn = self._new_conn()
  File "D:\software\python\lib\site-packages\urllib3\connection.py", line 169, in _new_conn
    self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x03D2BC70>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\software\python\lib\site-packages\requests\adapters.py", line 449, in send
    timeout=timeout
  File "D:\software\python\lib\site-packages\urllib3\connectionpool.py", line 641, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "D:\software\python\lib\site-packages\urllib3\util\retry.py", line 399, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='www.xxx.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x03D2BC70>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:/software/pycharm/workspace/test.py", line 76, in <module>
    requests.get("http://www.xxx.com")
  File "D:\software\python\lib\site-packages\requests\api.py", line 75, in get
    return request('get', url, params=params, **kwargs)
  File "D:\software\python\lib\site-packages\requests\api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "D:\software\python\lib\site-packages\requests\sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "D:\software\python\lib\site-packages\requests\sessions.py", line 646, in send
    r = adapter.send(request, **kwargs)
  File "D:\software\python\lib\site-packages\requests\adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='www.xxx.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x03D2BC70>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。'))
结果展示

 

其它日志使用方法:

通过fileConfig()配置日志:https://blog.csdn.net/qq_34182808/article/details/100735895

配置日志的几种方式:https://blog.csdn.net/yy19890521/article/details/80990175

posted @ 2019-11-03 17:53  无夜。  阅读(277)  评论(0编辑  收藏  举报