Python日志模块-Logging的应用

Python日志模块-Logging的应用

1 代码示例

代码仓库:OnlyAR/Logger (github.com)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# @Author : Only(AR)
# @File : logger.py

import logging
import os

import colorlog

# 日志级别
console_level = logging.DEBUG
file_level = logging.INFO

# 日志颜色配置
log_colors_config = {
'DEBUG': 'white',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'bold_red',
}

os.chdir(os.path.dirname(os.path.abspath(__file__)))


def _get_logger():
logger = logging.getLogger('logger')
logger.setLevel(logging.DEBUG)

# 设置控制台句柄
console_handler = logging.StreamHandler()
console_formatter = colorlog.ColoredFormatter(
fmt='%(log_color)s[%(levelname)s]: %(message)s',
log_colors=log_colors_config
)
console_handler.setFormatter(console_formatter)
console_handler.setLevel(console_level)
logger.addHandler(console_handler)

# 设置文件句柄
file_handler = logging.FileHandler('log.txt', encoding='utf8')
file_formatter = logging.Formatter(
fmt='[%(asctime)s] %(filename)s -> %(funcName)s line:%(lineno)d [%(levelname)s]: %(message)s',
)
file_handler.setFormatter(file_formatter)
file_handler.setLevel(file_level)
logger.addHandler(file_handler)
return logger


logger = _get_logger()

2 日志的终极解决方案:Loguru

后来我在项目中发现了更好用的开源日志库Delgan/loguru,安装命令:

1
pip install loguru

2.1 简单使用方法:

  • 打印日志
1
2
3
4
5
6
from loguru import logger

logger.debug("This is a debug")
logger.info("This is an info")
logger.warning("This is a warring")
logger.error("This is an error")
1
2
3
4
2023-07-25 15:37:00.217 | DEBUG    | __main__:<module>:3 - This is a debug
2023-07-25 15:37:00.217 | INFO | __main__:<module>:4 - This is an info
2023-07-25 15:37:00.217 | WARNING | __main__:<module>:5 - This is a warring
2023-07-25 15:37:00.217 | ERROR | __main__:<module>:6 - This is an error
  • 添加输出文件
1
2
3
from loguru import logger

logger.add("log.txt")
  • 移出输出文件
1
2
3
4
from loguru import logger

log = logger.add("log.txt")
logger.remove(log)

Python日志模块-Logging的应用
https://onlyar.site/2023/03/28/python-logger/
作者
Only(AR)
发布于
2023年3月28日
许可协议