23 lines
843 B
Python
23 lines
843 B
Python
import logging
|
||
from logging.handlers import RotatingFileHandler
|
||
|
||
# 创建一个logger
|
||
logger = logging.getLogger('my_logger')
|
||
logger.setLevel(logging.INFO) # 可以根据需要设置为DEBUG, ERROR, WARNING等
|
||
|
||
# 创建一个handler,用于写入日志文件
|
||
file_handler = RotatingFileHandler('app.log', maxBytes=1024*1024*5, backupCount=5)
|
||
file_handler.setLevel(logging.INFO)
|
||
|
||
# 创建一个handler,用于将日志输出到控制台
|
||
stream_handler = logging.StreamHandler()
|
||
stream_handler.setLevel(logging.ERROR) # 只输出error级别的到控制台
|
||
|
||
# 定义handler的输出格式
|
||
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||
file_handler.setFormatter(formatter)
|
||
stream_handler.setFormatter(formatter)
|
||
|
||
# 给logger添加handler
|
||
logger.addHandler(file_handler)
|
||
logger.addHandler(stream_handler) |