Skip to content

日志

https://docs.python.org/zh-cn/3.7/library/logging.html

logging 模块提供了灵活的记录事件、错误、警告和调试信息等日志信息的功能

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import logging

logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)s | %(message)s")
logger = logging.getLogger()

logger.info("hhh")
logger.debug("233")
logger.error("err")

# 2020-11-11 14:44:55,947 | INFO | hhh
# 2020-11-11 14:44:55,947 | ERROR | err

loguru

https://github.com/Delgan/loguru

https://loguru.readthedocs.io/en/stable/api/logger.html

https://zhuanlan.zhihu.com/p/93712428

https://zhuanlan.zhihu.com/p/335843386

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
logger.add('runtime_{time}.log', rotation="500 MB")

# 每天 0 点新创建一个 log 文件进行输出
logger.add('runtime_{time}.log', rotation='00:00')

# 一周创建一个 log 文件
logger.add('runtime_{time}.log', rotation='1 week')

# 保留最新 10 天的 log
logger.add('runtime.log', retention='10 days')
1
2
3
4
5
6
7
8
from loguru import logger

@logger.catch
def my_function(x, y, z):
    # An error? It's caught anyway!
    return 1 / (x + y + z)

my_function(0, 0, 0)

输出:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
2021-03-18 13:25:28.864 | ERROR    | __main__:<module>:8 - An error has been caught in function '<module>', process 'MainProcess' (67701), thread 'MainThread' (4606336512):
Traceback (most recent call last):

> File "test_log.py", line 8, in <module>
    my_function(0, 0, 0)
    └ <function my_function at 0x7f9c2bab6158>

  File "test_log.py", line 6, in my_function
    return 1 / (x + y + z)
                │   │   └ 0
                │   └ 0
                └ 0

ZeroDivisionError: division by zero

设置 level

默认 level 为 DEBUG,可以添加日志文件时设置为 level

如下所示:

1
2
3
4
5
6
7
from loguru import logger

logger.add('test_{time}.log', level="INFO")


logger.debug("hhh")
logger.info("test info")

可以看到文件内容:

1
2021-03-30 15:39:01.687 | INFO     | __main__:<module>:7 - test info

只有 info 内容